AI Run Lab

All chapters

Where a model fits in memory

A model is a collection of arrays. Work out the space for its numbers first. Then separate permanent storage, temporary work and the state kept for each active conversation.

Open this chapter with experiments and audio

Count bytes from the shapes

A matrix with 3 rows and 4 columns contains 12 values. At 16 bits per value, it occupies 24 bytes before metadata. To estimate a whole model, add all its distinct parameter counts, multiply by bits per parameter and divide by eight. A billion-parameter model at 16 bits holds about two billion bytes of raw weights.

The word “billion” refers to the number of scalar parameters. Two matrices can contain the same number of parameters with different shapes and different jobs. A file also records array names, dimensions and sometimes tables used to interpret compressed values. A model-card estimate and an operating system’s reported size may use different units. Decimal GB uses one billion bytes. Binary GiB uses 1,073,741,824 bytes.

What else occupies the device?

While answering, the runtime stores intermediate results and often the keys and values already computed for each earlier token. This KV cache grows with the retained sequence length and the number of concurrent sequences. Reusing it saves work in the next generation step. During training there are also gradients, saved activations for backpropagation and state for the optimizer.

For an idealized decoder with the same number of key/value heads in every layer, KV bytes per sequence are 2 × layers × tokens × KV heads × head dimension × bytes per value. The leading 2 counts keys and values. With 12 layers, 1,024 tokens, 4 KV heads, 64 components and 2 bytes per component, the total is 12 MiB. Doubling the context length doubles this cache in the simple model.

layers, tokens, kv_heads, head_width = 12, 1024, 4, 64
for sequences in (1, 4, 8):
    size = 2 * layers * tokens * kv_heads * head_width * 2 * sequences
    print(sequences, "sequence(s):", size / 2**20, "MiB")

Which computation suits a GPU?

A matrix product involves many similar multiply-and-add operations on different values. A GPU or another tensor accelerator can do many of these at the same time. Speed still depends on moving the inputs and weights to the computing units. A small request may leave units idle while waiting for memory.

The CPU prepares inputs, handles application logic and can also run models itself. On some devices CPU and GPU share memory, while others need transfers between host memory and dedicated device memory. CUDA, ROCm and Metal expose different hardware environments. A compatible build of the runtime determines which acceleration path is actually available.

What changes across several devices?

With data parallel training, each device processes different examples and the workers combine gradients. With tensor parallelism, several devices share the work for a layer. With pipeline parallelism, different devices hold different groups of layers. These choices have different communication requirements. Faster arithmetic on each device can still leave a slow link between devices as the limiting factor.

If a model fails to fit, record when it fails. A failure while loading points toward initial parameter storage or loading overhead. A failure after prompts grow or concurrency rises points toward runtime buffers or cache. A failure only during backpropagation suggests training-specific storage. Each observation leads to a different measurement.

Will a 14 GB file always fit on a device with 14 GB of free memory?

The file size alone cannot establish that. The running program also allocates cache, working space and runtime structures.

Hugging Face · KV cache strategies

PyTorch · Distributed overview

Why the ninth conversation can fail when the weights already fit

Take a simplified decoder with 32 layers, 8 key/value heads per layer, 128 coordinates per head and a two-byte storage type. Each token adds one key and one value in every layer. The cache therefore grows by 2 × 32 × 8 × 128 × 2 = 131,072 bytes per token, or 128 KiB. A request with 4,096 cached positions occupies 512 MiB. Eight independent requests of that length occupy 4 GiB in cache alone. This example assumes no prefix sharing, sliding window or compressed cache.

The weights are reused across the requests. Their caches belong to their respective token histories. If a ninth conversation arrives, the server may queue it, reduce concurrency or evict a cache that will later cost work to rebuild. PagedAttention allocates cache blocks as needed and can share blocks in eligible cases. It improves how memory is managed. The keys and values the model actually reads still occupy storage.

Change the sequence length and count the cache bytes →

Sources · Kwon et al., 2023