← Inference From First Principles

From Training to Execution

What training leaves behind, what must be true before it is executed, and what the first request pays that later ones do not.

Here is a small puzzle. The GPT-2 model on this machine has 124,439,808 parameters, stored as 32-bit floats. At four bytes each, that is 497,759,232 bytes. But the file holding them is 548,105,171 bytes. Where did the other 50,345,939 bytes come from?

They are not learned parameters. Most of them are twelve saved attention masks, one per layer, and 14,291 bytes are the file’s header. We will account for every byte below.

The puzzle is this chapter in miniature. We talk about “the model” as if it were one object, a block of learned numbers. What an inference runtime actually loads is a bundle: learned parameters, other saved tensors, an architecture definition, a tokeniser, default generation settings and the code that loads them. Any of those can change without a single weight changing. And even when the right bundle loads, it can run in the wrong state, with training behaviour switched on or gradient tracking quietly consuming memory.

So loading the weights is necessary but not sufficient. By the end of this chapter you will be able to:

  • identify exactly which files and tensors sit behind a model name;
  • tell apart the three separate PyTorch settings that people loosely call “inference mode”;
  • split “the first request was slow” into its real parts: importing libraries, loading the model, and warming up the first forward pass.

Where this sits

What Is Inference? timed one request and found that the forward pass dominated its measured stages. It treated the model as given, recorded only its name, and reported loading separately. (Its one-shot command timed loading as a stage; its repeated-request path reported it outside the stage table. Those are different measurement boundaries, which is one reason this chapter splits start-up costs carefully.)

This chapter opens the model box and adds two pieces to the Inference Lab:

  • an artefact manifest: file hashes plus an inventory of the loaded parameter tensors;
  • a readiness check: a quick report of the execution state the model is in.

Together these let a result say “this came from this artefact, run in this state”, which is much stronger than a model name. They are not a complete guarantee, and the chapter is careful to say what they leave out. We will speak of recorded identity and observed execution state, and keep words like “reproducible” for comparisons that check the whole environment.

For the wider Pi series the point is practical. The retrieval, memory and agent volumes call models by name through providers, and a name does not identify an artefact. The manifest is the local, checkable answer to “which model was that, exactly?” The same question returns in a weaker form when we reach provider APIs in Part VI.

What training leaves behind

Training produces parameter values. Packaging and publishing decide what travels with them: buffers, configuration, tokeniser files and generation defaults. For the GPT-2 snapshot used here, the manifest recorded seven files. (The command records whichever cached snapshot it finds; it does not enforce a revision, so save the reported snapshot id with every result.)

File Bytes SHA-256 (first 12 hex) What it is
model.safetensors 548,105,171 248dfc391186 Tensors
tokenizer.json 1,355,256 8414cab924d8 Tokeniser, serialised
vocab.json 1,042,301 196139668be6 Token strings to ids
merges.txt 456,318 1ce1664773c5 Byte-pair merge rules
config.json 665 0daed7749b4f Architecture hyperparameters
generation_config.json 124 ed0b32ac72c0 Default decoding settings
tokenizer_config.json 26 5e04eb606e3a Tokeniser options

Model artefact bundle

Only model.safetensors holds tensors. The other six files decide how those tensors are loaded and used, and each can change behaviour in its own way without touching a learned value:

If you change… What can happen
config.json (say, an incompatible layer count) Loading fails.
merges.txt Some inputs tokenise differently, so the model sees different ids. Not every id changes.
generation_config.json Decoding changes, if the calling library reads these defaults and the request does not override them.

Three different outcomes, a load failure, changed inputs and changed decoding, and none involves a weight. So before blaming the weights for a change in output, record the complete file set.

The sizes and hashes were produced by python examples/ch02/execution_modes.py manifest for cached snapshot 607a30d783dfa663caf39e06633721c8d4cfcd7e.

Where the 50 megabytes went

The saved file contains 160 named tensors. The loaded model reports 148 parameter tensors. Reading the file’s header shows the other twelve: one h.N.attn.bias tensor per transformer layer, each shaped 1 × 1 × 1024 × 1024 and stored as 32-bit floats. These are causal attention masks, saved alongside the weights but not trained.

The accounting closes exactly:

Component Bytes
148 parameter tensors (124,439,808 × 4 bytes) 497,759,232
12 saved masks (12 × 4,194,304) 50,331,648
Tensor data subtotal 548,090,880
Eight-byte length prefix plus JSON header 14,291
File size 548,105,171

Three lessons from this come back later:

  1. File size is not parameter bytes. Saved buffers and the container add to it.
  2. File contents are not memory use. A loader may transform or drop saved state, and the framework allocates more on top. The header tells us what is stored, not what stays resident after loading.
  3. A parameter digest misses buffers. The parameter_manifest and parameter_digest helpers in this chapter read named_parameters() only, not named_buffers(). A file hash would notice a changed mask; the parameter digest would not.

Three switches that look like one

Inference normally intends to leave the weights alone. But “the weights are frozen” is a policy you enforce at run time, not a property a PyTorch module has. Three separate controls are involved, and people often call any of them “inference mode”:

Switch How you set it What it controls What it does not do
Module mode model.eval() / model.train() Training-only layer behaviour, such as dropout and batch normalisation Disable gradients
Autograd context torch.no_grad() / torch.inference_mode() Whether operations inside the context are recorded for backpropagation (per thread) Change layer behaviour, or make weights read-only
Parameter trainability requires_grad, model.requires_grad_(False) Which parameters can accumulate gradients when recording is on Make the tensor storage read-only

Three switches that look like one

None of them stops code from writing directly into a weight tensor. A real “nothing changed” claim would hash the parameters before and after running the model. This chapter checks execution state and gradients; it does not do that before-and-after test.

The rest of this section takes the switches one at a time, with a measurement for each.

Module mode: dropout

The intuition. During training, dropout randomly switches off some activations so the network cannot lean on any single one. At inference you want the full, deterministic network, so dropout must be off.

The mechanism. Dropout zeroes each activation with probability \(p\) and scales up the survivors so the expected value stays the same. For an activation \(x\):

\[ y = \frac{m \odot x}{1-p}, \qquad m_i \sim \text{Bernoulli}(1-p) \]
In evaluation mode no mask is applied, and \(y = x\). GPT-2 uses dropout with \(p = 0.1\) on the embeddings, the attention weights and the residual connections.

The measurement. The probe ran the same 10-token input twice with dropout active and compared the full logit tensors:

Mode Two runs of the same input Last-position top token
Training (dropout on) Logits differed by up to 41.68 Agreed
Evaluation (dropout off) Logits matched exactly Agreed

So dropout changed the scores a lot without changing which token came out on top for this one input. Scores and selected tokens are different things, and one probe cannot tell you how often the selected token would change.

Why it matters. Leaving dropout on does not raise an error. It quietly produces different scores, which may or may not change the text. If an evaluation run varies unexpectedly, checking model.training is a cheap first test (though not the only one; Correctness, Determinism and Reproducibility covers the others).

In the recorded Transformers 5.17.0 environment, from_pretrained() returned GPT-2 with training = False already. That is a fact about this version and model class, not a promise. An inference entry point should set and check the mode it wants.

Autograd context: memory

The intuition. When gradient recording is on, PyTorch keeps intermediate results so a backward pass can use them later. Inference never runs a backward pass, so that memory is pure waste.

The measurement. For each mode, the harness started a fresh process, loaded GPT-2, warmed it up with an 8-token forward pass, then processed 512 tokens. It recorded the process’s peak working set (Windows’s high-water mark for the whole process) before and after the measured pass.

Mode Peak working set after forward Backward possible Output type
Autograd enabled 1,768.7 MB yes ordinary tensor with grad_fn
torch.no_grad() 1,272.0 MB no ordinary tensor
torch.inference_mode() 1,272.5 MB no inference tensor

With autograd on, the peak rose by about 528 MB during the forward pass. With either graph-free mode it rose by about 32 MB. On this setup, recording the graph substantially raised peak memory.

That 496 MB gap is not an exact count of saved activations. A process-wide peak includes temporary allocations and allocator effects, and it hides any allocation that stays below an earlier peak. It shows that the difference is large, not precisely what it consists of.

Why it might be large. Some arithmetic gives a sense of scale:

  • One dense attention-score array at 512 positions, with 12 heads and 4-byte numbers, is 12 × 512 × 512 × 4 = 12,582,912 bytes, about 12.6 MB. With autograd on, tensors like this, plus feed-forward activations, may be kept for all twelve layers.
  • The full logits array, 512 × 50,257 × 4 bytes, is about 103 MB. That one is needed in every mode by this unoptimised implementation.

The attention-score term grows with the square of the sequence length. That does not prove that the total overhead grows quadratically, because feed-forward activations, temporary buffers and the way peaks are measured also contribute. Exercise 5 tests the shape over several lengths.

Why it matters in a loop. The uncached loop from What Is Inference? recomputes the whole prefix at every step. Leaving grad mode on can create unwanted autograd state on each step. How much survives between steps depends on whether earlier outputs are still referenced, so you cannot simply multiply this one-pass difference by the number of tokens generated.

no_grad versus inference_mode

Both contexts stop graph recording, and their measured peaks, 1,272.0 MB and 1,272.5 MB, are too close for this single-run set-up to separate. The real difference is in what you can do with the output afterwards:

torch.no_grad() torch.inference_mode()
Records backward graph No No
Extra bookkeeping skipped — Also skips version-counter and view tracking for tensors created inside
Output Ordinary tensor Inference tensor (is_inference() == True in this experiment)
Later use in gradient-recorded work Generally straightforward Restricted; may need conversion, for example cloning outside inference mode, at a cost you should measure

So use inference_mode() when the whole path really is inference-only and nothing downstream needs differentiable tensors. The timings in results.json include a warm-up and a backward attempt, so they do not show either mode to be faster. Benchmark your own pipeline rather than trusting the name.

Parameter trainability

All 148 GPT-2 parameter tensors still had requires_grad=True after loading, after eval(), and inside inference_mode(). Neither of the other switches changes this flag.

That flag means the parameters can take part in gradient computation when recording is on. It does not mean an optimiser is running or that the weights are changing. The autograd experiment made this visible: in evaluation mode with ordinary grad mode on, the output kept a computation graph, and calling backward() on a scalar from the logits filled in parameter gradients. Under no_grad() or inference_mode() the output had no graph, and backward() raised an error. None of the three modes is designed to change the stored weights, but this chapter did not check that they stayed identical: no before-and-after digest was taken.

For an inference-only module, model.requires_grad_(False) stops gradients being tracked through the parameters if someone accidentally runs a grad-enabled forward pass. It does not stop direct writes to the weights, it does not stop a graph through other trainable inputs, and it is wrong if the same module will later be trained or used for gradient-based analysis. This chapter did not measure its cost or benefit, so treat it as a design choice to test.

The readiness check

The three switches can be inspected together. inference_readiness(module) in examples/ch02/execution_modes.py reports the module’s training flag, how many parameters have requires_grad=True, and whether autograd is on in the current thread:

def inference_readiness(module) -> dict:
    parameters = list(module.parameters())
    trainable = sum(1 for p in parameters if p.requires_grad)
    return {
        "training_mode": bool(module.training),
        "trainable_tensors": trainable,
        "total_tensors": len(parameters),
        "autograd_enabled": bool(torch.is_grad_enabled()),
        "ready": (not module.training) and (not torch.is_grad_enabled()),
    }

Its ready field is deliberately narrow: evaluation mode, and no grad recording. On the recorded GPT-2 run it reported:

When checked ready Why
After loading false Ordinary grad mode was on
After model.eval() false Grad mode was still on
Inside torch.inference_mode() true Both conditions met, even though all 148 parameters still had requires_grad=True

That last row is correct under the predicate, and it shows the predicate’s limits clearly. It is a teaching preflight, not production readiness. It does not check every submodule, the device, the revision, tokeniser compatibility, parameter hashes or whether anything will be mutated. A future request record should take this reading at the moment of generation and store artefact identifiers alongside it.

Observed, declared and not applicable

The Chapter 2 toy generator writes gradients_enabled_during_generation = False and model_training_mode = False as fixed values, although it has no autograd and no dropout. It lists training_mode in simulated_stages to say so. The real-model code queries the actual state at run time. The fields look identical but mean different things. A comparison between records must distinguish values that were observed, values that were declared, and fields that are not applicable.

Identifying the artefact

A useful identity record needs more than a name. This chapter builds two complementary views:

View What it hashes What it can detect What it misses
File layer Size and SHA-256 of seven named files in the cached snapshot Any change to those file bytes, including saved masks Extra files not on the list; where the snapshot came from
Loaded-parameter layer Sorted parameter names, shapes and raw values (parameter_digest) Changed parameter values, even across different file containers Buffers; dtype metadata (not hashed explicitly); module code; tokeniser

Manifest layers

For this model, parameter_manifest lists 148 named parameter tensors totalling 124,439,808 elements and 497,759,232 bytes, all float32, and parameter_digest produces 95cb2531cd09fbf7…. Because it hashes values rather than file bytes, the same weights in a different container can give the same digest. That is the point of having it. In the observed cache layout, the blob name of model.safetensors also matched an independently computed SHA-256, a useful local consistency check.

A stricter future manifest would hash dtype, buffer state and runtime versions too, and tests would change each one deliberately to prove it is covered.

What a hash proves

A hash proves that bytes match a reference digest. It does not prove who made the bytes. If an attacker can replace a file and the digest stored next to it, the check still passes. Safetensors avoids the code execution risk of pickle files and has a simple, specified layout (a length prefix, a JSON header, then tensor data), but it is not a signature, a malware scan or a supply-chain attestation.

For closed API models you cannot inspect weights at all. You can record the requested and returned model identifiers, provider, API revision where offered, timestamps and observed behaviour. That record is genuinely weaker than a local file-and-tensor manifest.

The toy analogue

The toy path in examples/ch02/reproducible_generation.py shows the same idea at small scale. A Checkpoint holds a transition table, bias, vocabulary and seed. Saving it produced a 93,259-byte JSON file containing a digest of the checkpoint’s canonical data, f51790a1c6eb34f8…. Here is how the loader behaves under different kinds of tampering:

Change to the saved file Loader result Evidence
One table value changed by \(10^{-9}\), old digest kept Rejected: digest mismatch Run and recorded
Only whitespace reformatted Accepted: canonical data and digest unchanged From the code; not run (exercise 2)
Values changed and digest updated to match Accepted: check bypassed From the code; not run
sha256 field removed Accepted without verification From the code; not run (exercise 1)

The last two rows are the current limits. The loader catches accidental corruption while a valid digest remains, but it does not enforce verification or authenticate the source. Exercise 1 fixes the missing-digest case. A production version would also compare against a trusted digest kept separately from the file.

What the first request pays

What Is Inference? saw load times between 1.58 and 3.20 seconds and one slow first forward pass, but did not measure library import time. Here, five fresh Python processes each imported the libraries, loaded GPT-2 and ran four forward passes over a seven-token prompt. Each cost was timed separately:

Cost Median over 5 processes Range Paid
Library import (torch, transformers) 15.9 s 15.2 – 17.7 s once per process
Model load 1.48 s 1.38 – 1.61 s once per process
First forward pass 154 ms 126 – 157 ms first call only
Later forward passes 103 ms 88 – 129 ms every later call

Import was the largest cost here. On this Windows machine, importing the software stack took a median of 15.9 seconds, about ten times as long as loading the model. That is unusually slow for importing torch and transformers, and the experiment did not check whether the file cache was warm or whether antivirus scanning contributed, so treat it as this machine’s figure rather than a general lesson. It is a cost of starting a process, not of doing arithmetic, and it is one practical reason a long-lived service pays start-up once and serves many requests.

Loading is modest. Model loading took about 1.5 seconds. Resident memory rose from about 577 MB after import to 1,089 MB after loading, an increase of about 512 MB. That is about the size of the parameter bytes, though the increase is not necessarily all parameters.

The first forward pass pays extra. Within each process the first pass took a median of 154 ms, against a pooled median of 103 ms for later passes: a penalty of about 51 ms. The cause was not isolated.

This bears on the question left open in Chapter 1 without settling it. There, the first forward pass was about 270 ms slower than the second (403 against 132 ms); here the penalty was about 51 ms. Those are different sizes, from different prompts, processes and timers, so they have not been shown to be the same effect. What both runs do show is that a one-off first-call penalty exists on this machine, and that it can disappear inside the sum of many steps.

The rule for benchmarks. Always declare your warm-up policy. Include start-up when you are asking about cold-start latency; exclude it when you are asking about warmed, steady-state execution. Either is legitimate; mixing them without saying so is not. Keep both distributions, report how many processes and requests you ran, and state exactly what each timer covers. When the book reaches time to first token in Latency, Throughput and Time to First Token, it separates process cold start, warm-up, queueing, prefill and transport rather than bundling them into one “first request” number.

Inference Lab increment

The Lab now has two new pieces alongside the request record from What Is Inference?:

  • file_manifest, parameter_manifest and parameter_digest, which describe an artefact as file hashes plus a tensor inventory;
  • inference_readiness, which reports module mode, trainable tensors and autograd state.

These are separate helpers for now. The intended next step is a single request record that carries the file hashes, parameter digest, relevant buffer state, library and code revisions, and a readiness reading taken during generation. That integrated record has not yet been built or demonstrated, so treat it as the target design.

Limits of this chapter’s evidence

About the set-up

  • One machine, one session, one CPU thread. Absolute latencies are not portable. Disk state, installed packages, background processes and allocator state were not varied systematically.
  • The sizes and hashes describe one pinned snapshot. The manifest command resolves whichever cached snapshot exists when it runs; it does not enforce a revision. To reproduce, save the reported snapshot, file hashes, library versions and command line with each result. These are local book results, not proof that every later GPT-2 experiment loaded identical bytes.
  • GPU execution was not measured. CUDA was available, but the parameters stayed on the CPU. An earlier result mislabelled availability as the execution device; the code now reports the parameter device, and the original result keeps an explicit correction note.

About the measurements

  • A Windows high-water mark is not an activation profiler. Peak working set includes allocations outside autograd and hides allocations below an earlier peak.
  • Dropout was probed on one input. The 41.68 maximum logit difference and the agreeing top token are single observations, not rates.
  • Evaluation mode is not a determinism guarantee. Two evaluation-mode outputs matched here. Bitwise agreement is not guaranteed across runs, libraries, hardware or numerical algorithms; Correctness, Determinism and Reproducibility treats this properly.
  • Start-up was measured once per configuration. The experiment did not check whether the operating-system file cache was warm, or measure the effect of antivirus scanning or a different installation. The first-forward penalty has possible causes (allocator effects, runtime initialisation, scheduling) but none was isolated.

About identity and integrity

  • The manifest is incomplete. Seven files were listed; the tensor digest covers parameters, not buffers; the toy loader accepts a missing digest.
  • Non-mutation was not tested. No before-and-after parameter comparison was made.
  • No production validation. Nothing here establishes checkpoint authenticity, safe input handling, provider-side provenance or cold-start behaviour under concurrent load.

What you should now be able to do

  • List the components of a model artefact beyond its parameters, and say which can change behaviour without touching a weight.
  • Explain why file size and parameter count differ, using a real file as the example.
  • Distinguish module mode, autograd context and parameter trainability, and say which of them eval(), no_grad() and inference_mode() each change.
  • Compute a manifest and a parameter digest for a model, and say what each does and does not prove.
  • Split “model load time” into import, load and first-call warm-up, and say which of them a long-lived server pays only once.

We now know exactly which artefact is running and in what state. But the model never sees text: it sees integer ids produced by the tokeniser, one of the files in our manifest. Tokens, Embeddings and Probability follows a prompt from text to ids, from ids to vectors, and from the model’s output scores to the probability distribution that a token is chosen from. Tokenisation can change the input without changing a single weight.

Key terms

  • Artefact: the files, configuration and code needed to instantiate and execute a particular model, not merely its learned weights.
  • Parameter: a tensor registered as a trainable model parameter; whether it currently receives gradients depends on flags and execution mode.
  • Buffer: registered non-parameter module state, such as a stored causal mask, that can still affect execution.
  • Frozen weights: an operational requirement that parameter values not change during a specified execution path; not synonymous with eval() or no_grad().
  • Computation graph: recorded operations and intermediate relationships used for automatic differentiation.
  • Evaluation mode: a module setting selected with eval() that changes training-sensitive layer behaviour, not a gradient-control mechanism.
  • Inference tensor: a tensor created under torch.inference_mode() with restrictions on some later autograd and mutation operations.
  • Manifest: an explicit, versioned description of selected artefact files or loaded tensor state; completeness must be declared.
  • Cold start: execution that includes one-off process or runtime initialisation costs, with a stated measurement boundary.

Reader exercises

  1. Corrupt one value in the saved toy checkpoint and confirm that loading rejects the unchanged embedded digest. Now remove the sha256 key entirely. Does the current loader accept it? Propose a test and an implementation change that refuse missing digests.
  2. Reformat only the whitespace of the saved toy JSON. Does loading still succeed? Explain why the embedded hash is over canonical checkpoint data rather than the saved file’s exact bytes.
  3. Run execution_modes.py dropout on a module without dropout. Why is agreement there not evidence that training and evaluation modes are interchangeable in general?
  4. Add model.requires_grad_(False) to a copy of the loading path, then test a grad-enabled forward and a deliberate in-place weight update separately. Which kind of work does the flag prevent, and which does it not?
  5. Repeat execution_modes.py modes at 128, 256 and 512 tokens, with multiple fresh processes per mode and length. Graph the increment in process peak, not “bytes saved by autograd”; test linear and quadratic fits without assuming either in advance.
  6. Change one registered model buffer while leaving parameters unchanged. Compare the parameter digest with a digest that explicitly includes named_buffers(). What does each claim actually identify?
  7. Rerun execution_modes.py startup --repeat 5 and document import, load and forward timings separately. Then write a time-to-first-token definition for a long-lived service, naming which costs that metric excludes.

References

Evidence in this chapter

Claim Category / evidential limit
eval() changes training-sensitive layers; grad contexts control graph recording Established background; PyTorch documentation
inference_mode() creates restricted inference tensors Established background; PyTorch documentation
Serialized GPT-2 snapshot has 160 named tensors; 12 additional saved masks occupy 50,331,648 bytes Local file-header inspection, pinned snapshot
Loaded module has 148 named parameter tensors, 124,439,808 elements Local parameter inventory
Parameter digest 95cb2531cd09fbf7… identifies parameters only, not buffers or dtype metadata explicitly Local implementation property; limited identity claim
Train-mode pair differed by up to 41.68 in logits; eval-mode pair agreed Book result, one input and environment
Recorded 512-token process peak rose about 528 MB with autograd, versus 32 MB without Book result, one process per mode; not direct activation memory
First forward median about 154 ms versus later pooled median about 103 ms Book result, five processes; causal mechanism unisolated
Autograd-related total process-peak overhead scales quadratically with length Hypothesis; not established by the 512-token test
Toy checkpoint rejects altered data when the old sha256 remains, but accepts absent hash Code-supported limitation; no authenticated provenance
Model bytes remain unchanged throughout generation Not tested by before/after parameter comparison
GPU behaviour, distributed loading, cross-hardware determinism, production service cold starts Not measured