Skip to content

Memory accounting, and sharding it across devices

Add up what training and serving need (weights, gradients, optimizer state, activations, KV cache), see how ZeRO and FSDP split the big parts across devices, and read CodeSplash's Resources estimate.

Advanced ~16 min8 steps

What runs in CodeSplash

You will be able to

  • Count the bytes per parameter for training with Adam in mixed precision
  • Compute a KV cache size from layers, width, context and batch
  • Explain what ZeRO stages 1-3 and FSDP shard and what stays replicated
  • Read a network's Resources estimate in CodeSplash

Read first

01

The training bill

Read

A training memory budgetTraining memory budgetMemory to train a network: weights, gradients, optimizer state, stored activations, plus temporary buffers. has four big lines:

LineGrows withTypical size per parameter
WeightsParameters2 bytes (16-bit) or 4 (32-bit)
GradientsParametersSame as the weights
Optimizer stateOptimizer stateValues an optimizer keeps per weight between steps. Adam and AdamW keep two (the moments), SGD with momentum one.ParametersAdam: 8 bytes (two 32-bit moments)
ActivationsBatch × length × width × depthNot per parameter

With mixed precisionMixed precisionTraining with low-precision math for speed and memory while keeping sensitive sums and master weights in higher precision., a common recipe keeps 16-bit weights and gradients plus a 32-bit master copy and Adam's two moments: 2 + 2 + 4 + 4 + 4 = 16 bytes per parameter before any activations. A 7-billion-parameter model needs about 112 GB for those lines alone.

DExplorable · How much memory does a model need?

Where does a language model's memory go — weights, KV cache, optimizer state — and does it fit on this Mac?

Model

Hypothetical decoders; the first is the reference workflow's own.

2048

Tokens held in the KV cache (and the length of the attention scores).

1

Sequences processed at once; the KV cache grows with it.

Weight format

Bits per stored weight; the llama.cpp types include their block scales.

KV cache format

Bytes per stored key or value.

Use

Training adds gradients and optimizer state; LoRA adds them only for the adapters.

8

LoRA only: rank of each adapter.

LoRA targets

LoRA only: which matrices get adapters.

16

Under half is “fits”, under 85% “tight”, as the app's own estimate says.

this Mac (16 GB)
  • Weights: 0.31 GiB
  • KV cache: 0.02 GiB
  • Runtime overhead (10%): 0.03 GiB
  • Verdict: fits (2%)
  • This model's KV heads (grouped-query)
  • One KV head per query head
Parameters
168059904
Weight bytes
336119808
KV cache bytes
25165824
Trainable parameters
0
Total bytes
397414195
Share of this Mac's memory
0.023
  • Puzzle: Make the larger decoder fit (under half) a 16 GB Mac for inference with a 4,096-token context.
  • Puzzle: With LoRA training less than 1% of the parameters, find a case where the total is still more than half of full fine-tuning's.
Reference decoder (168M parameters): 168,059,904 parameters, 0.31 GiB of weights in fp16 and a 0.02 GiB KV cache for 2,048 tokens. Total 0.37 GiB: 2% of 16 GB, so it fits. These are logical tensor sizes, not measured memory.

Reference decoder (168M parameters): 168,059,904 parameters, 0.31 GiB of weights in fp16 and a 0.02 GiB KV cache for 2,048 tokens. Total 0.37 GiB: 2% of 16 GB, so it fits. These are logical tensor sizes, not measured memory.

02

The serving bill

Read

Serving needs no gradients or optimizer state, but a language model keeps a KV cacheKV cacheKeys and values a language model keeps for every token in its context, per layer. It grows with the context window.: every layer stores a key and a value vector for every token in the context, so later tokens needn't recompute them.

KV bytes=2×layers×dmodel×context×batch×bytes per number.\text{KV bytes} = 2 \times \text{layers} \times d_{\text{model}} \times \text{context} \times \text{batch} \times \text{bytes per number}.

For long contexts the cache can rival the weights. Grouped-query attention shrinks it by sharing keys and values across heads; quantizing the cache shrinks it further.

03

Sharding the big parts

Read

Data-parallel trainingData-parallel trainingEvery device holds a full model copy, trains on its own slice of the batch, and the gradients are averaged each step. gives every device a full copy of everything. ZeROZeRO and fully sharded data parallel (FSDP)Data-parallel training that splits optimizer state, gradients and weights across devices instead of copying them. removes that redundancy in stages:

  • Stage 1 splits the optimizer state across the NN devices;
  • Stage 2 also splits the gradients;
  • Stage 3, like FSDP, also splits the weights, gathering each layer's weights right before it's needed.

Sharded parts cost 1/N1/N per device; replicated parts and temporary buffers don't shrink. The reference's example: 48 GiB of shardable state over 8 devices, plus 2 replicated and 4 temporary, gives 12 GiB per device. The price is communication: gathering weights and reducing gradients every step.

04

Resources estimate in CodeSplash

In the app

Before you train a network in Predict, its Resources estimate shows the memory for one fit, line by line: Weights, Gradients, Optimizer state, Saved weight copies (for weight averaging or the best epoch), Activations for a batch, Data and the Engine itself, in the dtype the compute profile uses. The run then reports its peak memory, so you can compare the estimate with what happened.

For local language models, Settings → AI estimates memory from the model's size, its quantization and the context length, KV cache included.

ZeRO and FSDP are explained here: CodeSplash trains on one device.

05

Predict: what shrinks with LoRA?

Predict

Predict first

You switch from full fine-tuning to LoRA training 1% of the weights. Which lines of the training bill shrink?

All four lines shrink by about 99%Gradients and optimizer state shrink; weights and activations stay
Reveal

Gradients and optimizer state. The frozen weights are still loaded, and activations still flow through every layer for the backward pass.

06

What runs here

Read
07

Check: memory

Checkpoint

Check yourself

Mixed-precision training with Adam keeps 16-bit weights and gradients, a 32-bit master copy of the weights and Adam's two 32-bit moments. How many bytes per parameter is that?

Show the answer

Answer: 16

2 + 2 + 4 + 4 + 4 = 16 bytes per parameter, before activations.

Check yourself

A model has 32 layers and width 4,096. In 16-bit numbers (2 bytes), how many bytes does the KV cache need for one sequence of 2,048 tokens? (2 × layers × width × tokens × bytes.)

Show the answer

Answer: 1073741824

2 × 32 × 4,096 × 2,048 × 2 = 1,073,741,824 bytes, 1 GiB per sequence. A batch of 8 needs 8 GiB.

Check yourself

What does ZeRO stage 3 (or FSDP) shard that stage 1 doesn't?

Show the answer

Answer: a

Stage 1 splits optimizer state, stage 2 adds gradients, stage 3 adds the weights, gathered layer by layer when needed.

Check yourself

64 GiB of shardable state is split over 16 devices; 6 GiB is replicated and 3 GiB is temporary on each. How many GiB per device?

Show the answer

Answer: 13

64 / 16 + 6 + 3 = 4 + 6 + 3 = 13 GiB. The replicated and temporary parts don't shrink with more devices.

Check yourself

What does sharding cost compared with plain data-parallel training?

Show the answer

Answer: a

The arithmetic is the same; the memory saving is paid for in network traffic between devices.

08

Recap

Recap
  • Training memory: weights, gradients and optimizer state scale with parameters (about 16 bytes each with mixed-precision Adam); activations scale with batch and length.
  • Serving a language model adds a KV cache that grows with layers, width, context and batch.
  • ZeRO stages and FSDP shard optimizer state, gradients and weights across devices, paid for with communication.
  • CodeSplash's Resources estimate shows each line before a network trains.

Concepts in this lesson