AI Hints
Home›Fine-Tuning LLMs Tutorial›Fitting Training into Memory
Fine-Tuning LLMs · Lesson 61 of 120

GPU Memory Budget

Will it fit?.

⏱ 2 min read▶ Video at 1:35:05🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

Before you rent a GPU, or start a long training run, you should know if it will fit in memory. Running out of memory, an hour into training, is painful. A quick budget prevents it.

  • Will it fit?
  • Out of memory hurts
  • Make a quick budget

A QLoRA budget

Let's budget QLoRA training for an eight billion model. The base weights in NF4 take about zero point five six bytes each. The LoRA weights and gradients take two bytes each. Adam's states take eight. And activations, the in between results kept for backward, depend on the batch size, and text length. We guess four gigabytes. Run it. About nine gigabytes in total. Notice how small the LoRA parts are. The base weights, and the activations, are what matter.

app.pypython
params = 8e9                 # an 8B model
lora_params = 42e6           # LoRA r=16 on all linear layers of that model

budget = {
    "Base weights (NF4)": params * 0.56,        # ~4.5 bits per weight, with scales
    "LoRA weights (bf16)": lora_params * 2,
    "LoRA gradients": lora_params * 2,
    "Adam states": lora_params * 8,
    "Activations (rough)": 4e9,                 # batch 4, 1024 tokens, checkpointing
}
for item, size in budget.items():
    print(f"{item:22} {size / 1e9:5.1f} GB")
print(f"{'Total':22} {sum(budget.values()) / 1e9:5.1f} GB")
Output
Base weights (NF4)       4.5 GB
LoRA weights (bf16)      0.1 GB
LoRA gradients           0.1 GB
Adam states              0.3 GB
Activations (rough)      4.0 GB
Total                    9.0 GB

Activations

What are activations? During the forward pass, every layer produces results. Backward needs them, to compute gradients, so they're kept in memory. More examples per batch, or longer texts, mean more activations. That's why batch size, and max length, are the first things to lower when memory runs out.

keyvalue
Activationsin-between results
Kept forthe backward pass
Grow withbatch size and text length
Out of memory?lower these first

Summary

Let's recap. Budget before you train. QLoRA memory is mostly the four bit base weights, plus activations. And activations grow with batch size, and text length. Next, a trick to use small batches without losing quality.

Key takeaways
  • Budget first
  • Base weights + activations
  • Batch and length drive activations
Next up: Gradient Accumulation — big batches, small memory