All guides

Your 4-bit QLoRA weights use 5 GiB, so why does fine-tuning still OOM on 24 GiB?

You load Llama-3.1-8B in 4-bit QLoRA using 5.31 GiB of VRAM on a 24 GiB GPU, freeze 98% of the parameters, set sequence length to 4,096 at micro-batch size 2, and crash with CUDA out of memory on step 1. Worse, following the top forum advice to shrink LoRA rank from r=64 to r=8 frees under 1 GiB and crashes on the exact same step.

  • On Llama-3.1-8B (8.03B parameters), shrinking LoRA rank from r=64 to r=8 across all 7 linear projections saves just 0.82 GiB of static adapter and 8-bit AdamW state (0.94 GiB vs 0.12 GiB).
  • Freezing 4-bit NF4 base weights skips weight optimizer states, not the 34.22 GiB of BF16 forward activations needed at 8,192 step tokens to backpropagate gradients back to layer 1's adapters.
  • Even with gradient checkpointing enabled (2.00 GiB saved checkpoints), standard Hugging Face CrossEntropyLoss spikes to 11.74 GiB on 128K-vocab Llama-3-8B and 27.34 GiB on 256K-vocab Gemma-2-9B unless replaced by fused linear cross-entropy (1.04 to 1.29 GiB).

Why lowering LoRA rank fails

Full BF16 fine-tuning of Llama-3.1-8B (8,030,261,248 parameters) needs 119.66 GiB before a single token runs: 14.96 GiB of weights, 14.96 GiB of gradients, and 89.75 GiB of FP32 AdamW states. QLoRA (arXiv:2305.14314) packs the 6.98B decoder linear weights into 4-bit NormalFloat with Double Quantization (4 + 8/64 + 32/(64 * 256) = 4.127 bits per parameter, or 3.35 GiB) and keeps the untied 128,256 x 4,096 input embeddings, lm_head, and RMSNorms in BF16 (1.96 GiB), totaling 5.31 GiB.

Attaching LoRA adapters (arXiv:2106.09685) of rank r=64 to all 7 linear projections per layer adds 167,772,160 trainable parameters (2.09% of the model), which take just 0.94 GiB across BF16 weights, BF16 gradients, and Paged 8-bit AdamW states. Cutting r=64 down to r=8 drops adapter state to 0.12 GiB, freeing only 0.82 GiB because LoRA adapters were never what filled your 24 GiB card.

Static component (Llama-3.1-8B)ParametersStorage formatVRAM
Full BF16 fine-tuning (no LoRA)8,030,261,248 (100%)2B weights + 2B grads + 12B FP32 AdamW119.66 GiB
QLoRA frozen base linear layers6,979,321,856 (86.91%)NF4 + Double Quantization (4.127 bits/param)3.35 GiB
QLoRA unquantized embeddings, lm_head, norms1,050,939,392 (13.09%)Untied 128,256 x 4,096 tables + RMSNorms in BF161.96 GiB
LoRA r=64 across all 7 linear projections167,772,160 (2.09%)2B BF16 weights + 2B grads + 2B Paged 8-bit AdamW0.94 GiB
LoRA r=8 across all 7 linear projections20,971,520 (0.26%)2B BF16 weights + 2B grads + 2B Paged 8-bit AdamW0.12 GiB (-0.82 GiB)

Frozen layers still save activations

Freezing requires_grad=False on 4-bit base weights skips base weight optimizer states, yet trainable LoRA adapters sit inside every block from layer 1 to layer 32. To propagate loss gradients from layer 32 all the way back to layer 1's A and B matrices, PyTorch autograd must still save every layer's BF16 forward activations along the chain.

Even with FlashAttention-2 avoiding O(S^2) attention score matrices in HBM, each Llama-3.1-8B layer stores RMSNorm inputs, Q/K/V/Out projections, and SwiGLU 14,336-wide MLP intermediates (arXiv:2205.01068). At 8,192 step tokens (micro_batch_size = 2, seq_len = 4,096), one layer holds 1.07 GiB of BF16 activations, or 34.22 GiB across all 32 layers.

  • Activations dwarf LoRA weights: Dettmers et al. (arXiv:2305.14314) measured 567 MB of input gradients against 26 MB of LoRA parameters on 7B LLaMA even at batch size 1 (21.8x larger).
  • What gradient checkpointing keeps: Storing only one [8192, 4096] BF16 boundary input per decoder block (64 MiB per layer) cuts saved backbone activations from 34.22 GiB down to 2.00 GiB (-94.2%), recomputing one 1.07 GiB layer at a time during backward.
  • Watch the frozen-input trap: Under legacy reentrant checkpoint hooks, if a quantized block's input tensor has requires_grad=False, autograd silently disconnects LoRA gradients unless you pass use_reentrant=False or call model.enable_input_require_grads().

The 128K-vocab loss spike

If gradient checkpointing drops saved activations to 2.00 GiB, why do modern 8B and 9B QLoRA runs still crash right at the end of the forward pass? Between 2023 and today, open-weight tokenizers expanded from 32,000 tokens (Llama 2, Mistral v0.1, Phi-3.5) to 128,256 on Llama 3 and 256,000 on Gemma 2.

Standard Hugging Face ForCausalLM computes [8192, 128256] BF16 logits (2,004 MiB), immediately upcasts the entire tensor to FP32 (logits.float(), 4,008 MiB), shifts token positions, and allocates FP32 log-softmax gradients. On an A100 at 8,192 tokens, Wijmans et al. (arXiv:2411.09009) measured 11.74 GiB (12,024 MiB) for Llama-3-8B's classifier head alone and 27.34 GiB (28,000 MiB) on Gemma-2-9B, exceeding a 24 GiB GPU by itself.

Four-bar chart comparing classifier-head Loss plus Gradient peak memory at 8,192 tokens across 32K-vocab Phi-3.5-Mini at 2.94 GiB, 128K-vocab Llama-3-8B at 11.74 GiB, 256K-vocab Gemma-2-9B at 27.34 GiB, and Llama-3-8B with Cut Cross-Entropy at 1.04 GiBClassifier head Loss+Gradient peak at 8,192 tokensPhi-3.5-Mini (32K vocab, unfused)2.94 GiBLlama-3-8B (128K vocab, unfused)11.74 GiBGemma-2-9B (256K vocab, unfused)27.34 GiB (OOM alone)Llama-3-8B with Cut Cross-Entropy1.04 GiB (-91%)
Model (A100, N = 8,192)Vocab |V|Unfused PyTorch / HFCut Cross-EntropyChange
Phi-3.5-Mini32,0642.94 GiB (3,006 MiB)0.23 GiB (236 MiB)-92.1%
Llama-3-8B128,25611.74 GiB (12,024 MiB)1.04 GiB (1,068 MiB)-91.1%
Mistral-NeMo-12B131,07212.00 GiB (12,288 MiB)1.33 GiB (1,362 MiB)-88.9%
Gemma-2-9B256,00027.34 GiB (28,000 MiB)1.77 GiB (1,809 MiB)-93.5%

Worse, in instruction SFT where prompt and padding positions carry labels == -100, unfused cross-entropy still allocates FP32 logits for every masked token before zeroing them out. Pre-filtering valid target indices before lm_head cuts unfused loss memory by 66.4% (arXiv:2411.09009), while fused linear cross-entropy kernels compute log-sum-exp in chunks or on-chip SRAM so full [N, |V|] logits never touch HBM at all.

Fitting 8B QLoRA on 24 GiB

Adding up all active PyTorch tensors at 8,192 step tokens shows why gradient checkpointing alone leaves Llama-3.1-8B right on the cliff at 19.99 GiB before 2 to 4 GiB of CUDA context, cuBLAS workspaces, and PyTorch caching-allocator block fragmentation. Pairing checkpointing with Liger Fused Linear Cross-Entropy (1.29 GiB loss head, arXiv:2410.10989) or Apple Cut Cross-Entropy (1.04 GiB loss head) brings peak active tensors down to 9.53 GiB and 9.43 GiB.

Notice why row 5 peaks at 9.43 GiB instead of 9.29 GiB: once Cut Cross-Entropy shrinks the loss step to 9.29 GiB (6.25 + 2.00 + 1.04), the true step peak moves to backbone backpropagation (6.25 GiB static + 2.00 GiB checkpoints + 1.07 GiB single recomputed layer + 0.11 GiB transient NF4 dequantization = 9.43 GiB), leaving roughly 13 GiB of clean room on a 24 GiB card.

Four-bar comparison of Llama-3.1-8B 4-bit QLoRA peak tensor memory at 8,192 tokens showing 52.2 GiB without gradient checkpointing, 51.2 GiB after shrinking LoRA rank from 64 to 8, 20.0 GiB with gradient checkpointing and unfused cross-entropy, and 9.4 GiB with gradient checkpointing plus fused cross-entropyLlama-3.1-8B QLoRA peak active tensors at 8,192 tokens24 GiB GPUDefault QLoRA (r=64, no ckpt)52.2 GiB (OOM)Shrink rank to r=8 (no ckpt)51.2 GiB (OOM)Grad checkpointing (unfused CE)20.0 GiB + CUDA overheadGrad ckpt + fused cross-entropy9.4 GiB (fits 24 GiB)
Configuration (8,192 tokens)StaticSaved act.Loss headPeak tensorsFits 24 GiB?
QLoRA r=64, no grad ckpt, default HF loss6.25 GiB34.22 GiB11.74 GiB52.21 GiBNo (2.2x over 24 GiB)
QLoRA r=8, no grad ckpt, default HF loss5.43 GiB34.03 GiB11.74 GiB51.20 GiBNo (saves 1.01 GiB total)
QLoRA r=64, grad ckpt, default HF loss6.25 GiB2.00 GiB11.74 GiB19.99 GiBOOM risk with 2 to 4 GiB CUDA/allocator overhead
QLoRA r=64, grad ckpt + Liger fused CE6.25 GiB2.00 GiB1.29 GiB9.53 GiBYes (~13 GiB headroom)
QLoRA r=64, grad ckpt + Cut Cross-Entropy6.25 GiB2.00 GiB1.04 GiB9.43 GiBYes (~13 GiB headroom)

1. Stop shrinking LoRA rank first

Cutting r=64 to r=8 frees 0.82 GiB of static state and 0.19 GiB of adapter activations at 8,192 tokens while reducing adapter capacity by 8x. Keep r=16 to r=64 and fix activations and loss tensors first.

2. Turn on non-reentrant checkpointing

Enable gradient_checkpointing=True with use_reentrant=False (or call enable_input_require_grads() on older hooks) so frozen 4-bit layers keep only 2.00 GiB of layer inputs instead of 34.22 GiB.

3. Fuse linear + cross-entropy loss

Set use_liger_kernel=True in TRL SFTConfig or patch Cut Cross-Entropy so your classifier head never allocates [N, |V|] FP32 logits in HBM, cutting Llama-3-8B loss memory from 11.74 GiB to 1.04 to 1.29 GiB.

4. Halve micro-batch before context length

Dropping per_device_train_batch_size from 2 to 1 and doubling gradient_accumulation_steps gives identical math at 4,096 step tokens, halving checkpointed inputs to 1.00 GiB (7.89 GiB backward peak).

Minimal TRL SFTConfig combining non-reentrant checkpointing, Paged 8-bit AdamW, and fused cross-entropy:

from trl import SFTConfig

sft_args = SFTConfig(
    per_device_train_batch_size=1,
    gradient_accumulation_steps=8,
    max_length=4096,
    gradient_checkpointing=True,
    gradient_checkpointing_kwargs={"use_reentrant": False},
    optim="paged_adamw_8bit",
    use_liger_kernel=True,  # chunks hidden states; skips [N, 128256] FP32 logits
)

Scope note: Static weights, adapter byte counts, and FlashAttention-2 per-layer activation figures above are deterministic tensor-byte calculations from the official meta-llama/Llama-3.1-8B architecture config, paired with published A100 classifier-head Loss+Gradient measurements from Wijmans et al. (arXiv:2411.09009, Tables 1, A1, and B1). Live nvidia-smi readings add roughly 1.5 to 3.5 GiB for the CUDA driver context, cuBLAS workspaces, and PyTorch caching-allocator fragmentation.

Once your fine-tuned adapter is merged or served in production, GPU memory bottlenecks shift from forward activations and FP32 loss logits to per-block 4-bit inference quantization scales, per-chat KV cache growth under 32 concurrent sessions, compute-bound prefill latency spikes, and MoE versus dense VRAM sizing. Browse all 21 breakdowns on the guides index.

Build clear intuition on backpropagation, quantization, and GPU memory math

Studying autograd Jacobians, NF4 double quantization, and cross-entropy memory inside one long AI thread derails fast whenever you ask a side question on a formula. Topic Breakdown generates a structured chapter roadmap and lets you highlight any equation or term to open a side-by-side chat right next to the chapter.

Or enter Backpropagation, activation checkpointing, and QLoRA fine-tuning on the home page.

Sources

Checked 29 November 2026