Estimate GPU memory for QLoRA-style fine-tuning

Before renting a GPU you want a quick memory estimate. In QLoRA-style training the frozen base model is stored in 4 bits and only the small LoRA adapters are trained, so optimizer state exists only for the adapters.

Write qlora_memory_gb(base_params, lora_params, base_bits, block, scale_bytes). Ignore activations. Use 1 GB = 1e9 bytes.
- base bytes = base_params * base_bits / 8 + ceil(base_params / block) * scale_bytes (one scale per block of weights)
- LoRA bytes = lora_params * 12: 2 bytes for the bf16 weight, 2 for its gradient, 8 for the two fp32 Adam moments
Return a dict with "base_gb", "lora_gb" and "total_gb" as floats.

Signaturedef qlora_memory_gb(base_params, lora_params, base_bits, block, scale_bytes)

Example

qlora_memory_gb(1e9, 1e7, 4, 64, 4) gives base_gb 0.5625, lora_gb 0.12, total_gb 0.6825.

Understand the idea

Before renting a GPU you want a rough memory number. In QLoRA-style training the big base model is frozen and stored in 4 bits, so it costs half a byte per weight plus a small scale per block. Only the small LoRA adapters are trained, so only they need gradients and optimizer state. Activations are ignored here. Worked example: base 7e9 params, 4 bits, block 64, scale 4 bytes; LoRA 2e7 params. Base = 7e9 * 4 / 8 = 3.5e9 bytes, plus ceil(7e9 / 64) = 109,375,000 scales * 4 = 0.4375e9 bytes, total 3.9375e9, so 3.9375 GB. LoRA = 2e7 * 12 = 2.4e8 bytes = 0.24 GB (2 for the bf16 weight, 2 for its gradient, 8 for two fp32 Adam moments). Total = 4.1775 GB. Rule: base_bytes = params * bits / 8 + ceil(params / block) * scale_bytes; lora_bytes = lora_params * 12; GB = bytes / 1e9. Charging Adam state on the frozen base weights gives a full fine-tuning estimate, far too high. This is the back-of-envelope sizing used before fine-tuning on a single GPU.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleqlora_memory_gb(1e9, 1e7, 4, 64, 4)
  • Sample 2: 7B model, 40M adaptersqlora_memory_gb(7e9, 4e7, 4, 64, 4)
  • Test 3: 8-bit base, odd block countqlora_memory_gb(1000, 10, 8, 64, 2)