AI Run Lab

All chapters

Optimizing inference

A smaller file, a quicker first token and more tokens per second describe different improvements. Choose the quantity you want to improve before changing the model.

Open this chapter with experiments and audio

Round one group of weights

Quantization represents values using a limited set of levels. In a simple symmetric example, let the step size be 0.1. A weight of 0.36 becomes integer 4 and reconstructs as 0.40. A weight of −0.22 becomes −2 and reconstructs as −0.20. The scale is part of the representation. A smaller step reduces rounding error near zero but covers a narrower range with the same integer limits.

For a group of weights, choose the scale, divide each weight by it, round to an integer and clamp the integer to the allowed range. Reconstruct for inspection by multiplying by the scale again. At four bits there are sixteen possible bit patterns. Different schemes assign those patterns to levels differently. Professional implementations often use separate scales for different groups.

weights = [-0.22, 0.36, 0.71, 1.25]
scale = 0.1
for w in weights:
    q = max(-8, min(7, round(w / scale)))
    restored = q * scale
    print(f"{w:5.2f}   {q:2d}   {restored:5.2f}   error {abs(w-restored):.2f}")

Interpret the largest error

For 1.25, the nearest integer would be 12 or 13, but this signed four-bit example stops at 7. Reconstruction therefore gives 0.70 and the error is 0.55. This is clipping. Shrinking the step again makes this outlier worse. Choosing a larger scale covers the outlier but can make the smaller values less precise.

The code uses ordinary Python integers to make the algorithm visible. It demonstrates the numerical mapping only. A runtime achieves the memory saving by packing low-bit codes and using kernels that can read or transform that representation. At seven billion weights the raw payload falls from 14 GB at 16 bits to 3.5 GB at four bits. Metadata, scales and higher-precision layers change the real file size.

Compare different kinds of optimization

Pruning removes selected weights or structures. A sparse array only gains speed if the runtime can avoid the removed work. Distillation trains a student model against targets supplied by a teacher. FlashAttention computes the attention operation in blocks to reduce data movement. A storage format determines how arrays and metadata are serialized. A file extension on its own tells you little about model quality.

ChangeMeasure
Fewer bits per weightBytes, quality on fixed prompts, generation rate
Batched requestsAggregate output rate and each user’s waiting time
FlashAttentionTime and peak memory at the same sequence length
GGUF or SafetensorsContents, loader support and stored precision

How long does reading the weights take?

Assume one dense model serves one sequence and reads its entire packed weight array from device memory once per generated token. Under that assumption, how does changing the number format affect transfer time?

This calculation isolates weight traffic. Compare it with measured token intervals. Cache reads, temporary writes, arithmetic, actual bandwidth, batching and format overhead can change the result.

Run a fair comparison

Keep the checkpoint family, prompts, context length, output budget, hardware and concurrency fixed. Record whether the first run includes loading. Measure time to first token and the rate of later output separately. Then inspect answers on tasks that matter: arithmetic, extraction, source attribution or another clearly defined task. A shorter but incomplete answer can make a model appear fast.

Try changing only batch size. Several users may collectively receive more tokens per second because their work fills the device more efficiently. An individual user can still wait longer for admission or the first token. The best setting depends on which measure matters to the application.

Does a four-fold reduction in raw storage guarantee a four-fold speedup?

No. Data movement, kernel support, the input size and runtime overhead also affect speed.

Dao et al. · FlashAttention

Two users can experience the same throughput differently

Suppose an already loaded service takes 0.8 seconds to return the first generated token and then 0.04 seconds per additional token. A 101-token response takes approximately 0.8 + 100 × 0.04 = 4.8 seconds. Improving prefill and the other work before first output to 0.4 seconds saves 0.4 seconds. Halving the interval between later tokens saves 2 seconds on this request. For a one-token answer only the first improvement matters.

Prefill processes many prompt positions together. During decoding, one request needs its previous selected token before it can compute the next one. Batching several users can reuse a weight read across requests, increasing aggregate tokens per second. Waiting to form a batch can also delay an individual user. Benchmark prompt length, output length and concurrency separately. Alongside median latency, report a high percentile to expose long waits.

Change prompt and output length independently →

Sources · vLLM