Back to learning

INTERACTIVE LEARNING · PYTORCH

LearnPyTorch · Tensor Lab

Nine guided lessons build tensor intuition: axes, broadcasting, batched products, flattening, safe squeeze, channel bias, pooling, linear layers, and softmax.

Each tile is a value, each axis gives it a position. Predict what an operation will do, run it, then inspect the result. The starter programs contain deliberate mistakes: a program can run and still arrange the data incorrectly.

LearnPyTorch · New: Attention Detective

LearnPyTorch: make the invisible visible

19 small challenges. Break a tensor, follow a gradient, catch an attention bug. No installation or account.

Completed 0 / 19Continue learning →
Your learning map · See all 19 challenges

Progress stays in this browser. All lessons are open; choose your own route.

Open the autograd lab →

Choose a lesson, edit the code, and select Run. Compare your result with the target and select an intermediate step to inspect it. Hints progress from an idea to a solution. A lesson passes only when shapes and values match on the visible example and three fresh inputs. Replay the operations one by one, compare the difference with the target, and click a matrix-product cell to inspect its calculation. The softmax lesson also shows the distribution and sum for each query.

Completed 0 / 9

A change of perspective

An image is more than a list of numbers. Move its axes without losing the relationship between pixels and channels.

Your mission

Turn x from [height, width, channel] into y with [channel, height, width]. Keep every pixel in the right place.

Ctrl / ⌘ + Enter to run

Select a tile to inspect its coordinates and storage offset.

Follow the transformation

One idea to keep

reshape changes how a sequence is grouped. permute changes which axis comes first. Equal shapes do not guarantee equal values.

What you will practise

Reorder the axes

Turn x from [height, width, channel] into y with [channel, height, width]. Keep every pixel in the right place.

reshape changes how a sequence is grouped. permute changes which axis comes first. Equal shapes do not guarantee equal values.

Convert [batch, height, width, channel] into [batch, channel, height, width]. Which axis stays in place?

PyTorch documentation ↗

Understand broadcasting

Create y by subtracting each row’s mean from that same row of x. Every output row should have mean zero.

Broadcasting aligns axes from the right. Dimensions must match or one must be 1. keepdim=True retains the reduced axis with size 1.

For x [batch, time, features], subtract the mean over time for each batch and feature. Which dim should you reduce?

PyTorch documentation ↗

Multiply batched matrices

Produce y [batch, query, key]. Each score must be the dot product of a query and a key from the same batch.

With @, the last two axes are matrix axes and earlier axes are batch axes. Swap the key and feature axes of k so feature dimensions contract.

For q [B, H, Q, D] and k [B, H, K, D], predict the shape of q @ k.transpose(-2, -1).

PyTorch documentation ↗

Flatten without mixing batches

Turn x [batch, height, width] into y [batch, height × width], keeping each example’s values in their original order.

flatten(start_dim=1) merges the axes after the batch axis. Flattening everything also removes the batch boundary.

For x [B, C, H, W], predict x.flatten(1).shape. How would you merge only H and W?

PyTorch documentation ↗

Squeeze one axis safely

Turn x [batch, feature, 1] into y [batch, feature]. Keep axis 0 even when its size is 1.

squeeze() removes every size-one axis. squeeze(-1) names the axis to remove and preserves other singleton axes.

Why might a model work during training but fail on its last batch if it uses squeeze() without dim?

PyTorch documentation ↗

Broadcast a channel bias

Add bias [channel] to x [batch, channel, height, width], reusing each channel’s bias across its pixels and all examples.

Broadcasting aligns dimensions from the right, without reading axis names. Reshape the bias to [1, channel, 1, 1]. The visible channel and width sizes happen to match.

For channels-last x [B, H, W, C], would adding a [C] bias directly be correct? Explain the alignment.

PyTorch documentation ↗

Pool spatial dimensions

Average x [batch, channel, height, width] over height and width to produce y [batch, channel].

A reduction removes an axis unless keepdim=True. After reducing the last axis, the previous second-last axis becomes the last axis.

How would you keep a [B, C, 1, 1] result so it can broadcast back over the original image?

PyTorch documentation ↗

Build a linear layer

Compute y [batch, time, output] from x, weight [output, input], and bias [output]. Use one projection at every time step.

A PyTorch linear layer computes x @ weight.T + bias on the final feature axis. Leading axes survive, and the bias broadcasts across them.

For x [B, H, T, D] and weight [O, D], what shape does the output have? Which axes share the same parameters?

PyTorch documentation ↗

Normalize attention scores

Create y with the same shape as scores [batch, query, key], with softmax applied across keys independently for each query.

softmax(dim) exponentiates and normalizes within that axis. Each group sums to one. The implementation subtracts the group maximum to avoid overflow for large finite scores.

If you add the same constant to every score within one query, should its probabilities change? Try scores + 1000 in the playground.

PyTorch documentation ↗
Supported expressions
x.permute(2, 0, 1)
Reorder axes while preserving which element belongs where.
x.transpose(-2, -1)
Swap two axes; negative axes count from the end.
x.reshape(3, -1)
Regroup the logical element sequence; one -1 can infer a dimension.
x.unsqueeze(1) / x.squeeze(1)
Insert or remove a size-one axis.
x.mean(dim=1, keepdim=True) / x.sum(dim=0)
Reduce an axis; keepdim=True retains its position for broadcasting.
x + y / x - y / x * y / x / y / x @ y
Elementwise arithmetic with broadcasting, or matrix multiplication with @.
torch.tensor([[1, 2], [3, 4]]) / torch.arange(12)
Create a tensor from nested lists or the numbers 0 through n−1.
torch.ones(2, 3) / torch.zeros(2, 3)
Create tensors filled with ones or zeros.
x.flatten(start_dim=1, end_dim=-1)
Merge a contiguous range of axes; axes outside the range stay in place.
x.softmax(dim=-1)
Normalize exponentials along an explicit axis; each group sums to one.

A focused learning environment

This is a PyTorch-style simulator, not a full Python runtime. It supports numeric tensors of rank 0–4 with up to 4096 elements and positive dimensions. The canvas shows up to 8 × 8 cells per slice. Indexing, loops, autograd, devices, dtypes, empty tensors, and in-place changes are outside this release. Noncontiguous reshape conservatively copies here; real PyTorch can sometimes return a view. Export uses floating-point tensors explicitly.

Progress stays in this browser when storage is available. Code runs locally in a bounded simulator; it is not sent to a server. Share copies your code into a URL. Python export creates a file you can run in an environment with PyTorch installed.

Independent learning project, inspired by Learn Git Branching; not affiliated with PyTorch.

PyTorch documentation ↗