view and reshape: Why a Transpose Cannot Always Flatten

黎 浩然/ 20 10 月, 2026/ 大语言模型/LARGELANGUAGEMODEL/LLM, 教程/TUTORIAL, 计算机/COMPUTER/ 0 comments

A view failure after transpose is not caused by a changed element count. The requested shape can require an indexing order that the existing strides cannot represent. Replacing view with reshape may solve the shape problem by copying, but cannot promise both shared storage and a copy-free path.

Contents
  1. Record strides as well as shape
  2. A one-dimensional view needs a fixed step
  3. Noncontiguous does not mean every view fails
  4. A copy changes both representation and aliasing
  5. Eight address-map checks
  6. Establish axis meaning before choosing a copy
  7. Sources and backfill note

To decide between view and reshape, first write the mapping from logical coordinates to storage positions. This example explains a transpose that cannot flatten as a view, then constructs a noncontiguous layout that can. 中文版.

Record strides as well as shape

For an ordinary strided layout, coordinate (i,j) maps to offset+i×s₀+j×s₁. Shape bounds the coordinates; strides say how far storage advances when a coordinate increases by one. We use element indices rather than byte addresses, and restrict the teaching layouts to two dimensions with nonnegative strides.

A 2×3 matrix stored as [10,11,12,13,14,15] has strides (3,1). Reading rows visits positions [0,1,2,3,4,5]. Swapping the axes gives shape 3×2 and strides (1,3), whose logical traversal visits [0,3,1,4,2,5]. The values have a different logical order even though their original storage remains in place.

The transpose documentation specifies shared storage for ordinary strided tensors. Changing the indexing interpretation does not require moving all six values merely to exchange two axes. Sparse layouts have separate rules and are outside this example.

Original (2,3): strides(3,1)
Swapped (3,2): strides(1,3)
Logical positions0,3,1,4,2,5
Original index flow: a transpose changes logical traversal while ordinary strided storage is shared.

A one-dimensional view needs a fixed step

Flattening the transposed result in its current logical order into length six requires one stride connecting adjacent logical elements. The differences in [0,3,1,4,2,5] are [3,−2,3,−2,3]. No single step expresses that order. Having six available elements is insufficient to construct the requested view.

The view definition requires compatible shapes and strides. One condition for combining adjacent dimensions is stride[i]=stride[i+1]×size[i+1]. In this example one is not three times two, so these two nonsingleton dimensions cannot merge into the desired one-dimensional view.

Simply interpreting the original contiguous storage with another shape retains the original rowwise sequence; it is not an axis transpose. Identical shapes do not establish identical data semantics. A successful operation can still mix the features belonging to different samples when batch, time and channel axes are confused.

Noncontiguous does not mean every view fails

Consider a sliced layout with shape (2,2) and strides (4,2). Logical traversal visits positions [0,2,4,6]. It skips storage elements and is not the ordinary elementwise contiguous layout, but length four with stride two expresses the flattened order. Here the merging condition four equals two times two holds.

This counterexample prevents treating noncontiguity as sufficient evidence that a particular view must fail. The question concerns the specific target shape and specific strides. Singleton dimensions and other cases require the full rules. The program below checks only the layouts it lists; it is not a general implementation of PyTorch’s view-compatibility algorithm.

Keep shape, stride and storage_offset in a diagnostic record, then state the intended logical traversal. Logging only is_contiguous does not establish that every possible shape conversion must copy or fail. A boolean can summarize one property without answering the particular transformation question.

Transpose: alternating steps3,−2 cannot flatten
Slice: positions0,2,4,6 have step2
View compatibility depends on target and strides
Original layout comparison: noncontiguity alone does not decide a particular view.

A copy changes both representation and aliasing

The reshape definition permits either a view or a copy, and callers should not rely on which occurs. For the transposed order above, reading old positions [0,3,1,4,2,5] into fresh contiguous storage makes a one-dimensional stride-one representation possible.

The new storage contains [10,13,11,14,12,15]. If old storage position three subsequently changes, a view through that position sees the change, while the copied second value stays thirteen. Copying changes observable behavior when a caller expects mutations to propagate. Conversely, an operation that may share storage is not an unconditional independent snapshot.

Decide the ownership requirement before choosing a shape operation. Besides successful execution, verify the values and axis meaning, and decide whether mutations should propagate. Performance is a third question requiring measurements for actual shapes, devices and execution paths. A six-element drawing supplies no device latency or memory-allocation benchmark.

Eight address-map checks

The example uses Python lists and explicit indices to enumerate logical traversal. Six assertions check the two layouts and their adjacent differences. The final two check the packed order and show that modifying original storage does not retroactively alter a copied list.

# Address-map model, not a PyTorch tensor implementation.
from itertools import product

def offsets(shape, stride, base=0):
    return [base + sum(i*s for i,s in zip(idx,stride))
            for idx in product(*(range(n) for n in shape))]

a = offsets((2,3), (3,1))
t = offsets((3,2), (1,3))
sliced = offsets((2,2), (4,2))
assert a == [0,1,2,3,4,5]
assert t == [0,3,1,4,2,5]
assert t != a
assert [t[i+1]-t[i] for i in range(5)] == [3,-2,3,-2,3]
assert sliced == [0,2,4,6]
assert all(sliced[i+1]-sliced[i] == 2 for i in range(3))
storage = [10,11,12,13,14,15]
packed = [storage[k] for k in t]
assert packed == [10,13,11,14,12,15]
storage[t[1]] = 99
assert storage[3] == 99 and packed[1] == 13
print('8 address-map checks passed')

This is not a PyTorch runtime or autograd acceptance test. It provides storage-position evidence small enough to inspect by hand. A project integration test must execute its actual operation and record copying behavior, output values and permitted mutation behavior. Those facts cannot be inferred for an arbitrary production tensor from this arithmetic model.

Establish axis meaning before choosing a copy

Use an axis-exchange operation when the intention is to exchange axes. When regrouping the existing logical order, check target-shape and stride compatibility. Consider reshape when copying is allowed. If sharing storage is a hard requirement, document it as an interface contract; an incompatible case should then fail explicitly rather than silently taking a copy-capable path.

The earlier MSE broadcasting investigation makes a related distinction: a legal shape is only an entry condition; element correspondence determines whether a computation means what was intended. Distinct sentinel values along every axis reveal misplaced elements more readily than zeros or repeated values.

If these address calculations help localize a transpose-and-flatten problem, voluntary support through the section below is welcome. The reusable artifacts are the shape-and-stride record and mutation-propagation checks for the next layout change.

Sources and backfill note

view · reshape · transpose

Checked against versioned PyTorch 2.8 definitions available before the planned October20 14:00 Beijing slot. This backfill retains that article date; actual public release time is recorded separately. Derivations and diagrams are original. Standard-library code ran locally, without a PyTorch integration test or device benchmark.

Support

If the explanations or examples helped you solve a problem or save time, you’re welcome to support this site with a voluntary tip.

WeChat support QR code; click to enlarge
WeChat
Alipay support QR code; click to enlarge
Alipay
Buy Me a Coffee; support this site
Buy Me a Coffee

Click a QR code to enlarge. More options: support page。

Share this Post

Leave a Comment

您的邮箱地址不会被公开。 必填项已用 * 标注

*
*