AI Wiki中文/EN

Tensors and shapes

张量与形状

Keep axis meanings intact through projection, transpose and reshape.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A shape is a set of slots, not a complete description

Imagine two sentences, each padded to three token positions, with two features stored for every token. The resulting array has shape (2,3,2). The first axis identifies the sentence, the second identifies position, and the third identifies a feature channel. Swapping the two axes of length two preserves the shape while changing what each entry means.

That is why a comment such as “input: 2×3×2” is weaker than “input: batch×token×channel.” Many model bugs preserve all dimension sizes. They quietly mix examples or normalize across the wrong axis.

In the array terminology used by Deep Learning, §2.1, a tensor extends the familiar scalar, vector and matrix to a grid with more axes. This chapter uses that machine-learning convention and keeps the axis meanings explicit. The separate tensor products chapter explains the algebraic operation behind product spaces.

Name the axes before choosing the operation

An order-k array has k axes. Its shape lists their lengths; the total number of stored entries is their product. A scalar has order zero and a single value. “Rank” is sometimes used for the number of array axes, but matrix rank means the dimension of the column space. Say order or number of axes when the distinction matters.

Let X store B batches, T positions and C channels. Apply the same C×O weight matrix W to each token:

X∈RB×T×C,W∈RC×O,Ybto=∑c=0C−1XbtcWco,Y∈RB×T×O.X\in\mathbb R^{B\times T\times C},\quad W\in\mathbb R^{C\times O},\quad Y_{bto}=\sum_{c=0}^{C-1}X_{btc}W_{co},\quad Y\in\mathbb R^{B\times T\times O}.

Only the channel index disappears into the sum. Batch and position stay separate. The NumPy expression einsum('btc,co->bto', X, W) states both the contraction and the output order. The letters are labels chosen by the programmer, not built-in semantic types. Explicit output labels avoid the alphabetical output-order rules of implicit mode; see the NumPy 1.26 reference.

Transpose changes the coordinate lookup

To exchange batch and position, create Z with shape (T,B,C). Its entries obey:

Ztbc=Xbtc.Z_{tbc}=X_{btc}.

This is transpose(X,(1,0,2)): output axis zero refers to input axis one, and so on. NumPy’s transpose documentation specifies this axis-permutation convention. The operation often returns a view; it does not promise contiguous storage.

Reshape answers a different question: how should an existing traversal of entries be grouped into a new shape? With default C-order, X[b,t,c] has traversal offset:

r=((bT)+t)C+c.r=((bT)+t)C+c.

Reshaping to (T,B,C) regroups that traversal; it does not generally implement Z[t,b,c]=X[b,t,c]. In our fixture, the requested old entry X[0,1,0] equals 2. Transpose puts it at [1,0,0]; reshape puts 4 there. Both outputs have shape (3,2,2), so a shape assertion alone misses the bug.

Array coordinates are not a complete geometric definition

In mathematics, a tensor is an object associated with vector spaces and their multilinear structure; its coordinate array depends on chosen bases. An arbitrary array can serve as coordinates after those spaces and bases are specified. Merely storing an ndarray neither specifies physical transformation laws nor checks them. Changing array axes, changing a vector-space basis and multiplying tensors are separate operations.

Project every token without mixing sentences

Use Python 3.12 with NumPy 1.26.4 from this repository’s example requirements. The complete program accepts integer arrays with nonempty axes of length at most 32 and values from −100 to 100. It casts to int64 before computing. At most 32 products of magnitude 10,000 contribute to an output, so the stated domain cannot overflow int64. These small limits make this an exact teaching example, not a general model layer.

import numpy as np


def project_tokens(x, w):
    x, w = np.asarray(x), np.asarray(w)
    if x.ndim != 3 or w.ndim != 2:
        raise ValueError('expected X(batch,token,channel), W(channel,output)')
    if any(s == 0 or s > 32 for s in (*x.shape, *w.shape)):
        raise ValueError('axis lengths must be in [1,32]')
    if x.shape[2] != w.shape[0]:
        raise ValueError('channel dimensions differ')
    if x.dtype.kind not in 'iu' or w.dtype.kind not in 'iu':
        raise ValueError('integer arrays required')
    if np.any(x < -100) or np.any(x > 100) or np.any(w < -100) or np.any(w > 100):
        raise ValueError('entries must be in [-100,100]')
    return np.einsum('btc,co->bto',x.astype(np.int64),w.astype(np.int64))


if __name__ == '__main__':
    x=np.arange(12).reshape(2,3,2)
    w=np.array([[1,-1],[2,0]])
    y=project_tokens(x,w)
    swapped=np.transpose(x,(1,0,2))
    regrouped=x.reshape(3,2,2)
    assert swapped[1,0,0] == x[0,1,0] == 2
    assert regrouped[1,0,0] == 4
    print('output shape:',y.shape)
    print('output:',y.tolist())
    print('same shape, different meaning:',swapped.shape == regrouped.shape,
          np.array_equal(swapped,regrouped))

Output:

output shape: (2, 3, 2)
output: [[[2, 0], [8, -2], [14, -4]], [[20, -6], [26, -8], [32, -10]]]
same shape, different meaning: True False

The first token has channels [0,1]. Its two outputs are 0×1+1×2=2 and 0×(−1)+1×0=0. The next token [2,3] produces [8,−2]. Each position uses the same weights; no sum spans sentences or positions.

For ordinary dense arithmetic the projection takes O(BTCO) work and stores BT O output entries. The explicit integer conversion also copies the inputs. A transpose can often change strides without copying data, but a later kernel may need a contiguous copy. Do not infer runtime or allocation behavior from shape alone. Vectorization and broadcasting develops those engineering choices.

Correct dimensions can still mean incorrect data

An array with shape (2,3,2) cannot tell you whether its last axis holds color channels, coordinates or hidden features. Nor can it tell you whether position 2 is padding. Masks, units, names and layout conventions belong in the data contract. A projection of padded tokens still computes outputs unless you explicitly handle padding.

Broadcasting can make incompatible intentions produce legal arithmetic. A bias of shape (O,) adds one value per output channel; a tensor whose dimensions happen to align may add along a different intended axis without an exception. Check selected coordinates using a small literal example, not just the final shape.

This example uses shared linear weights and exact bounded integers. It does not implement attention, nonlinear activations, ragged tensors, automatic differentiation or device placement. Those operations add constraints; calling their input a tensor does not remove the constraints.

Find the mistake that a shape check cannot catch

  1. X has shape (4,5,6), and W has shape (6,7). What is the output of btc,co->bto shaped like?

Answer 1: (4,5,7). The channel index c is summed; batch b and token t remain.

  1. For the program’s X, compare transpose(X,(1,0,2))[1,0,0] with X.reshape(3,2,2)[1,0,0].

Answer 2: They are 2 and 4. Transpose retrieves X[0,1,0]; reshape uses the C-order traversal offset 4.

  1. Can a 3×3 matrix have array order two but matrix rank one?

Answer 3: Yes. A nonzero matrix whose every column is a multiple of one vector has rank one and still has two axes.

  1. How would you test that changing the second sentence leaves the first sentence’s projected output unchanged?

Answer 4: Copy X, alter only X[1,:,:], run both projections and compare output[0,:,:]. The contraction sums channels only; a change across batches reveals an indexing or contraction error.

Carry the labels into the next layer

The array definition in Deep Learning helps connect linear algebra to model inputs. NumPy’s einsum and transpose references make the index operations executable. Their notation is most useful when accompanied by a written meaning for every axis.

Continue with matrix calculus to differentiate a shared projection, or with attention to see a second contraction over token positions. As a project, add an output-channel bias, then verify one token by hand and verify batch independence. Keep layout changes separate from the arithmetic so a later optimization can be checked against the same coordinate contract.

Make a prediction, then check

Which operation exchanges the first two axes of X?

Choose one answer

Learning objectives

  • Explain why reshape need not exchange axes.
  • Check a contraction with named axes and literal coordinates.

Prerequisites & connections

Explore related knowledge →

References

  1. Deep Learning — Chapter 2: Linear Algebra
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
  2. numpy.einsum — NumPy 1.26
    NumPy developers
  3. numpy.transpose — NumPy 1.26
    NumPy developers

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, derivations, literal or exact computational checks, real runtime experiments where stated, and bilingual review; not independent human or second-agent peer review.

  • Four tests passed: literal contractions, batch independence, transpose/reshape coordinate mismatch and bounded integer/input contracts. Three paired formulas and four answers render.
  • Single-agent authored technical review, with primary-source locations, stated assumptions and matching bilingual examples/exercises. Not independent human or second-agent review. Final publication navigation and repository checks are separate.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.