Python & PyTorch for Inference

Everything this module has computed so far happened on paper. From the next module onward it happens in code, and the code of this field is Python with PyTorch at its center: the library the course adopts here and uses, directly or underneath an engine, for the rest of the way. Its central object is the tensor from tensor shapes, made executable.

This lesson is the working habits, not a language course. It assumes you can read Python and gives you the handful of moves inference work actually uses: reading a tensor's three facts, keeping tensors on the right device in the right format, and running models without paying for machinery that only training needs. Every output shown was produced by the code beside it, on PyTorch 2.13.

A tensor in code

A PyTorch tensor carries the facts the lesson on tensor shapes taught you to read, plus one new one, as attributes:

The first line is the five-token activation, and the second line is the counting frame from memory and throughput arithmetic as one expression: element count times byte width. The number to pause on is 81,920. A fresh tensor is 32-bit by default, so it costs twice what the course's standing BF16 assumption implies until you cast it; the .to(torch.bfloat16) line halves it to the ~41 KB that inventory from tensor shapes predicted. Checking dtype before trusting a memory estimate is the first habit.

.to() is also how tensors change machines. A device is where the tensor's bytes live: "cpu" for main memory, "cuda" for an NVIDIA GPU, "mps" on Apple silicon. One rule governs them: every tensor in an operation must live on the same device.

Break it and PyTorch refuses at the exact operation. On the Apple-silicon machine these outputs came from, multiplying an "mps" tensor by a CPU tensor fails with RuntimeError: Tensor for argument #2 'mat2' is on CPU, but expected it to be on GPU (while checking arguments for mm). The wording varies by backend and operation, but the diagnosis never does: print both .device attributes and move one tensor.

Provoking a shape error

Matrix multiplication is the @ operator, and it enforces the inner-axis rule mechanically. Run the five-token activation into the up projection as the weights file actually stores it:

That is the exact message the lesson on tensor shapes quoted from the PyTorch source, now triggered on purpose, and the fix is the transpose the runtime applies for you when a real model runs: a @ w.T returns torch.Size([5, 14336]). Provoking this error once, deliberately, is worth more than reading about it; the check it teaches (write both shapes down, compare inner axes) is the one you will run mentally in unfamiliar code.

Inference mode

By default, PyTorch stands ready to do more per operation than the math you asked for. Whenever an input carries requires_grad=True, and a model's weights do by default, it records how each result was produced, building the bookkeeping that training's backward pass needs; the recording costs memory and time. Inference never uses it.

The True says the first result carries recording machinery; inside the torch.inference_mode() block, the same multiplication produces a plain tensor. The course's habit: model code runs inside torch.inference_mode(), and models are switched to model.eval() first, which turns off training-only behaviors some layers have. Both lines appear throughout serving code, and now you know what they are declining to pay for.

Common misconception. Engineers hear "Python is slow" and conclude serious inference cannot be written in it. In this stack Python is the dispatcher, not the calculator: each operation is a call into compiled GPU or CPU kernels, and the heavy work never executes as Python. That is why nearly every serving system you will meet is driven from Python. Where the dispatch overhead itself starts to matter, many small operations per token, is covered in compilation and CUDA graphs.

A pinned environment

The last habit is packaging the other three so they repeat. A virtual environment pins what "worked on my machine" means:

Which torch build to install, and how to tell whether it can actually see a GPU, waits for GPU compatibility; the plain pip install torch above is the CPU-capable default. What matters here is the shape of the habit: one environment per project, versions frozen to a file, and the version printed before any result is trusted. This is the "pinned environment and repeated result" that levels of inference engineering set as the evidence bar for the run scope.

Downloading a real model, tokenizing text, and generating with it are deliberately absent from this lesson: that is running your first LLM. The next lesson steps back from the keyboard first and walks the architecture itself, block by block.