
21 November 2026 · ML System reading notes · 6/6
ML System 06: Model Inference and Security
Part six covers sections 9.4 and 9.5 of the book's chapter 9: model inference and model security. The inference half follows the book through pre- and post-processing, parallel computing, hardware instruction optimization and algorithm optimization. The book doesn't say much about LLM inference, so I added three sections of my own on batching, the KV cache and CUDA Graphs, and worked through one question: for a 2T-parameter model with a million-token context, how big is the KV cache? The security half is mostly about how model obfuscation works.
Pre-processing and post-processing
Once a model has been converted and compressed, it can be deployed to run inference. There is a stage of data processing on each side of inference.
Pre-processing turns raw data into input the model can use. It mainly means feature encoding, normalization and handling outliers.
Post-processing happens after inference: the model's output is tidied up and handed to the user. Common steps include:
- discretizing continuous outputs;
- visualizing the data;
- manually widening the prediction range: a regression model's predictions tend to bunch in the middle and miss very large or very small values, so values outside the normal range are multiplied by a coefficient to stretch both ends;
- top-k, and the token decoding strategies a language model uses when it generates text.
Parallel computing
Split the input data into slices and have several threads work on different slices, and you have parallel execution of an operator. To make this easy, and to avoid the cost of creating and destroying threads all the time, inference frameworks usually use a thread pool. There are two ways to get one: use the OpenMP API directly, or have the framework implement its own thread pool built for operator parallelism.
Hardware instruction optimization
The most direct approach is to hand-write assembly for hot operators. On CPUs this usually means SIMD instructions; on ARM, the SIMD instruction set is called NEON.
SIMD: one instruction, a row of numbers
A NEON register is 128 bits wide and holds several numbers side by side: four 32-bit values, eight 16-bit values or sixteen 8-bit values. SIMD means one instruction does the same thing to every number in the register. For example:
fmla v0.4s, v1.4s, v2.4s
fmlameans multiply, then add;.4smeans each register holds four FP32 values;- the whole instruction multiplies the numbers at matching positions in v1 and v2 and adds the results into the matching positions of v0.
One instruction does four multiply-adds. Matrix multiplication and convolution in a model are almost entirely multiply-then-add, so these instructions fit them well.
This also explains why quantization speeds things up on a CPU: the same register holds only four FP32 values but sixteen INT8 values. Part 5 noted that you only get a real speedup when both weights and activations are quantized and the math runs in INT8 operators, and this is why that's faster on a CPU. It applies when the device has no GPU, such as a phone or an embedded device.
The slow part is moving data
There are only a few compute instructions and they are fixed. What's slow is reading and writing memory. So the focus of optimization is raising the cache hit rate, and the usual techniques are:
- Loop unrolling: use more registers, trading code size for speed;
- Instruction reordering: keep different execution units busy at the same time, and issue slow instructions early;
- Register blocking: keep a small block of results in registers and reuse the data already loaded, again and again;
- Data reordering: make reads and writes contiguous in memory;
- Prefetching: move data from memory into cache before it's needed.
Algorithm optimization
The book's algorithm optimizations are all about convolution:
- Img2col (also written im2col): take each patch of input the kernel slides over and stretch it into a column. All the columns together form one big matrix, the kernels are unrolled into a matrix too, and the convolution becomes a single matrix multiplication, a GEMM.
- Winograd: trade multiplications for additions. Multiplication costs more than addition, so Winograd uses a transform to do fewer multiplications at the price of some extra additions.
LLM inference
Most of the optimizations above are done on CPUs and devices like phones. Running a large model on GPUs brings problems of its own, and the next three sections are the ones I took notes on.
Batching and continuous batching
The batch size is set by how many people are sending requests at the same time. When generating a token, the GPU spends most of its time reading the model's hundreds of gigabytes of weights out of GPU memory, and very little time computing. Put four people's requests together and the weights are still read only once, but you get four tokens out, one for each person.
The trouble is that answers have different lengths and requests arrive at different times. Continuous batching handles this like a bus: whoever finishes gets off, and the next request gets on right away, without waiting for everyone on board to finish before letting anyone off. So the number of riders can change at every stop, and a scheduler decides how many get on and off at each one.
In theory the batch has to grow to several hundred before the GPU's compute is fully fed and the workload goes from memory-bound to compute-bound. In practice you usually hit the KV cache wall first. Each person's KV cache is their own, so the bigger the batch, the faster GPU memory fills up, and the batch size is usually capped by the KV cache.
How big is the KV cache
I worked through one question: for a 2T-parameter model with a context of one million tokens, roughly how big is the KV cache?
The answer barely depends on the total parameter count. It depends on how the attention layers are designed. Most of an MoE model's parameters are in the experts (the FFNs), and experts don't produce any KV cache; only attention layers do. So two models with the same 2T parameters can have KV caches a thousand times apart.
For standard attention, the KV cache per token = 2 (K and V) × number of layers × number of KV heads × head dim × bytes per number.
Estimates for one million tokens and a single request:
| Architecture | Per token | 1M tokens |
|---|---|---|
| Naive multi-head attention (a hypothetical 2T dense model: 160 layers, 128 heads, head dim 128, BF16) | about 10 MB | about 10 TB |
| GQA (Llama 3.1 405B: 126 layers, 8 KV heads) | about 500 KB | about 0.5 TB |
| MLA (DeepSeek-V3: 61 layers, each storing just one 576-dim compressed vector) | about 70 KB | about 70 GB |
| V4-Pro hybrid compressed attention (CSA + HCA, 1.6T) | — | a few GB (my estimate, from the report's "only 10% of V3.2") |
A single H100 has only 80 GB of memory, so the naive design simply can't run with a long context. This is why DeepSeek has kept shrinking the KV cache with each generation: once the context gets long, the KV cache is the biggest thing in GPU memory, and it directly caps the batch size. The harder you compress it, the more people one machine can serve at once, and the cheaper long context becomes.
CUDA Graphs
Part 2, on why dynamic graphs are slow, introduced being launch-bound: every operator pays a fixed CPU cost, and when operators are tiny the GPU finishes faster than the CPU can issue work, so it spends most of its time waiting. A CUDA Graph records a whole sequence of launches and submits it in one go from then on. The CPU cost goes away, and the GPU no longer waits for the CPU to issue kernels one at a time. The reduce-overhead mode of torch.compile in Part 2 is the default mode with this added.
It works in three steps:
- Capture: run the code once without doing any real computation in the kernels, only recording what each launch contains: which kernel, how many threads, and which GPU memory addresses hold the inputs and outputs.
- Instantiate: the driver checks the recording, optimizes it a little, and turns it into a graph that can be executed directly.
- Replay: from then on, a single launch makes the GPU run the whole sequence of kernels back to back.
The cost is a little more GPU memory, and everything has to be fixed: neither the input shapes nor the batch size can change. So it's used mainly in the decode phase, when tokens are generated one at a time. The prefill phase processes the whole input at once; its operators are usually large and its lengths vary a lot, so it isn't launch-bound anyway and doesn't need it. For the batch, inference engines record graphs for a few sizes in advance, say one each for 1, 2, 4, 8, 16 and so on. If 7 requests come in, they're padded to 8.
Model security
Once a model is deployed, how do you keep it from being stolen? Protection comes in two kinds: static protection covers transmission and storage, and dynamic protection covers runtime.
Static protection
Static protection uses file encryption: the model is transmitted and stored as ciphertext and decrypted in memory before inference. The weakness is that the model sits in memory as plaintext during inference, where it can be dumped and stolen.
Dynamic protection
Dynamic protection has three approaches:
| Approach | How it works | Benefits | Costs |
|---|---|---|---|
| TEE (trusted execution environment) | trusted hardware walls off a secure area, and the model is decrypted and run inside it | low latency for CPU inference | depends on specific hardware, struggles to protect large models, no support for heterogeneous hardware acceleration |
| Encrypted computation | cryptographic methods such as homomorphic encryption and secure multi-party computation keep the model encrypted the whole time | doesn't depend on specific hardware | high compute and communication overhead, and can't protect the model's structure |
| Model obfuscation | scrambles the model's computation logic so an attacker who gets the model can't make sense of it | doesn't depend on hardware, can protect large models | small performance overhead, low accuracy loss |
How model obfuscation works
Model obfuscation has two phases. The offline phase obfuscates the model and its operators ahead of time:
- Parse the model to get the computational graph. The graph contains node identifiers, operator types, weights and the network structure.
- Scramble the network structure. Graph compression merges key subgraphs into single new nodes. Graph augmentation then adds new input/output edges, which can connect to existing nodes or to newly added obfuscation nodes, to hide the real dependencies.
- Anonymize the nodes. Node identifiers, operator types and similar information are replaced with meaningless symbols, while each identifier stays unique. Nodes with the same operator type are split into several sets, and each set shares one anonymous symbol, to keep the number of operator types from exploding.
- Scramble the weights. Each weight is processed with random noise and a mapping function, and different weights can use different noise and functions. The resulting graph is saved as the model file.
- Transform the operator interfaces. For each kind of operator that needs protecting, generate several candidate obfuscated operators, as many as there are sets from step 3, then transform their interfaces, for example by changing their inputs and outputs and renaming them to the anonymous symbols from step 3.
- Transform the operator implementations. Code obfuscation techniques such as string encryption and redundant code make the obfuscated operators' code hard to read. Each obfuscated operator also has the inverse of the weight scrambling built in, which removes the noise on the fly at runtime, so the results match the original model. The obfuscated operators are saved as a library file.
The deployment and runtime phase then puts them to use:
- Deploy the obfuscated model file and the obfuscated operator library to the target device.
- Load the obfuscated model and parse out the obfuscated computational graph.
- Initialize the graph to produce a sequence of execution tasks. There are two options here:
- to protect the model at runtime, initialize directly from the obfuscated graph, so the sequence contains obfuscated or original operators;
- if only transmission and storage need protecting, first restore the obfuscated graph to the original in memory and then initialize, which makes inference cheaper.
- Run inference: walk through the task sequence, calling the obfuscated operator library for obfuscated operators and the original library for everything else.