Lesson 1.2 — Tensor Manipulation
Why manipulate tensors?
The same robot data is consumed by different modules that expect different axis structures. Manipulation is not cosmetic: every operation either selects data, reorganizes axes, or joins independent tensors.
Selection
Pick one robot, time interval or joint from a trajectory. Selection can reduce both the number of elements and the number of axes.
Symbols: X trajectory tensor · b batch index · : all time steps · j joint index.
Reorganization
Merge, split or reorder feature axes. The element count is unchanged, but the index order may change.
Symbols: reshape changes axis lengths keeping traversal order · permute reorders axes.
Composition
Combine independent tensors into a batch or a multivariate sample. Rank may stay the same or increase by one.
Symbols: cat joins along an existing axis · stack creates a new axis.
Core principle: name the data semantics of every axis before choosing an operation. Do not validate with shape alone — check the element mapping. The animations show logical index relationships, not physical memory copies.
Indexing & slicing
Symbols: X input matrix with R rows and C columns · i fixed row index (0 ≤ i < R) · j column index (0 ≤ j < C) · Y_j 1-D vector from integer-indexing row i · Z_{u,j} 2-D slice starting at row a with step s and slice row index u.
X[i, :] produces a one-dimensional vector, while
X[i:i+1, :] keeps a row axis of length 1. A slice
start:stop:step excludes stop; with a positive step the
indices increase. A negative integer index counts from the end, so -1 is
the last element.
Index & Slice Navigator
import torch
X = torch.arange(20).reshape(4, 5)
Y = X[0:1, :]
print(Y.shape) # (1, 5)
X[0] and X[0:1] select the same values but produce
different shapes. Keeping the batch axis is often essential for a model input.
A slice can also produce an empty axis, in which case numel is 0.
Reshape & flatten
Symbols: r input rank (number of axes) · d_i length of input axis i · s output rank · e_j length of output axis j (total numel stays identical).
Reshape preserves the input's logical element order. Flatten merges a chosen contiguous
range of index axes. The special size -1 may appear at most once and is
inferred from the total element count; it is not a negative dimension. The examples use
a contiguous arange source and make no claim about the underlying memory
layout.
A logical position is counted from zero in row-major traversal. After reshaping, that position is decoded using the new axis lengths. For example, with input shape (B,T,D), the position of (b,t,d) is (bT+t)D+d. This is a logical position in the tensor. The storage offset of a strided view depends on its strides and storage offset.
Pick the same logical position in two output layouts. Explain which axis changes fastest in each layout.
Reshape & Flatten Explorer
import torch
X = torch.arange(24).reshape(2, 3, 4)
Y = X.reshape(2, -1)
assert Y.shape == (2, 12)
print(Y)
Reshape changes the index structure, not the values. Input element
k is also output element k. When axes merge, the last input
axis varies fastest.
Transpose & permute
Symbols: X input tensor of rank r · p_k original axis index placed at output axis k · i_k coordinate along original axis k · Y permuted output tensor.
The arguments name the input axis that becomes each output axis. For
example permute(2, 0, 1) means the new axis 0 is the old axis 2. Every
original axis must appear exactly once. Unlike reshape, permute changes the index
order rather than preserving linear traversal order.
Transpose vs Permute vs Reshape
import torch
X = torch.arange(24).reshape(2, 3, 4)
Y = X.permute(2, 0, 1)
print(Y.shape) # (4, 2, 3)
Same shape does not mean same values. For a (2, 3) source,
reshape(3, 2) and transpose(0, 1) both produce (3, 2), but
Y[0, 1] is 1 after reshape and 3 after transpose. A permutation that swaps
only two axes is exactly transpose; permute is the general form. Always
inspect identifiable values.
Squeeze & unsqueeze
Symbols: k insertion axis index (0 ≤ k ≤ r) · r original rank · d_0, …, d_{r-1} original axis lengths · 1 newly inserted singleton axis at position k.
Unsqueeze
Insert a length-one axis and increase rank by one. x.unsqueeze(0) is the
usual way to add a batch axis to a single sample.
Squeeze
Remove only a specified axis that has length 1. x.squeeze() removes all
length-one axes and may remove a batch axis unintentionally.
Singleton Axis Builder
import torch
X = torch.arange(6).reshape(2, 3)
Y = X.unsqueeze(0)
assert Y.shape == (1, 2, 3)
print(Y)
No axis is "empty" just because its length is 1. A tensor with shape
(1, 7) has rank 2; (7,) has rank 1. Squeezing changes how later
operations broadcast, even when the values are identical.
Concatenate & stack
Symbols: k target axis index · m input tensor index (M tensors total) · d_k^(m) length of axis k in tensor m · d_k^out resulting length of axis k in the output.
Concatenation requires every non-concatenated axis to match. Stack requires all input shapes to be identical. The labs use two (2, 3) matrices: A contains 0–5 and B contains 100–105, so the source of every element stays visible.
Concatenation Lab · cat along an existing axis
import torch
A = torch.arange(6).reshape(2, 3)
B = A + 100
Y = torch.cat([A, B], dim=0)
assert Y.shape == (4, 3)
Stack Lab · insert a new axis
import torch
A = torch.arange(6).reshape(2, 3)
B = A + 100
Y = torch.stack([A, B], dim=2)
assert Y.shape == (2, 3, 2)
Equivalence: for equal-shaped inputs,
torch.stack([A, B], dim=k) equals
torch.cat([A.unsqueeze(k), B.unsqueeze(k)], dim=k). But
cat([A, B], dim=k) alone never increases rank.
Robot data assembly — B / T / J / S
Symbols: B batch size · T original time steps · T' sliced time window length (T' ≤ T) · J number of joints · S stacked state variables (S = 2 for q, dq) · F = JS flattened per-step feature size.
Robot Data Assembly · B / T / J / S
import torch
q = torch.arange(12).reshape(2, 3, 2)
dq = q + 100
X = torch.stack([q, dq], dim=-1)
print(X.shape) # (2, 3, 2, 2)
Keep the axis semantics visible. After Z = F.permute(1, 0, 2)
the shape can be unchanged when B = T, yet the axes now mean (T, B, F). A shape check
alone cannot catch that change.
Learn by coding — PyTorch
01 — Core operations, verified with assertions
Use assertions on shapes and on selected values, not only on the printed tensor.
import torch
X = torch.arange(24).reshape(2, 3, 4)
# Selection: integer drops an axis, slice preserves it.
assert X[0].shape == (3, 4)
assert X[0:1].shape == (1, 3, 4)
assert X[:, ::2, :].shape == (2, 2, 4)
# Reorganization
Y = X.reshape(2, -1)
assert Y.shape == (2, 12)
assert torch.equal(Y, X.flatten(1, 2))
P = X.permute(2, 0, 1)
assert P.shape == (4, 2, 3)
assert P[3, 1, 2] == X[1, 2, 3]
# Singleton dimensions
U = X.unsqueeze(0)
assert U.shape == (1, 2, 3, 4)
assert torch.equal(U.squeeze(0), X)
assert torch.equal(X.squeeze(0), X) # size 2: unchanged
# Joining
A = torch.arange(6).reshape(2, 3)
B = A + 100
assert torch.cat([A, B], dim=1).shape == (2, 6)
S = torch.stack([A, B], dim=2)
assert S.shape == (2, 3, 2)
assert torch.equal(S, torch.cat([A.unsqueeze(2), B.unsqueeze(2)], dim=2))
print('All core operations verified.')
02 — Robot data assembly
Stack q and dq, slice the time range, flatten J and S, then move T before B.
import torch
B, T, J = 2, 3, 2
q = torch.arange(B*T*J).reshape(B,T,J)
dq = q + 100
X = torch.stack([q, dq], dim=-1) # (2,3,2,2)
W = X[:, 1:3, :, :] # (2,2,2,2)
F = W.flatten(2, 3) # (2,2,4)
Z = F.permute(1,0,2) # (2,2,4), axes now T,B,F
assert X[1,2,1,0] == q[1,2,1]
assert X[1,2,1,1] == dq[1,2,1]
assert Z[1,0,3] == dq[0,2,1]
print('Shape:', Z.shape, 'axes: T, B, F')
print(Z)
Z[1, 0, 3] indexes time 1, batch 0, feature 3 — the flatten index 3 is joint 1, state 1 (dq).
03 — Attention tensor preparation
This is a tensor-reorganization reference only; the attention computation itself is not part of this lesson.
import torch
B, T, H, D = 32, 100, 12, 64
X = torch.randn(B, T, H*D)
Y = X.reshape(B, T, H, D)
Z = Y.permute(0, 2, 1, 3) # B,H,T,D
h, k = divmod(130, D)
assert Z.shape == (32, 12, 100, 64)
assert X[2,50,130] == Z[2,h,50,k]
reshaping splits the feature axis into (H, D); permute(0, 2, 1, 3) then moves H before T. The feature index 130 decomposes as h = 2, k = 2.
Mini project — robot tensor audit
Goal: build a (2, 3, 2, 2) robot tensor from q and dq, then reproduce the pipeline above. Assert every intermediate shape and prove that the same (b, t, j, s) value appears before and after flattening. Write one sentence per axis explaining its meaning.
import torch
B, T, J, S = 2, 3, 2, 2
q = torch.arange(B*T*J).reshape(B, T, J)
dq = q + 100
# TODO: stack q and dq into (B, T, J, S)
# TODO: select time indices 1 and 2
# TODO: flatten J and S into F = J*S
# TODO: permute to (T, B, F) and assert the shape
# TODO: prove one element survives every transformation
Do not replace the assertions with random numbers. Track one (b, t, j, s) index through every stage.
Operation summary
| Operation | Rank | numel | Meaning |
|---|---|---|---|
| Integer index | −1 per indexed axis | ≤ input | Select one coordinate |
| Slice | unchanged | ≤ input | Select a coordinate range |
| Reshape / flatten | may change | unchanged | Reorganize in logical order |
| Transpose / permute | unchanged | unchanged | Reorder axes |
| Unsqueeze / squeeze | +1 / −1 or unchanged | unchanged | Handle singleton axes |
| Cat | unchanged | sum of inputs | Lengthen an existing axis |
| Stack | +1 | sum of inputs | Introduce a new axis |
Scope boundary: this lesson studies logical data transformations only. Strides, contiguity and the view-vs-copy distinction are out of scope; broadcasting and reduction belong to Lesson 1.3.