KV Cache, Quantization, and Memory
Inference has distinct phases
Prefill processes the input prompt and establishes representations used for generation. Decode repeatedly produces subsequent tokens. Time to first token and tokens per second measure different parts of this experience.
During autoregressive decoding, a KV cache stores previous attention keys and values so they need not be recomputed from scratch for each next token. It is temporary computational state, not a searchable store of user memories. Cache memory grows with sequence length, layers, batch size, and the attention configuration.
Estimate weight storage first
For 7 billion parameters at two bytes each, raw weight storage is about 14 billion bytes, or about 13.0 GiB. At four bits per weight the idealized packed storage is about 3.5 billion bytes. Actual storage includes quantization metadata, alignment, and other components. Runtime also needs caches, activations, workspaces, and serving overhead.
parameters = 7_000_000_000
for bits in [32, 16, 8, 4]:
bytes_needed = parameters * bits / 8
print(bits, round(bytes_needed / (1024 ** 3), 2), "GiB raw")Run in the Python compiler. This calculation estimates storage; it does not prove the model will fit or run fast on a particular device.
Quantization, batching, and acceleration
Quantization stores or computes selected values at reduced precision. It can reduce memory and improve speed on supported hardware, but may change quality or introduce conversion overhead. Quantized weights do not mean every operation or cache uses the same precision.
Batching improves throughput by sharing efficient hardware execution across requests, but waiting to form batches can increase latency. Continuous batching can admit and finish requests at different times. Speculative decoding uses proposed tokens and verification to accelerate generation in suitable settings; its benefit depends on acceptance and implementation.
Checkpoint with answers
Is a 4-bit model guaranteed to be four times faster than a 16-bit model? No. Hardware kernels, memory bandwidth, batch size, and overhead determine the result.
Why can a long conversation exhaust memory despite unchanged weights? Its KV cache and related runtime buffers grow.
Exercise: A model fits on a device for one short request but fails under eight long requests. What should you inspect? Answer: concurrent sequence lengths, KV-cache allocation, batching, maximum context settings, and total available memory.