Module 1 · When and why to fine-tune

Estimating GPU budget, memory and costs

7 min read

"Will it fit on the card?" is the first question of any fine-tuning project, and the answer takes five minutes to compute. This lesson breaks down the memory of a training run, estimates it for several models and methods, compares it with Forge's real measurements — including a Windows-specific surprise — then estimates duration and cost.

Where the memory goes

During training, the GPU stores five things:

ItemSizeNote
Weightsparameters × bytes per parameter4 bytes in fp32, 2 in bf16, 0.5 in NF4 (QLoRA)
Gradientstrained parameters × 4Only what you train
Optimizer (AdamW)trained parameters × 8Two fp32 moments: the heaviest item in full fine-tuning
Activations~ 34 × batch × sequence × hidden size × layers (bytes, in 16 bits)Divided by ~17 with gradient checkpointing
Logitsbatch × sequence × vocabulary × 4, plus their gradientHuge with a large vocabulary, unless computed in chunks

forge/budget.py encodes these rules:

act_bytes = BYTES[compute_dtype] / 2  # la formule est donnée pour 16 bits
per_layer = (2 if checkpointing else 34) * batch * seq * shape.hidden * act_bytes
return MemoryEstimate(
    weights=shape.params * BYTES[weights_dtype],
    gradients=trainable * 4,
    optimizer=trainable * 8,
    activations=per_layer * shape.layers,
    logits=2 * batch * seq * shape.vocab * 4 if full_logits else 0.0,
)

What it gives

Estimates for a batch of 8 sequences of 256 tokens, weights in bf16, gradient checkpointing enabled, LoRA on all linear layers (about 1.75% of the parameters):

ModelFull fine-tuningLoRAQLoRA
SmolLM2-135M2.6 GB1.1 GB0.9 GB
Qwen2.5-0.5B8.8 GB3.4 GB2.7 GB
Llama-3.1-8B107 GB19 GB7.8 GB
Llama-3.1-70B925 GB150 GB51 GB

Three lessons. In full fine-tuning, the optimizer weighs twice the weights: 60 GB for an 8 B. LoRA almost entirely removes gradients and optimizer: what remains is the frozen weights. QLoRA divides those weights by four again: an 8 B trains on a 12 to 16 GB consumer card, a 70 B on a single 80 GB GPU.

For small models, the logits dominate: with a 151,936-token vocabulary, Qwen2.5-0.5B would produce 2.3 GB of logits and gradients for this batch alone. TRL 1.x computes them in chunks, on the answer tokens only: this item almost disappears (the estimator's full_logits=False option).

Estimate versus measurement

Forge measures the real peak (torch.cuda.max_memory_allocated) on every training run. On the course's GTX 1060 (6 GB, no bf16: everything in fp32), batch of 8, about 200 tokens:

RunEstimatedMeasured
Qwen2.5-0.5B, LoRA2.07 GB2.87 GB
Qwen2.5-0.5B, QLoRA0.46 GB1.66 GB
Qwen2.5-0.5B, full7.49 GB8.41 GB
SmolLM2-135M, LoRA0.66 GB1.00 GB
SmolLM2-135M, full2.11 GB2.32 GB

The estimate gives the right order of magnitude, but always underestimates: temporary buffers, allocator fragmentation, compute kernels. Plan a 20 to 40% margin. The QLoRA gap is instructive: bitsandbytes only quantizes linear layers; Qwen2.5-0.5B's embedding matrix (136 million parameters, more than a quarter of the model) stays in full precision. On a small model with a large vocabulary, QLoRA therefore saves much less than expected.

The surprise: 8.41 GB on a 6 GB card

The full fine-tuning of Qwen2.5-0.5B did not fail, even though it needed 8.41 GB on a card that has 6. Under Windows, the NVIDIA driver silently spills into system RAM when GPU memory is full (the "CUDA – Sysmem Fallback Policy" option). Training continues, but system memory accesses are much slower: the run took 7.2 minutes for one epoch, versus about 5 minutes per epoch with LoRA. Under Linux, the same training stops dead with a CUDA out of memory error.

This behavior is a trap both ways: a training run that "works" on a Windows workstation can fail on the production Linux server, and an abnormally slow training run under Windows may simply be spilling over. Always compare the measured peak with the card's memory.

Reducing memory, in order

  1. Gradient checkpointing (enabled by default in TRL): activations are no longer stored but recomputed, for about 20% more time.
  2. LoRA, then QLoRA: gradients and optimizer reduced to almost nothing, then weights divided by four.
  3. Smaller batch + gradient accumulation: a batch of 2 accumulated 4 times is equivalent, for the optimizer, to a batch of 8, with the activation memory of a batch of 2.
  4. Shorter sequences: truncate or split overly long examples.
  5. Several GPUs with sharding (lesson 3.4).

Inference has a budget too

In production, memory = weights + KV cache (the attention keys and values, kept for every token already read):

def inference_memory(shape: ModelShape, dtype: str, batch: int, context: int, kv_heads: int,
                     head_dim: int) -> float:
    """Poids + cache KV (2 tenseurs par couche : clés et valeurs), en octets."""
    kv = 2 * shape.layers * batch * context * kv_heads * head_dim * BYTES["bf16"]
    return shape.params * BYTES[dtype] + kv

For Llama-3.1-8B in bf16 serving 16 requests of 8,192 tokens in parallel: 15 GB of weights and 16 GB of cache, 31 GB in total. The cache exceeds the weights: it is what limits the number of simultaneous requests (lesson 5.4).

Duration and cost

Duration is computed from a measured throughput over a few dozen steps — never from a spec sheet:

def training_cost(tokens: float, epochs: float, tokens_per_second: float,
                  price_per_hour: float) -> tuple[float, float]:
    """Durée (heures) et coût d'un entraînement, à partir d'un débit MESURÉ sur quelques pas."""
    hours = tokens * epochs / tokens_per_second / 3600
    return hours, hours * price_per_hour

Forge's LoRA run processed about 415,000 tokens in 610 seconds: about 680 tokens per second on the GTX 1060. As a calculation example, 50 million tokens over 3 epochs at 2,500 tokens/s (a recent rented GPU, an order of magnitude for a model of a few billion parameters with LoRA) take 17 hours; at $2.50 per hour, $42. The calculation is trivial; measuring the throughput is not, and it comes first. Add iterations to the budget: a serious project rarely needs fewer than ten training runs before the right one.

Key takeaways

  • Training memory = weights + gradients + optimizer + activations + logits; in full fine-tuning, the optimizer weighs twice the weights.
  • LoRA almost removes gradients and optimizer; QLoRA divides frozen weights by four — except embeddings, which are not quantized.
  • The estimate gives the order of magnitude; measurement exceeds it by 20 to 40%: plan a margin.
  • Under Windows, the NVIDIA driver silently spills into RAM (8.41 GB on a 6 GB card): slower here, an error under Linux.
  • Duration and cost come from a measured throughput, multiplied by the project's number of iterations.

Practice

  1. Run examples/02_budget.py, then add the model you are targeting with the values from its card.
  2. Measure your GPU's throughput (tokens/s) over 20 steps of examples/03_sft_lora.py and estimate the duration of a full training run.
  3. Under Windows, disable the RAM fallback in the NVIDIA control panel and rerun a training that is too large: what happens?

Resources