One call in the merge fails, and it's worth knowing why.
Predict
heads is (1, 2, 3, 2) and contiguous, with strides (12, 6, 2, 1). What are the strides of heads.transpose(1, 2)?
y = heads.transpose(1, 2)print(heads.stride(), y.stride())print(y.is_contiguous())
(12, 6, 2, 1) (12, 2, 6, 1)False
A stride is how far to jump in memory to take one step along an axis. The transpose swapped two strides and moved no data:
heads
y
shape
(B, H, T, d)
(B, T, H, d)
strides
(12, 6, 2, 1)
(12, 2, 6, 1)
next position
jump 2
jump 2
next head
jump 6
jump 6
The twelve numbers in memory
head 0 (1, 6)
0123450110112021
head 1 (1, 6)
678910112312132223
Memory slots are on top: head 0's six numbers, then head 1's. Position 0 of y, in green, is two runs six slots apart.
Position 0's four numbers are no longer next to each other in memory. Contiguous means the plain layout, one row after another, and y isn't.
view never copies, so it can't join numbers that sit apart. y.view(B, T, C) stops with RuntimeError: view size is not compatible with input tensor's size and stride.
reshape returns a view when it can and copies when it has to.
.contiguous().view(B, T, C) copies first, then views.
Use .reshape(B, T, C) or .contiguous().view(B, T, C). The tests pass with either.