PyTorch Internals: From a Python Call to a Kernel

One call such as torch.add(a, b) passes through a stack of layers before any number is added. A dispatcher picks the layers: autocast, autograd, version tracking, Python hooks, then the kernel for your device. Each layer does one job and hands the call down.

Learn the stack from the Python binding to the kernel, then the parts around it: the tensor object, the memory allocator, the backward engine, the graph compilers (fx, export, torch.compile), the hooks that tools use, custom ops, and deployment.

Pick an operation and a device. Turn on requires_grad, autocast or a FlopCounterMode. Press Call and watch the call fall through the dispatch keys. A filled row ran a kernel. A dashed row was skipped.

You need autograd (the graph behind backward) and Making PyTorch Fast (why fewer, bigger ops win). We build everything else from zero.

The dispatcher walk

Ready

Keys, their order, which keys have a kernel for each operator, the key sets and the error text are PyTorch 2.10's, read with torch._C._dispatch_keys, _dispatch_tls_local_include_set, _dispatch_dump_table and the v2.10.0 sources. Only the keys this call can meet are drawn; PyTorch has 145. Times: one-element torch.add on an Apple M5 Max, one thread, measured with timeit.

Chapter 0

Where do 376 nanoseconds go?

Adding two numbers takes 8 ns in Python and 376 ns in PyTorch. The difference is the machinery this lesson opens up.

Here are four ways to add one number to another, timed on an Apple M5 Max with one thread:

CodeWhat is addedTime per call
x + ytwo Python floats8 ns
na + nbtwo NumPy arrays of 1 element136 ns
torch.add(a, b)two tensors of 1 element376 ns
w + bthe same, but w.requires_grad is True704 ns
torch.add(big, big)two tensors of 1,000,000 elements217,624 ns

The addition itself is one machine instruction. Almost all of the 376 ns is spent deciding which code should add, and preparing for what might come next: a backward pass, a cast, a hook, a different device. That work is the subject of this lesson.

A simple model explains the table. Each call pays a fixed price, then a small price per element:

t(N)
The time for one call on N elements.
c0
The per-call overhead: Python, argument parsing, the dispatcher, allocating the output. It does not depend on N.
c1
The work per element: reading the inputs, adding, writing the output.
N
The number of elements.

Worked: c0 ≈ 376 ns. From the million-element row, c1 ≈ 217,624 / 106 = 0.218 ns per element. The two costs are equal at N = c0 / c1 = 376 / 0.218 ≈ 1,700 elements. Below that size, PyTorch spends most of its time on bookkeeping.

Slide N below and watch the share of overhead shrink. Then turn on requires_grad: the fixed price nearly doubles, because autograd must build a backward node on every call.

Overhead against work

Left: time per call against size, both on log scales. Right: what that one call spends its time on. The dots are measurements; the lines are the model above.

100

Measured on an Apple M5 Max, PyTorch 2.10, torch.set_num_threads(1), best of 5 timeit runs: 376 ns (1 element), 704 ns (1 element, requires_grad), 217,624 ns (106 elements). The straight lines are the two-number model fitted to those points; real curves bend where caches run out.

The road map of this lesson

  1. The tensor object: TensorImpl, Storage, and the trip from Python into C++.
  2. The dispatcher: dispatch keys, key sets, priorities, fallthroughs. You build one.
  3. What each key does: autocast, autograd, views and in-place, Python hooks, then the ATen kernel.
  4. The price of eager mode: per-op overhead and memory traffic, measured.
  5. The caching allocator: why nvidia-smi shows more than you allocated.
  6. The autograd engine: dependency counts, a ready queue, a thread per device.
  7. Capturing graphs: TorchScript, torch.fx, torch.export. You build a tracer.
  8. Inside torch.compile: Dynamo, guards, AOTAutograd, Inductor.
  9. Hooking in: __torch_function__, __torch_dispatch__, FakeTensor, FLOP counting, custom ops.
  10. Leaving Python: export, ONNX, and quantisation.
  11. Connections: a map of the source tree, the cheat sheet, limits.

PyTorch, Zero to Expert

This is lesson 10 of an eleven-part series inside The Builder's Toolkit. Each lesson has Code Labs that run a copy of the PyTorch API in your browser.

  1. PyTorch Tensors: storage, strides and views.
  2. Autograd: the graph behind backward().
  3. nn.Module Inside Out.
  4. Datasets and DataLoaders.
  5. The Training Loop, Line by Line.
  6. Debugging Training.
  7. Memory and Mixed Precision.
  8. Making PyTorch Fast.
  9. Distributed PyTorch: DDP and FSDP.
  10. PyTorch Internals (this lesson): from a Python call to a kernel.
  11. Build PyTorch from Scratch.
With c0 = 376 ns per call and c1 = 0.218 ns per element, which is faster: 1,000 calls on 100 elements each, or 1 call on 100,000 elements?

Chapter 1

The tensor object, and the trip into C++

A Python tensor is a thin handle on a C++ TensorImpl, which points at a StorageImpl that owns the bytes

The torch.Tensor you hold in Python is small. It is a Python object with one important field: a pointer to a C++ object called TensorImpl. The TensorImpl holds everything that describes the tensor. It points at a second object, the StorageImpl, which owns the actual bytes.

The split exists for views. A view such as a.t() or a[1:, 2:] gets a new TensorImpl with new sizes and strides, but it points at the same StorageImpl. No bytes are copied. Edward Yang put it this way: storage defines the physical memory, and each tensor records "the sizes, strides and offset, defining the logical interpretation of the physical memory" Yang 2019.

What a TensorImpl holds

Pick an expression below. The fields shown are the ones PyTorch 2.10 printed for it.

Inside a TensorImpl

a = torch.arange(12.).reshape(3, 4). Top: the TensorImpl of the chosen expression. Bottom: the 12 floats of storage; the cells it reads are lit, numbered in the order the tensor visits them.

Sizes, strides, offsets, storage sizes, versions, grad_fn and key sets are PyTorch 2.10's printed values. w is a.clone().requires_grad_(), so it has its own storage.

To find element (i, j), PyTorch computes one address. This is the only arithmetic a view needs:

addr(i, j)
The byte address of the element at row i, column j.
data
The start of the storage's bytes (untyped_storage().data_ptr()).
offset
Where this tensor starts inside the storage, in elements (storage_offset()).
s0, s1
The strides: how many elements to skip for one step along each dimension.
itemsize
Bytes per element: 4 for float32, 2 for bfloat16.

Worked: v = a[1:, 2:] has offset 6 and strides (4, 1). For v[1, 1]: 6 + 1·4 + 1·1 = 11, byte 11 × 4 = 44, and the value there is 11.0. Check: v[1, 1] is a[2, 3] = 2·4 + 3 = 11.

From torch.add to C++

torch.add is not written in Python. It is a C function, generated when PyTorch is built:

Run this on a machine with PyTorch

import torch
print(torch.add)
print(torch.add is torch._C._VariableFunctions.add)
output (torch 2.10)
<built-in method add of type object at 0x1049d7558>
True

The generator, torchgen, reads one file, aten/src/ATen/native/native_functions.yaml. It holds 2,666 operator entries in v2.10.0. Here is the one for add:

# aten/src/ATen/native/native_functions.yaml (v2.10.0), excerpt
- func: add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
  structured_delegate: add.out
  variants: function, method
  tags: [core, pointwise]

The schema in the first line is a typed signature. From it torchgen writes the Python binding, the C++ function at::add, and the dispatcher registration. When you call torch.add(a, b), the generated binding does four things:

  1. Parses the Python arguments against the schemas of every add overload (torch/csrc/utils/python_arg_parser.cpp).
  2. Checks whether any argument overrides __torch_function__ (Chapter 9). If one does, Python code takes over here.
  3. Releases the global interpreter lock, so other Python threads can run while the kernel works.
  4. Calls at::add, which enters the dispatcher.
What changes between a and a.t()?

Chapter 2

The dispatcher: keys, key sets and fallthroughs

Every operator has a table of kernels, one column per dispatch key; a call runs the highest-priority key it carries

Many separate concerns touch every operator. Autograd must record a node. Autocast must cast. A tracer must log. vmap must batch. The device decides which kernel adds. If add handled all of these itself, every operator would grow into the same tangle.

PyTorch splits them out. For each operator, the dispatcher keeps a table of function pointers with one entry per dispatch key. Edward Yang calls it a re-implementation of C++ virtual tables, with two differences: the tables are per operator, not per class, and the choice looks at all the arguments plus thread-local state Yang 2020.

Which key runs

A call first computes a key set: a bitset with one bit per key. Then it runs the highest-priority key in the set.

Kt
The keys a tensor argument carries in its TensorImpl. Every CPU tensor carries CPU, ADInplaceOrView, AutogradCPU and AutocastCPU.
Kinclude
Keys this thread adds to every call, for "modes" that are not tied to a tensor. By default: BackendSelect and ADInplaceOrView.
Kexclude
Keys this thread removes. Autocast is off by default because its keys sit in this set.
K
The final set. The dispatcher runs the highest-priority key in K that has a kernel for this operator.

Worked, torch.add(a, b) on CPU with autocast off: {CPU, ADInplaceOrView, AutogradCPU, AutocastCPU} ∪ {BackendSelect, ADInplaceOrView} − {AutocastCPU, …} = {AutogradCPU, ADInplaceOrView, BackendSelect, CPU}. The highest is AutogradCPU, so the autograd kernel runs first.

Priority is just the order of the keys in c10/core/DispatchKey.h. In PyTorch 2.10 the functionality keys you meet most have these numbers; higher runs first:

KeyNumberIts job
PythonTLSSnapshot42save the Python mode stack before anything else runs
AutocastCPU25cast inputs for operators on the autocast lists
Autograd∗22record a backward node
ADInplaceOrView20bump version counters, set up views
Functionalize15turn mutation into pure ops (for compilers)
Python12call __torch_dispatch__ subclasses and modes
BackendSelect11pick a backend for calls with no tensor input
CPU, CUDA, Meta50, 51, 65the backend kernels, below every functionality key

∗ AutogradFunctionality is 22. The per-backend keys you see printed, such as AutogradCPU (135), combine that functionality bit with a backend bit; Edward Yang describes the change in a 2024 reply on his post Yang 2020.

Key set arithmetic

Three bitsets combine into the final set, sorted by priority. The first key with a kernel wins. Turn on no_grad and compare with inference_mode.

Every set shown is what PyTorch 2.10 printed for torch.add on that tensor (torch._C._dispatch_keys, _dispatch_tls_local_include_set, _dispatch_tls_local_exclude_set). Exclude sets list only the keys that matter here; the printed sets also hold the autocast keys of eight other device types. Times: 1-element a + b, M5 Max.

Fallthroughs, fallbacks and redispatch

Not every key has work to do for every operator. add is not on any autocast list, so the AutocastCPU entry of add's table is a fallthrough: the dispatcher skips the key as if its bit were off. Three keys are registered this way for every operator at once, with one line each in the v2.10.0 source:

// aten/src/ATen/autocast_mode.cpp, and the same for ADInplaceOrView, BackendSelect
TORCH_LIBRARY_IMPL(_, AutocastCPU, m) {
  m.fallback(torch::CppFunction::makeFallthrough());
}

The _ means "every operator". That is a backend fallback: one registration fills a whole column of the table. A specific registration, such as AutocastCPU's kernel for mm, fills one cell and wins over the column Yang 2020.

When a kernel finishes its part, it redispatches: it calls the same operator again with its own key, and every key above it, masked off. The autograd kernel, for example, records its node and then calls the operator again "below autograd". The real table shows the difference:

Run this on a machine with PyTorch

import torch
a = torch.randn(3)
print(torch._C._dispatch_keys(a))
for op in ["aten::add.Tensor", "aten::mm"]:
    for row in torch._C._dispatch_dump_table(op).splitlines():
        if row.split(":")[0] in ("AutocastCPU", "AutogradCPU", "CPU"):
            print(op, row.split(":")[0], row.split("[")[-1])
output (torch 2.10)
DispatchKeySet(CPU, ADInplaceOrView, AutogradCPU, AutocastCPU)
aten::add.Tensor CPU kernel]
aten::add.Tensor AutogradCPU autograd kernel]
aten::add.Tensor AutocastCPU backend fallback]
aten::mm CPU kernel]
aten::mm AutogradCPU autograd kernel]
aten::mm AutocastCPU kernel]

Now build a dispatcher yourself: a priority list, a table with fallthroughs, key sets, and kernels that redispatch.

Autocast is on. Why does torch.add on two float32 CPU tensors skip AutocastCPU, while a @ b stops there?

Chapter 3

What each key does, then the kernel

Autocast casts, autograd records, ADInplaceOrView counts versions, the Python key calls your hooks, and ATen finally loops over the numbers

Follow a @ b on CPU, with autocast on and a.requires_grad True, from the top of the stack down.

Autocast (priority 25)

mm is on autocast's lower-precision list, so its kernel casts both inputs to the autocast dtype and redispatches. The default dtype is torch.bfloat16 on CPU and torch.float16 on CUDA (torch.get_autocast_dtype). Losses are on a cast-up-to-float32 list. Every other operator falls through and keeps its input dtypes.

Autocast sits above autograd on purpose. Its casts are ordinary operators, so they pass through autograd and are recorded. That is how gradients flow back through a cast to your float32 weights.

Autograd (priority 22)

The autograd kernels are generated from tools/autograd/derivatives.yaml. If any input requires a gradient, the kernel creates the backward node, saves what the formula needs, and sets the output's grad_fn. Then it redispatches below autograd. If no input requires a gradient, it just redispatches. Two real entries:

# tools/autograd/derivatives.yaml (v2.10.0), excerpt
- name: add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
  self: handle_r_to_c(self.scalar_type(), grad)
  other: handle_r_to_c(other.scalar_type(), maybe_multiply(grad, alpha.conj()))
- name: mm(Tensor self, Tensor mat2) -> Tensor
  self: mm_mat1_backward(grad, mat2, self.sym_sizes(), self.sym_strides(), self.layout(), 1)
  mat2: mm_mat2_backward(grad, self, mat2.sym_sizes(), mat2.sym_strides(), mat2.layout(), 1)

The add formulas use only grad, so its node saves no tensors. The mm formulas read mat2 and self, so its node saves both inputs. That difference is the memory cost of the backward pass, decided one line at a time.

ADInplaceOrView (priority 20)

For an in-place operator such as add_, this key bumps the version counter. For a view operator such as t(), it records how the view relates to its base. For anything else it falls through.

Functionalize and Python (priorities 15 and 12)

These keys appear only when something asks for them. Functionalize is switched on by compilers (Chapter 8) to rewrite mutation into pure operators. Python is switched on by a tensor subclass or a mode that defines __torch_dispatch__ (Chapter 9). Because it sits below autograd and autocast, a Python mode sees what they produced. Here is a real log:

Run this on a machine with PyTorch

import torch
from torch.utils._python_dispatch import TorchDispatchMode

class Log(TorchDispatchMode):
    def __torch_dispatch__(self, func, types, args=(), kwargs=None):
        out = func(*args, **(kwargs or {}))          # continue down the stack
        print(func, [a.dtype for a in args if isinstance(a, torch.Tensor)])
        return out

a, b = torch.randn(4, 4), torch.randn(4, 4)
with torch.autocast("cpu", dtype=torch.bfloat16), Log():
    c = a @ b
w = torch.randn(3, requires_grad=True); x = torch.randn(3)
with Log():
    (w * x).tanh().sum().backward()
output (torch 2.10)
aten._to_copy.default [torch.float32]
aten._to_copy.default [torch.float32]
aten.mm.default [torch.bfloat16, torch.bfloat16]
aten.mul.Tensor [torch.float32, torch.float32]
aten.tanh.default [torch.float32]
aten.detach.default [torch.float32]
aten.sum.default [torch.float32]
aten.ones_like.default [torch.float32]
aten.expand.default [torch.float32]
aten.detach.default [torch.float32]
aten.tanh_backward.default [torch.float32, torch.float32]
aten.mul.Tensor [torch.float32, torch.float32]
aten.detach.default [torch.float32]

The two casts come before mm: autocast ran first. The second half shows the backward pass, which the C++ engine runs through the same dispatcher: tanh_backward, then the mul that multiplies by x.

BackendSelect (priority 11)

torch.ones(3) has no tensor argument, so no tensor contributes a backend key. BackendSelect, which is always in the include set, has kernels for such factory functions. It reads the device argument and sends the call to that backend.

The kernel

At last the backend key runs an ATen kernel. For add the YAML said structured_delegate: add.out: the out-variant is the workhorse, and the plain and in-place versions are thin wrappers. Edward Yang lists the parts of a kernel: error checks (TORCH_CHECK), allocating the output, a dtype dispatch (a switch over float, double, bfloat16, …), parallelism across threads, and the inner loop Yang 2019. Pointwise kernels use TensorIterator, which handles broadcasting and type promotion once for all of them.

The inner loop is vectorized: one CPU instruction handles a short vector of numbers. A 128-bit register holds 4 float32 values (ARM NEON); a 256-bit one holds 8 (AVX2); a 512-bit one holds 16 (AVX-512). The work splits across threads first, then each thread walks its share in vector steps, then mops up a short tail.

N
Elements to process.
T
Threads sharing the work.
L
Lanes: values per vector instruction (4, 8 or 16 float32).
steps
Vector instructions each thread issues for one operation.
tail
Elements each thread handles one at a time at the end.

Worked: N = 1,000,000, T = 6, L = 4 (the values in the kernel torch.compile generated on the M5 Max, Chapter 8): each thread gets about 166,667 elements, so about 41,666 vector steps and a tail of up to 3.

How a CPU kernel walks the numbers

Each cell is one element. Colour bands are threads; boxes are vector steps; red-edged cells are the scalar tail.

70

Vector lanes L

Threads T

Lane counts are for float32 in 128-, 256- and 512-bit registers. Real ATen splits work in grains (at::parallel_for) and skips threads for small tensors, so tiny N often runs on one thread; this toy always splits evenly.

Each key's rules decide the dtype that comes out. Predict them, then run them.

Why does a __torch_dispatch__ mode see two _to_copy calls before mm under autocast?

Chapter 4

The price of eager mode

Running one operator at a time pays the per-call price again and again, and sends every intermediate result through memory

PyTorch's normal mode is eager: each line of Python runs its operator at once and returns a finished tensor. That is why you can print, branch and debug anywhere. It also means PyTorch only ever sees one operator at a time. Two costs follow.

The per-call price. Chapter 0 measured it: about 376 ns per call on CPU before any work. A model with many small operators spends its time there.

Memory traffic. Take torch.relu(x * a + b) on a million floats. Eager mode runs three kernels. mul reads x and a and writes a temporary. add reads that temporary and b and writes another. relu reads it and writes the result. The arithmetic is tiny; moving the bytes is the real work. Kernels like these are memory bound.

k
The number of kernel calls: 3 in eager mode here, 1 when the chain is fused.
bytes
Everything every kernel reads plus everything it writes.
BW
The memory bandwidth the kernels reach.
t
The time for the whole chain.

Worked, N = 106 float32: eager bytes = mul (2 in + 1 out) + add (2 + 1) + relu (1 + 1) = 8 × 4 MB = 32 MB. Fused, one kernel reads x, a, b once and writes once: 4 × 4 MB = 16 MB. Measured on the M5 Max: eager 0.49 ms, fused by torch.compile 0.214 ms: 2.3×, close to the 2× that the bytes predict.

Fusion means running a chain of operators as one kernel that keeps intermediate values in registers. It needs to see the whole chain first. That is the reason for every graph capture tool in Chapters 7 and 8.

Eager against fused

A chain of k pointwise ops, each reading one tensor and writing one. Eager runs k kernels; fused runs one. Bars split each time into per-call price (purple) and moving bytes (yellow).

4
10⁶

Model only. c0 = 376 ns and an effective 55 GB/s, both from the M5 Max one-thread measurements (12 MB moved in 217.6 µs by a 106-element add). Real fused kernels also pay a compile cost once (Chapter 8) and can be limited by arithmetic, not bytes.

Now measure the per-call price yourself. The total work stays fixed; only the number of calls changes.

A fused kernel computes relu(x * a + b) on N floats. How many bytes does it move, and how does that compare with eager mode?

Chapter 5

The caching allocator

Why nvidia-smi shows more memory than your tensors use, what empty_cache() really frees, and where fragmentation comes from

Every operator allocates its output. A training step allocates thousands of tensors and frees most of them again. Asking the GPU driver each time (cudaMalloc, cudaFree) would be slow, and freeing can force the CPU to wait for the GPU. So PyTorch keeps freed memory for itself and hands it out again. In the documentation's words, this "allows fast memory deallocation without device synchronizations. However, the unused memory managed by the allocator will still show as if used in nvidia-smi" CUDA semantics, PyTorch 2.10 docs.

The rules

These are the constants and rules in v2.10.0 (c10/core/AllocatorConfig.h, c10/cuda/CUDACachingAllocator.cpp):

So there are two numbers. torch.cuda.memory_allocated() counts bytes in blocks that tensors are using. torch.cuda.memory_reserved() counts every segment the allocator holds. nvidia-smi sees the reserved memory, plus the memory the CUDA context itself takes.

allocated
Bytes in blocks that live tensors use (memory_allocated).
reserved
Bytes in all segments the allocator holds (memory_reserved).
waste
The share of reserved memory that is cached but not in use at this moment.

Worked, from the lab below: at peak, 47.1 MiB allocated in 58.0 MiB reserved, so waste = 1 − 47.1 / 58.0 = 19%. Between steps, with the activations freed, the same 58 MiB holds only 12 MiB of weights.

The caching allocator, step by step

Each bar is a segment (one cudaMalloc), drawn to scale. Green blocks hold live tensors; yellow blocks are free and cached. Run steps, change how the batch size behaves, then press empty_cache().

The same rules and constants as the lab and PyTorch 2.10's allocator (one stream, no memory limit). The workload is illustrative: 4 weights of about 3 MiB kept for the whole run; per step, 6 activations of B × 96 KiB, 20 small temporaries of B × 1000 bytes and one buffer of B × 512 KiB. The bars show the moment of peak use inside the step.

What empty_cache() does, and does not do

It returns every completely free segment to the driver, so other programs can use it. It cannot free memory that live tensors use, and it cannot move tensors to close the gaps. A segment with one small live block stays reserved. The docs say it plainly: empty_cache releases "all unused cached memory", but it "can not increase the amount of GPU memory available for PyTorch" CUDA semantics, PyTorch 2.10 docs.

Fragmentation and expandable segments

Fragmentation is free memory in pieces too small to use. The classic cause is a batch size that changes a little. A segment sized for batch N cannot hold batch N + 1, so a new segment is made, and the old one keeps a useless sliver. In the device, pick "grows" and watch reserved memory climb in stairs while old segments sit half used. The allocator's own design note says that in a model "50+ layers deep, this pattern might repeat 50+ times creating many slivers" allocator source note.

The option PYTORCH_ALLOC_CONF=expandable_segments:True changes the plan. The allocator reserves a huge range of virtual addresses and maps physical memory into it page by page as it grows, so allocations tile into one segment that can expand. It is marked experimental and is off by default in 2.10. (PYTORCH_CUDA_ALLOC_CONF still works as an alias.) Another knob, max_split_size_mb, stops the allocator from splitting blocks above a size, which keeps big blocks whole for big requests.

Run this on a machine with a CUDA GPU (not run for this page: the test machine has none)

import torch
x = torch.empty(1000, 1000, device="cuda")       # 4,000,000 bytes
print(torch.cuda.memory_allocated(), torch.cuda.memory_reserved())
del x                                              # block goes back to the cache
print(torch.cuda.memory_allocated(), torch.cuda.memory_reserved())
torch.cuda.empty_cache()                           # now the segment is returned
print(torch.cuda.memory_reserved())
torch.cuda.memory._record_memory_history()          # then run some steps, and:
torch.cuda.memory._dump_snapshot("snap.pickle")       # open at pytorch.org/memory_viz

By the rules above, expect 4,000,256 bytes allocated (rounded to a multiple of 512) in 20,971,520 reserved (a 20 MiB segment), then 0 in 20,971,520 after del, then 0 after empty_cache().

Now build the allocator: rounding, segment sizes, and best fit.

After del of every activation and torch.cuda.empty_cache(), reserved memory is 20 MiB while only 12 MiB of weights are allocated. Why?

Chapter 6

The autograd engine

backward() hands the graph to a C++ engine: it counts dependencies, sums gradients in buffers, and runs nodes from a ready queue, with one worker thread per GPU

Lesson 2 showed the graph: grad_fn nodes linked by next_functions. Calling loss.backward() hands that graph to the engine in torch/csrc/autograd/engine.cpp. The engine must solve one problem: run every node exactly once, and only after all the gradients flowing into it have arrived and been added up.

Dependencies and the ready queue

  1. Count dependencies. Walk the graph from the root. For every edge into a node, add 1 to that node's count.
  2. Buffer and sum. Each node gets an input buffer. A gradient that arrives is added into it, and the count goes down by 1.
  3. Ready when zero. A node whose count reaches 0 has its full gradient. It goes into a ready queue.
  4. Run. A worker takes a node from the queue, calls its backward formula, and sends each output gradient to the next node along next_functions.
p → v
Every edge from a node p into node v. A tensor used twice in forward gives two edges.
ḡp→v
The gradient node p sends to v when p runs.
ḡv
The total gradient v needs before its own formula can run.
deps(v)
Edges into v whose gradient has not arrived yet.

Worked: for h = w * x + b and loss = (h.tanh() * h).sum(), h's node AddBackward0 has two parents: the top MulBackward0 directly, and TanhBackward0. So deps = 2. It runs only after TanhBackward0 has run, with the sum of both gradients.

The ready queue is a priority queue. Among ready nodes it picks the one with the highest sequence number: nodes are numbered as forward creates them, so the newest runs first, which keeps backward close to the reverse of forward. In PyTorch 2.10 the example above numbers its nodes MulBackward0 (w·x) 0, AddBackward0 1, TanhBackward0 2, the top MulBackward0 3, SumBackward0 4. The two AccumulateGrad leaf nodes print 18446744073709551615, the largest 64-bit number, so a leaf's gradient is written as soon as it is ready.

A thread per device

The engine's comments describe the threads: "The CUDA, XLA threads are shared among all invocations of backwards via device_ready_queues_, while the caller thread is dedicated to processing work for devices" such as the CPU engine.cpp. So CPU nodes run on the thread that called backward(), and each GPU has one long-lived worker thread with its own queue. A gradient's device decides which queue its node joins. Two GPUs can run their halves of backward at the same time.

The engine at work

A model split across two GPUs: h = relu(x @ W1) on cuda:0, then z = h.to("cuda:1") @ W2 and loss = z.sum() + z.pow(2).sum() on cuda:1. Each tick, every device thread runs one ready node. Badges are dependency counts.

Node names, the dependency rule, newest-first order and the thread per device follow PyTorch 2.10's engine. Device placement follows the gradient: ToCopyBackward0 receives its gradient on cuda:1 and returns it on cuda:0. One node per thread per tick is a simplification; real nodes take different times.

Now write the engine's two key rules yourself, on real grad_fn nodes.

In loss = (h.tanh() * h).sum(), what would go wrong if h's node ran as soon as its first gradient arrived?

Chapter 7

Capturing graphs: TorchScript, fx and export

Four ways to turn a Python model into a graph, and the one question that separates them: is the graph always right?

A graph is the model as data: a list of operators and the tensors that flow between them. With a graph you can fuse operators, plan memory, or run the model where there is no Python at all. Getting a graph out of arbitrary Python is the hard part. The PyTorch 2 paper reviews the attempts Ansel 2024, §2.

The four tools

f(x)
What your Python model returns on input x.
G(x)
What the captured graph returns.
guards(x)
The checks the capture recorded (shapes, dtypes, constants). If a guard fails, a sound system refuses or captures again; it never runs a wrong graph.

Worked: torch.export of a model with if x.shape[0] > 2, traced with 2 rows and a dynamic batch dimension, raised UserError: Constraints violated (n)!: it would not pretend the other branch does not exist. torch.jit.trace of the same model returned the 2-row branch for 3 rows, silently wrong.

The grid below is the result of running every tool on six small programs in PyTorch 2.10, then calling each captured version on inputs that take the other path.

Which capture survives what

Pick a program and a tool, or tap a cell. Green: correct on new inputs. Yellow: works, but drops a Python side effect. Purple: refused with an error. Red: silently wrong.

Every cell is a real run on PyTorch 2.10 (CPU). Captured with a 2-element input whose sum is negative, checked on a 3-element input and a positive one. export used a dynamic first dimension; compile used backend="eager". Error texts are shortened.

torch.fx: a graph you can edit

fx is mainly a toolkit for graph rewriting: trace, change the graph with Python, regenerate code. Here is a real trace of a block with a linear layer, a scale and a shift:

Run this on a machine with PyTorch

import torch, torch.nn as nn, torch.fx as fx, operator

class Block(nn.Module):
    def __init__(self):
        super().__init__()
        self.lin = nn.Linear(4, 4)
        self.scale = nn.Parameter(torch.ones(4)); self.shift = nn.Parameter(torch.zeros(4))
    def forward(self, x):
        h = self.lin(x)
        return torch.relu(h * self.scale + self.shift)

gm = fx.symbolic_trace(Block())
print(gm.graph)
output (torch 2.10)
graph():
    %x : [num_users=1] = placeholder[target=x]
    %lin : [num_users=1] = call_module[target=lin](args = (%x,), kwargs = {})
    %scale : [num_users=1] = get_attr[target=scale]
    %mul : [num_users=1] = call_function[target=operator.mul](args = (%lin, %scale), kwargs = {})
    %shift : [num_users=1] = get_attr[target=shift]
    %add : [num_users=1] = call_function[target=operator.add](args = (%mul, %shift), kwargs = {})
    %relu : [num_users=1] = call_function[target=torch.relu](args = (%add,), kwargs = {})
    return relu

A pass walks the nodes and rewrites them. This one fuses mul then add into torch.addcmul:

def fuse_mul_add(gm):
    for node in list(gm.graph.nodes):
        if node.op == "call_function" and node.target is operator.add:
            mul, b = node.args
            if isinstance(mul, fx.Node) and mul.target is operator.mul and len(mul.users) == 1:
                x, a = mul.args
                with gm.graph.inserting_after(node):
                    new = gm.graph.call_function(torch.addcmul, (b, x, a))
                node.replace_all_uses_with(new)
                gm.graph.erase_node(node); gm.graph.erase_node(mul)
    gm.graph.lint(); gm.recompile()

fuse_mul_add(gm)
print(gm.code)
output (torch 2.10)
def forward(self, x):
    lin = self.lin(x);  x = None
    scale = self.scale
    shift = self.shift
    addcmul = torch.addcmul(shift, lin, scale);  shift = lin = scale = None
    relu = torch.relu(addcmul);  addcmul = None
    return relu

The rewritten module gives the same output (checked with torch.allclose: True). The two weaknesses, also run for real:

output (torch 2.10)
# fx.symbolic_trace of:  if x.sum() > 0: return x + 1 ... return x - 1
TraceError: symbolically traced variables cannot be used as inputs to control flow
# fx.symbolic_trace of:  return torch.rand(3) + x   (the paper's example)
def forward(self, x):
    _tensor_constant0 = self._tensor_constant0
    add = _tensor_constant0.add(x);  _tensor_constant0 = x = None
    return add

torch.export: a sound graph for deployment

from torch.export import export, Dim
ep = export(Block(), (torch.randn(2, 4),))
print(ep.graph_module.code); print(ep.graph_signature)
output (torch 2.10)
def forward(self, p_scale, p_shift, p_lin_weight, p_lin_bias, x):
    linear = torch.ops.aten.linear.default(x, p_lin_weight, p_lin_bias);  x = p_lin_weight = p_lin_bias = None
    mul = torch.ops.aten.mul.Tensor(linear, p_scale);  linear = p_scale = None
    add = torch.ops.aten.add.Tensor(mul, p_shift);  mul = p_shift = None
    relu = torch.ops.aten.relu.default(add);  add = None
    return (relu,)

# inputs
p_scale: PARAMETER target='scale'
p_shift: PARAMETER target='shift'
p_lin_weight: PARAMETER target='lin.weight'
p_lin_bias: PARAMETER target='lin.bias'
x: USER_INPUT

# outputs
relu: USER_OUTPUT

The graph now holds ATen operators (torch.ops.aten.*) and lists the weights as explicit inputs. Shapes are fixed unless you say otherwise: calling it on 7 rows raises AssertionError: Guard failed: x.size()[0] == 2. With dynamic_shapes={"x": {0: Dim("batch")}} the batch dimension becomes a symbol and 7 rows run. A branch on a value raises GuardOnDataDependentSymNode; rewrite it with torch.cond, which export keeps as a real branch:

output (torch 2.10): export of torch.cond(x.sum() > 0, lambda x: x + 1, lambda x: x - 1, (x,))
def forward(self, x):
    sum_1 = torch.ops.aten.sum.default(x)
    gt = torch.ops.aten.gt.Scalar(sum_1, 0);  sum_1 = None
    true_graph_0 = self.true_graph_0
    false_graph_0 = self.false_graph_0
    cond = torch.ops.higher_order.cond(gt, true_graph_0, false_graph_0, (x,));  gt = true_graph_0 = false_graph_0 = x = None
    getitem = cond[0];  cond = None
    return (getitem,)

Now build the core of torch.fx yourself: proxies that record, an interpreter, and the fusion pass.

You need one graph of your model to ship to a server with no Python, and you want an error rather than a silently wrong graph. Which tool?

Chapter 8

Inside torch.compile

TorchDynamo reads Python bytecode and pulls out graphs with guards; AOTAutograd adds the backward; Inductor fuses and writes the kernels

torch.compile keeps eager mode's freedom and still gets graphs. It is three components in a row, described in the PyTorch 2 paper Ansel 2024.

1. TorchDynamo: graphs from bytecode

CPython lets a program replace the function that runs each Python frame (PEP 523). Dynamo installs its own. Before a function runs, Dynamo steps through its bytecode symbolically, one instruction at a time. Tensor operations go into an FX graph. Everything the graph depends on, such as shapes, dtypes and Python constants, becomes a guard Ansel 2024, §3.2–3.4.

Dynamo caches the compiled graph and its guards on the code object. The next call only checks the guards.

Sometimes Dynamo meets code it cannot put in a graph, such as a call into an unknown library. Then it makes a graph break: it compiles the graph so far, lets Python run that part, and resumes in a new graph Ansel 2024, §3.8. That is why it never fails outright. Here is a real break:

Run this on a machine with PyTorch

import torch
def show(gm, example_inputs):                # a custom backend: print, then run as is
    print(gm.code); return gm.forward
def f(x, w):
    y = torch.relu(x @ w)
    print("hello from Python")              # not a tensor op
    return (y * 2).sum()
torch.compile(f, backend=show)(torch.randn(8, 4), torch.randn(4, 4))
ex = torch._dynamo.explain(f)(torch.randn(8, 4), torch.randn(4, 4))
print(ex.graph_count, ex.graph_break_count, ex.break_reasons[0].reason)
output (torch 2.10)
def forward(self, L_x_ : torch.Tensor, L_w_ : torch.Tensor):
    l_x_ = L_x_
    l_w_ = L_w_
    matmul = l_x_ @ l_w_;  l_x_ = l_w_ = None
    y = torch.relu(matmul);  matmul = None
    return (y,)
hello from Python
def forward(self, L_y_ : torch.Tensor):
    l_y_ = L_y_
    mul = l_y_ * 2;  l_y_ = None
    sum_1 = mul.sum();  mul = None
    return (sum_1,)
hello from Python
2 1 Failed to trace builtin operator
  Explanation: Dynamo does not know how to trace builtin operator `print` with argument types ['str'] (has_kwargs False)
  Hint: Avoid calling builtin `print` with argument types ['str']. Consider using an equivalent alternative function/method to `print`.
  ... (two more hints and a link to the graph-break site follow)

Two graphs, one break, and the print still runs every call. (The second "hello" comes from explain, which runs f again.) Dynamo's guard checks are cheap: the paper measured its capture overhead at 5% for inference and 1% for training, against 38% and 90% for the older Lazy Tensors approach Ansel 2024, Table 2. It captured 74 of 80 TorchBench models, against 36 for TorchScript Table 1.

2. AOTAutograd: the backward graph, ahead of time

Dynamo captures only the forward. AOTAutograd runs the ordinary autograd engine on fake tensors (shapes, no data) and records forward and backward together as one joint graph. A min-cut algorithm then splits it into a forward and a backward graph, choosing which activations to save and which are cheaper to recompute Ansel 2024, §3.9. It also decomposes large operators into a smaller core set (191 decompositions at the time of the paper) and removes mutation. A real split for (x * w).tanh().sum():

output (torch 2.10): functorch.compile.aot_function with printing compilers
== forward graph ==
def forward(self, primals_1, primals_2):
    mul = torch.ops.aten.mul.Tensor(primals_1, primals_2);  primals_2 = None
    tanh = torch.ops.aten.tanh.default(mul);  mul = None
    detach = torch.ops.aten.detach.default(tanh)
    sum_1 = torch.ops.aten.sum.default(tanh);  tanh = None
    return (sum_1, primals_1, detach)
== backward graph ==
def forward(self, primals_1, detach, tangents_1):
    expand = torch.ops.aten.expand.default(tangents_1, [3]);  tangents_1 = None
    detach_1 = torch.ops.aten.detach.default(detach);  detach = None
    tanh_backward = torch.ops.aten.tanh_backward.default(expand, detach_1);  expand = detach_1 = None
    mul_1 = torch.ops.aten.mul.Tensor(tanh_backward, primals_1);  tanh_backward = primals_1 = None
    return (None, mul_1)

The forward returns two extra outputs, primals_1 (x) and the tanh result: exactly what the backward needs. Those are the saved tensors, now chosen by a compiler instead of by each node.

3. TorchInductor: fused kernels

Inductor lowers the graph to a loop-level IR, decides which operators to fuse, and writes code: Triton for GPUs, C++ with OpenMP for CPUs Ansel 2024, §4. Fusion is where most of the speed comes from. With fusion and inlining turned off, the paper's HuggingFace inference speedup fell from 1.91× to 0.80×, a slowdown Table 4. Here is the real kernel Inductor wrote for torch.relu(x * a + b) on the M5 Max:

output (torch 2.10): torch._inductor.utils.run_and_get_code, excerpt
cpp_fused_add_mul_relu_0 = async_compile.cpp_pybinding(['const float*', 'const float*', 'const float*', 'float*'], r'''
extern "C"  void  kernel(const float* in_ptr0, const float* in_ptr1, const float* in_ptr2, float* out_ptr0)
{
    #pragma omp parallel num_threads(6)
    {
            #pragma omp for
            for(int64_t x0=static_cast<int64_t>(0LL); x0<static_cast<int64_t>(1000000LL); x0+=static_cast<int64_t>(4LL))
            {
                        auto tmp0 = at::vec::Vectorized<float>::loadu(in_ptr0 + static_cast<int64_t>(x0), static_cast<int64_t>(4));
                        auto tmp1 = at::vec::Vectorized<float>::loadu(in_ptr1 + static_cast<int64_t>(x0), static_cast<int64_t>(4));
                        auto tmp3 = at::vec::Vectorized<float>::loadu(in_ptr2 + static_cast<int64_t>(x0), static_cast<int64_t>(4));
                        auto tmp2 = tmp0 * tmp1;
                        auto tmp4 = tmp2 + tmp3;
                        auto tmp5 = at::vec::clamp_min(tmp4, decltype(tmp4)(0));
                        tmp5.store(out_ptr0 + static_cast<int64_t>(x0));
            }
    }
}''')

One kernel, three loads, one store, 4 floats per step, 6 threads: Chapter 3's loop and Chapter 4's fusion, written by a compiler. First call (compiling): 4.0 s. Then eager 0.49 ms against compiled 0.214 ms per call. Across 180+ models on an A100, the paper reports geometric-mean speedups of 2.27× for inference and 1.41× for training Ansel 2024, Abstract.

Tcompile
The one-time cost of capturing and compiling (and of every recompile).
teager
Time per call without compiling.
tcompiled
Time per call with the compiled code.
n∗
Calls needed before compiling has paid for itself.

Worked, the kernel above: n∗ = 4.0 s / (0.49 − 0.214) ms = 4.0 / 0.000276 ≈ 14,500 calls. A training run makes millions of calls. A script that runs the model ten times should not compile. Every recompile adds another Tcompile.

Guards and recompiles

A cached graph is reused only while its guards pass. Change a shape, a dtype or requires_grad, and Dynamo compiles again. After the second shape it marks the size as dynamic: a symbol that covers many sizes. Sizes 0 and 1 are always specialised, because broadcasting treats them differently Ansel 2024, §5.2. Play with the cache:

Dynamo's guard cache

Each button calls f = torch.compile(lambda x: (x * 2).sum()) once. The cache lists compiled entries with their guards. A call reuses the first entry whose guards pass; if none pass, Dynamo compiles a new one.

Behaviour recorded from PyTorch 2.10 with a counting backend: (8, 4) compiled; (16, 4) recompiled with a symbolic size s77; (32, 4) and (64, 4) reused it; (1, 4) compiled a static entry; float64 and requires_grad each compiled once more. torch._dynamo.config.recompile_limit is 8; past it, Dynamo stops compiling that function and runs it eagerly. Guard texts are simplified.

Which part of torch.compile decides which activations are saved for backward?

Chapter 9

Hooking in: subclasses, modes and custom ops

__torch_function__ sees the Python API; __torch_dispatch__ sees ATen operators below autograd. Tools such as FakeTensor and FlopCounterMode are built on them.

PyTorch gives Python code two places to step into every call.

What each hook sees

The same code, seen from two heights. Blue chips: what __torch_function__ receives. Purple chips: what __torch_dispatch__ receives. lin = nn.Linear(8, 4), ln = nn.LayerNorm(4), x is (2, 8).

Logged on PyTorch 2.10 with one TorchFunctionMode and one TorchDispatchMode active together. Names are shortened: aten.addmm.default is shown as addmm.

Tools built on __torch_dispatch__

FakeTensor is a subclass that holds shapes, dtypes and devices but no data. Its operators compute output metadata with each operator's meta function. Dynamo and AOTAutograd trace with it (Ansel 2024, §3.5, §3.9), and you can use it to check a model's shapes without memory:

Run this on a machine with PyTorch

import torch, torch.nn as nn
from torch._subclasses.fake_tensor import FakeTensorMode
with FakeTensorMode():
    big = nn.Linear(16384, 16384)        # 268M weights: 1 GiB if it were real
    y = big(torch.randn(32, 16384))
    print(type(y).__name__, y.shape, y.dtype)
print(torch.empty(10**12, device="meta").shape)   # the meta device: also no data
output (torch 2.10)
FakeTensor torch.Size([32, 16384]) torch.float32
torch.Size([1000000000000])

FlopCounterMode is a dispatch mode that counts the FLOPs of matrix multiplies and convolutions, using the convention that one multiply-add is 2 FLOPs:

m
Rows of A: usually the batch size times the sequence length.
k
The shared inner dimension: one multiply and one add per k.
n
Columns of B: the output features.
FLOPs
Floating-point operations for the whole product.

Worked, a 512 → 1024 → 10 MLP on a batch of 64: forward = 2·64·512·1024 + 2·64·1024·10 = 68,419,584. The backward adds 69,730,304: weight gradients for both layers, and the input gradient of the second layer only, because x needs no gradient. Usually backward costs about twice the forward; here it is about once.

from torch.utils.flop_counter import FlopCounterMode
model = nn.Sequential(nn.Linear(512, 1024), nn.ReLU(), nn.Linear(1024, 10))
with FlopCounterMode(display=False) as fc:
    model(torch.randn(64, 512)).sum().backward()
print(fc.get_total_flops(), {str(k): v for k, v in fc.get_flop_counts()["Global"].items()})
output (torch 2.10)
138149888 {'aten.addmm': 68419584, 'aten.mm': 69730304}

mini-torch has no __torch_function__, so the lab builds the same single choke point with a wrapper class and counts FLOPs through it.

Your own operators

Sometimes you need an operator PyTorch does not have: a kernel from another library, or your own CUDA. torch.library.custom_op registers a Python function as a real dispatcher operator. Give it a fake implementation (output shapes, for FakeTensor and torch.compile) and an autograd formula, then let opcheck test the registration:

import torch, numpy as np
from torch import Tensor

@torch.library.custom_op("mylib::soft_clip", mutates_args=())
def soft_clip(x: Tensor, limit: float) -> Tensor:
    return torch.from_numpy(limit * np.tanh(x.numpy() / limit))   # opaque to PyTorch

@soft_clip.register_fake
def _(x, limit):
    return torch.empty_like(x)                                    # shape and dtype only

def setup_context(ctx, inputs, output):
    ctx.save_for_backward(inputs[0]); ctx.limit = inputs[1]
def backward(ctx, g):
    (x,) = ctx.saved_tensors
    return g * (1 - torch.tanh(x / ctx.limit) ** 2), None
soft_clip.register_autograd(backward, setup_context=setup_context)

x = torch.tensor([-6.0, -1.0, 0.0, 1.0, 6.0], requires_grad=True)
y = torch.ops.mylib.soft_clip(x, 3.0); print(y)
y.sum().backward(); print(x.grad)
print(torch.library.opcheck(soft_clip, (torch.randn(4, requires_grad=True), 3.0)))
print(torch.compile(lambda t: soft_clip(t, 3.0) * 2, fullgraph=True)(torch.ones(2)))
output (torch 2.10)
tensor([-2.8921, -0.9645,  0.0000,  0.9645,  2.8921],
       grad_fn=<GeneratedBackwardFor_mylib_soft_clip_defaultBackward>)
tensor([0.0707, 0.8966, 1.0000, 0.8966, 0.0707])
{'test_schema': 'SUCCESS', 'test_autograd_registration': 'SUCCESS', 'test_faketensor': 'SUCCESS', 'test_aot_dispatch_dynamic': 'SUCCESS'}
tensor([1.9291, 1.9291])

The function body may call NumPy because the dispatcher hands it plain tensors below autograd. With fullgraph=True, torch.compile keeps the op in one graph as an opaque node instead of breaking, thanks to the fake implementation.

For speed, write the kernel in C++ or CUDA and build it as a C++ extension. torch.utils.cpp_extension.load_inline compiles a source string on the spot (5 s on the M5 Max):

from torch.utils.cpp_extension import load_inline
src = r"""
#include <torch/extension.h>
torch::Tensor scale_add(torch::Tensor x, torch::Tensor a, torch::Tensor b) {
  TORCH_CHECK(x.sizes() == a.sizes() && a.sizes() == b.sizes(), "shapes must match");
  auto xc = x.contiguous(), ac = a.contiguous(), bc = b.contiguous();
  auto out = torch::empty_like(xc);
  const float* px = xc.data_ptr<float>(); const float* pa = ac.data_ptr<float>();
  const float* pb = bc.data_ptr<float>(); float* po = out.data_ptr<float>();
  for (int64_t i = 0; i < xc.numel(); ++i) po[i] = px[i] * pa[i] + pb[i];
  return out;
}"""
ext = load_inline(name="scale_add_ext", cpp_sources=src, functions=["scale_add"])
x, a, b = torch.randn(5), torch.randn(5), torch.randn(5)
print(torch.allclose(ext.scale_add(x, a, b), x * a + b))
ext.scale_add(x, a, torch.randn(4))
output (torch 2.10)
True
RuntimeError: shapes must match

A function bound this way is a plain C++ call: the dispatcher, autograd and torch.compile do not know it. To give it those, register it as an operator with TORCH_LIBRARY in C++ or wrap it with torch.library.custom_op as above. For CUDA, pass cuda_sources or build with CUDAExtension.

Your custom op works in eager mode, but torch.compile(fullgraph=True) fails on it. What is most likely missing?

Chapter 10

Leaving Python: export, ONNX and quantisation

How a trained model leaves the training process, and how int8 makes it four times smaller

A served model often runs where Python is unwelcome: a C++ server, a phone, another runtime. In PyTorch 2.10 every path starts from torch.export (Chapter 7):

Run this on a machine with PyTorch, plus onnx, onnxscript and onnxruntime

import torch, numpy as np, onnx, onnxruntime as ort
m = Block().eval()                                     # the Block from Chapter 7
torch.onnx.export(m, (torch.randn(2, 4),), "block.onnx", dynamic_shapes={"x": {0: "batch"}})
print([n.op_type for n in onnx.load("block.onnx").graph.node])
sess = ort.InferenceSession("block.onnx")
xx = torch.randn(3, 4)
out = sess.run(None, {sess.get_inputs()[0].name: xx.numpy()})[0]
print(out.shape, np.abs(out - m(xx).detach().numpy()).max())
output (torch 2.10, onnx 1.21, onnxscript 0.7.2, onnxruntime 1.31)
['Gemm', 'Mul', 'Add', 'Relu']
(3, 4) 5.960464477539063e-08

Four ONNX nodes, a symbolic batch dimension, and outputs that match PyTorch to about one float32 rounding step.

Quantisation at a glance

A float32 weight takes 4 bytes. Quantisation stores it as an 8-bit integer plus a shared scale and zero point. The model shrinks about 4×, and integer arithmetic can be faster.

x
A real value: a weight or an activation.
s
The scale: the gap between neighbouring representable values, (hi − lo) / 255 for a range [lo, hi].
z
The zero point: the integer that stands for 0.0, round(−128 − lo / s).
q
The stored 8-bit integer.
x̂
The value you get back. It is off from x by at most s / 2 inside the range.

Worked, range [−1, 3]: s = 4 / 255 = 0.015686, z = round(−128 + 1 / 0.015686) = round(−64.25) = −64. The value 1.0 becomes q = round(63.75) − 64 = 0, and comes back as 0.015686 × (0 + 64) = 1.0039: an error of 0.0039, under s / 2 = 0.0078.

Three schemes use this mapping. They differ in how the activation range is found:

SchemeWeightsActivationsUse it when
Dynamicint8, ahead of timerange measured on each batch as it runsLinear and LSTM layers on CPU; no data needed
Static (post-training)int8, ahead of timerange fixed by calibration: observers watch sample batchesconvolutional nets; you have a few hundred representative inputs
QAT (quantisation-aware training)trained with fake quantisationfake-quantised during trainingpost-training int8 loses too much accuracy; gradients pass the rounding by a straight-through estimator (lesson 2)

One scale or one per row?

Top: one weight row's values (blue ticks) and the integer grid (purple lines). Bottom: worst error per row, relative to that row's size. Rows grow from small to large.

Bits

Scale

2

An illustrative 16 × 64 weight: row r is Gaussian noise times a scale that grows from about 0.03 to 3 (the lab's matrix). Asymmetric affine quantisation, range widened to include 0, computed live.

In PyTorch 2.10, torch.ao.quantization.quantize_dynamic still runs, with a warning:

import torch, torch.nn as nn, io
from torch.ao.quantization import quantize_dynamic
torch.backends.quantized.engine = "qnnpack"          # the engine Apple silicon supports
m = nn.Sequential(nn.Linear(256, 256))
q = quantize_dynamic(m, {nn.Linear}, dtype=torch.qint8)
print(q)
def size(mod): b = io.BytesIO(); torch.save(mod.state_dict(), b); return len(b.getvalue())
print("state_dict bytes: float32", size(m), "  int8", size(q))
output (torch 2.10, qnnpack engine on Apple silicon)
DeprecationWarning: torch.ao.quantization is deprecated and will be removed in 2.10.
For migrations of users:
1. Eager mode quantization (torch.ao.quantization.quantize, torch.ao.quantization.quantize_dynamic), please migrate to use torchao eager mode quantize_ API instead
2. FX graph mode quantization (...), please migrate to use torchao pt2e quantization API instead (prepare_pt2e, convert_pt2e)
Sequential(
  (0): DynamicQuantizedLinear(in_features=256, out_features=256, dtype=torch.qint8, qscheme=torch.per_tensor_affine)
)
state_dict bytes: float32 265061   int8 69149

The new home of quantisation is the separate torchao library, which works on exported graphs. The maths is the formula above. The saved size fell 3.8×, a little short of 4× because scales and file headers stay.

Per-tensor int8 gives one scale for a whole weight matrix whose rows range from 0.03 to 3 in size. What happens to the small rows?

Chapter 11

Connections

A map of the source tree, the cheat sheet, honest limits, and where to go next

You can now read PyTorch's source with a purpose. Pick a directory to see what lives there, or press Follow torch.add to walk the files a single call touches.

Where things live (v2.10.0)

Tap a directory. The colour is its role on this page: blue Python, purple dispatch, green kernels, warm autograd, yellow memory.

Every path was checked against the v2.10.0 tag on GitHub; the Python packages also against the installed torch 2.10.0. Files under torch/csrc/autograd/generated/ do not exist in the repository: they are written at build time.

The cheat sheet

IdeaIn one line
The tensorPython handle → TensorImpl (sizes, strides, offset, dtype, device, key set, version, autograd meta) → StorageImpl (bytes). Views share storage.
The bindingGenerated from native_functions.yaml: parse args, check __torch_function__, release the GIL, call at::op.
The dispatcherK = (tensor keys ∪ include) − exclude; run the highest key with a kernel; fallthrough keys are skipped; kernels redispatch below themselves.
Key orderAutocast (25) > Autograd (22) > ADInplaceOrView (20) > Functionalize (15) > Python (12) > BackendSelect (11) > backend.
The kernelATen: checks, allocate output, dtype switch, threads, vectorized loop; structured ops delegate to .out.
Eager costt ≈ k·c0 + bytes / BW. Fewer, bigger, fused ops win.
Allocator512 B rounding; ≤1 MiB → 2 MiB segments; <10 MiB → 20 MiB; best fit; free blocks cached. reserved ≥ allocated; empty_cache frees only empty segments.
EngineCount dependencies, sum gradients in buffers, run when the count hits 0, newest first; CPU on your thread, one worker per GPU.
Capturejit.trace/script: deprecated. fx: editable, unsound. export: sound, whole graph, ATen IR. compile: graphs plus breaks plus guards.
torch.compileDynamo (bytecode → FX + guards) → AOTAutograd (joint graph, min-cut) → Inductor (fused Triton / C++). Break even at Tcompile / time saved per call.
Hooks__torch_function__: public API, above C++. __torch_dispatch__: ATen ops below autograd. FakeTensor, FlopCounterMode, custom_op + register_fake.
Deployexport → AOTInductor, ExecuTorch, ONNX (dynamo=True), export.save. int8: q = round(x/s) + z, per-channel weights; quantisation now lives in torchao.

Honest limits

Where this sits

Machine learning frameworks split into define-by-run (eager) designs such as PyTorch and define-and-run (graph) designs such as early TensorFlow. Users strongly preferred eager mode, so graph frameworks moved toward it Ansel 2024, §1. PyTorch went the other way: it kept eager mode as the truth and added capture on top, first by tracing and parsing, now by reading bytecode. JAX chose a middle path: its jit requires pure functions without data-dependent Python control flow Ansel 2024, §2.6.

Where to go next on this site:

The takeaway. A PyTorch call is a walk down a stack. The binding turns Python into C++. The dispatcher computes a key set and runs one layer at a time: autocast casts, autograd records, version counters tick, Python hooks look, and a vectorized kernel finally touches the numbers, in memory the caching allocator lent it. Graph compilers exist because doing this one operator at a time costs a fixed price per call and a trip through memory per result.
You want to know why torch.add is slow for tiny tensors. Which file shows the work done before any kernel runs on a CPU tensor with requires_grad=True?

Now press Present or Teach and explain, out loud and from memory, every layer a call to a @ b passes through with autocast on and a.requires_grad True. Then go back to the hero and check yourself.

PyTorch Internals: From a Python Call to a Kernel. Lesson 10 of PyTorch, Zero to Expert (The Builder's Toolkit). Every API, printed output, default and error text was run on PyTorch 2.10.0 (CPU, Apple M5 Max); source paths and constants were read at the v2.10.0 tag. Sources: J. Ansel, E. Yang, H. He, N. Gimelshein, A. Jain, M. Voznesensky, B. Bao, P. Bell, D. Berard, E. Burovski, et al., "PyTorch 2: Faster Machine Learning Through Dynamic Python Bytecode Transformation and Graph Compilation" (ASPLOS 2024, doi:10.1145/3620665.3640366), §1–6, Tables 1–4; E. Z. Yang, "PyTorch internals" (blog, May 16, 2019, blog.ezyang.com); E. Z. Yang, "Let's talk about the PyTorch dispatcher" (blog, September 10, 2020, blog.ezyang.com); PyTorch documentation, "CUDA semantics" (docs); A. Paszke et al., "PyTorch: An Imperative Style, High-Performance Deep Learning Library" (NeurIPS 2019, arXiv).
Back to Gleams