Phase 01/Tensors and tokens/PyTorch tensors and execution
PHASE 01 · Tensors and tokens

PyTorch tensors and execution

0%
5 h5 subtopics2 lessons · 1 required
In plain English

A tensor is just a grid of numbers with a label saying how many rows, columns and deeper dimensions it has. PyTorch is the toolbox that stores those grids in memory and runs arithmetic on them very quickly, on a CPU or a GPU. Think of a tensor as a spreadsheet, and PyTorch as the engine that can add, multiply or reshape entire spreadsheets in one command instead of cell by cell. Every weight inside a language model and every intermediate result during a forward pass is one of these grids, so knowing how they are laid out in memory and how expensive each operation is lets you predict where a model spends its time.

Why it matters

Inference performance is mostly a story about tensor shapes, data types and memory layout. A view versus a copy, fp32 versus bf16, or a non-contiguous tensor silently triggering a copy can each change latency by 2x. You need to see these details instinctively before touching CUDA.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Create, reshape, slice and broadcast tensors and predict the resulting shapes.
  • Explain the difference between a view and a copy using strides and contiguity.
  • Measure matmul throughput on your CPU and express it in GFLOP/s.
  • Use torch.profiler to find which operators dominate a model forward pass.
  • Describe what eager execution does on every operator call and why it has overhead.

Key concepts

Shape and dtype
The dimensions of a tensor and the numeric type (fp32, bf16, int8) of each element; together they fix its byte size.
Stride
How many elements to skip in memory to move one step along each dimension; explains why transposes are free and some reshapes are not.
View vs copy
A view shares storage with its source (reshape, transpose, slice); a copy allocates new memory (contiguous, clone, most arithmetic).
Broadcasting
Rules that let tensors of different shapes be combined by virtually repeating the smaller one along size-1 dimensions.
Eager execution
PyTorch runs each operator immediately as Python calls it; simple, but each call pays dispatch and kernel-launch overhead.
FLOP
One floating-point operation; a matmul of (M,K) by (K,N) costs about 2*M*K*N FLOPs.
torch.profiler
The built-in tool that records every operator with its wall time and memory so you can see what a forward pass is actually made of.

Subtopics

  1. 1. Tensor creation, shapes and dtypes

    torch.zeros, randn, arange, tensor(); shape, dtype, device; element_size() and byte accounting.

  2. 2. Views, strides and contiguity

    How reshape, view, transpose, permute and slicing manipulate strides without moving data, and when .contiguous() copies.

  3. 3. Broadcasting and batched matmul

    Broadcasting semantics, torch.matmul over leading batch dimensions, einsum as a readable alternative.

  4. 4. Autograd off, inference mode

    torch.no_grad and torch.inference_mode; why inference skips building the graph and saves memory.

  5. 5. Profiling a forward pass on CPU

    torch.profiler record_function, key_averages, and reading the operator table for a GPT-2 forward pass.

Resources

documentation
article

Hands-on lessons

L1

Strides, views and a CPU matmul roofline

CPU · your Macnotebook90 minrequired

Goal · Produce a table proving which ops are views, and a GFLOP/s measurement of your laptop CPU for the matmul shapes GPT-2 uses.

  1. 1Create x = torch.randn(4, 1024, 768); print x.stride(), x.transpose(1, 2).stride(), x.view(4, -1).stride().
  2. 2For reshape, view, transpose, permute, slice, contiguous and clone, check data_ptr() equality with the source and record view-or-copy in a table.
  3. 3Try x.transpose(1, 2).view(4, -1) and explain the error; fix it with contiguous() or reshape().
  4. 4Time torch.matmul on (T, 768) @ (768, 3072) for T in [1, 16, 128, 1024] with time.perf_counter, 10 warmup runs then 50 timed runs.
  5. 5Convert each timing to GFLOP/s using 2*T*768*3072; repeat with dtype bfloat16.
  6. 6Vary torch.set_num_threads from 1 to your core count for T=1024 and plot GFLOP/s vs threads.
Deliverable
A notebook with the view/copy table, a GFLOP/s vs T plot and a GFLOP/s vs threads plot.
Check
T=1 achieves at least 10x lower GFLOP/s than T=1024, and the view/copy table matches the official Tensor Views page for every op.
L2

Profile a GPT-2 forward pass on CPU

CPU · your Macscript60 minoptional

Goal · Rank the operators in one GPT-2 small forward pass by total CPU time and by call count.

  1. 1pip install torch transformers; load gpt2 with AutoModelForCausalLM and call model.eval().
  2. 2Tokenize a 256-token prompt and run one forward under torch.inference_mode() as a warmup.
  3. 3Wrap a second forward in torch.profiler.profile(activities=[CPU], record_shapes=True).
  4. 4Print prof.key_averages().table(sort_by='cpu_time_total', row_limit=15).
  5. 5Identify the share of time taken by aten::addmm / aten::mm vs everything else; write one paragraph on what dominates.
  6. 6Repeat with a 1-token prompt and note how the ranking changes.
Deliverable
A script and a saved profiler table for both prompt lengths.
Check
Matmul-family ops account for more than 60 percent of CPU time at 256 tokens; at 1 token their share drops and per-op overhead is visible.

Build your own

Build your own tensor inspector and CPU roofline harness

PythonCPU · your Mac~5 h

A small CLI that reports a tensor's memory layout (views, strides, contiguity, aliasing) and measures where CPU matmul sits on the roofline, with no autograd involved.

The real thing: github.com/pytorch/pytorch/blob/main/c10/core/TensorImpl.h ↗

How you know a stage passes

Write tests/test_inspector.py first. Each stage adds a test that feeds known tensors (a transpose, a slice, a .view, an expand, a contiguous copy) to your `inspect(t)` function and asserts on the returned dict (strides, is_contiguous, shares_storage, bytes). Later stages add `bench.py`, whose CSV output is checked by a test for shape and monotonicity. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01strides and contiguity from first principles
    Your `inspect(t)` computes expected row-major strides from the shape and reports whether the tensor's actual strides match, without calling is_contiguous().
    test · For x = torch.randn(4, 6), inspect(x)["contiguous"] is True and inspect(x.t())["contiguous"] is False; your computed strides equal x.stride() for 20 random shapes.
  2. 02view versus copy detection
    The inspector reports whether two tensors alias the same storage and at what byte offset, so you can tell a view from a copy.
    test · shares_storage(x, x[1:3]) is True with offset 6 * 4 bytes for a (4, 6) float32; shares_storage(x, x.clone()) is False; shares_storage(x, x.reshape(24)) is True and shares_storage(x.t(), x.t().reshape(24)) is False.
  3. 03a CLI that explains a chain of ops
    `python inspect.py 'randn(8,16).t()[::2].unsqueeze(0)'` prints one line per op with shape, strides, contiguity and whether a copy happened.
    test · The CLI output for that expression shows exactly zero copies and a final stride tuple of (0, 2, 16) or your derived equivalent; running it with `.contiguous()` appended shows exactly one copy.
  4. 04count the copies in a model
    A torch function-mode hook counts hidden copies (contiguous, clone, copy_) during a GPT-2-small forward on 64 tokens under torch.inference_mode().
    test · Your counter reports a non-zero copy count and names the top three call sites; replacing one .contiguous() you can safely remove lowers the count by one.
  5. 05a CPU matmul roofline
    `bench.py` times square float32 matmuls from N=64 to N=4096, computes GFLOP/s and arithmetic intensity, and writes a CSV plus a roofline plot with your machine's measured peak and bandwidth.
    test · The CSV has one row per N; GFLOP/s is non-decreasing from N=64 to N=1024; N=4096 reaches at least 50 percent of the peak you measured with a long-running matmul.
  6. 06show the layout penalty
    The benchmark also times matmul on a transposed (non-contiguous) operand and on a contiguous copy, and reports the ratio.
    test · The README table lists both timings for N=2048 and the ratio; your one-paragraph explanation names the stride that caused the slowdown.

Knowledge check

QDoes x.transpose(0, 1) allocate new memory?

No. It returns a view with swapped strides; only a later .contiguous() or an op that needs dense memory will copy.

QHow many bytes does a (1024, 768) fp32 tensor take, and in bf16?

1024*768*4 = 3,145,728 bytes (3 MiB) in fp32 and half that, 1,572,864 bytes, in bf16.

QWhy is a (1, 768) @ (768, 3072) matmul so much slower per FLOP than (1024, 768) @ (768, 3072)?

With one row the weight matrix is read from memory once and used only once per element, so the op is memory-bound and fixed overhead dominates; with 1024 rows each weight element is reused 1024 times.

QWhat does torch.inference_mode() save compared with a plain forward?

It skips recording the autograd graph and version counters, so no saved activations for backward and less bookkeeping per op.

Completion

  • All 5 subtopics marked done
  • All 1 required lessons done
  • All five subtopics marked completed.
  • Lesson l1 deliverable saved and its check passes.
  • Can predict the stride of a transposed or sliced tensor without running it.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →