Skip to content

Block Swap: Stream frozen transformer blocks from host RAM so a dense model can train past the card's VRAM - #11832

Merged
danielhanchen merged 35 commits into
unslothai:mainfrom
LeoBorcherding:feat/block-swap
Oct 4, 2026
Merged

danielhanchen merged 35 commits into
unslothai:mainfrom
LeoBorcherding:feat/block-swap

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Closes #3997.

Adds block_swap_layers = N to get_peft_model on both the Llama fast path and the generic vision path. N decoder blocks, spaced evenly through the stack, live in pinned host RAM; each is fetched onto the card just before it runs and dropped right after. Under LoRA the base weights are frozen, so nothing is ever copied back: the host tensor stays authoritative. Only the fetch costs bandwidth, and at 2048 tokens and above it hides completely behind compute.

Measured on Llama-3.2-3B 4-bit, R9700 (ROCm 7.13, PCIe 4.0, 13.3 GB/s host-to-device), swapping 24 of 28 layers:

  • 1006 MiB less peak VRAM, constant across sequence length (it's weights, not activations)
  • smallest card that still trains: 5.00 → 4.06 GiB, by bisection under set_per_process_memory_fraction
  • step time within run-to-run noise at ≥2048 tokens (−0.3% at 2048, −1.2% at 4096, 3 reps); +3.2% at 512
  • 60/60 training steps bitwise identical to the no-swap run, through optimizer updates, driven through this parameter on this branch

The mechanism is unsloth_zoo.block_swap (companion: unslothai/unsloth-zoo#1378). This PR is the parameter, the install point, and the refusals.

How

block_swap_layers = 0 is the default and installs nothing. With N > 0, install_block_swap runs after PEFT wrapping on both paths:

  • N decoder blocks' frozen parameters are copied to pinned host memory. get_peft_model spaces them evenly, so each copy hides behind several layers of compute; from_pretrained keeps the last N, which it builds on the host. For bnb Params4bit only the packed uint8 blob travels; quant_state is small and stays resident, so dequant is unchanged.
  • Device slots come from a fixed pool of prefetch_depth + 1 per distinct parameter-shape signature, allocated once. Fetching into fresh tensors each time leaves the allocator's high-water mark near baseline (measured: 0.38 GiB smaller card instead of 0.94), because average residency drops but the peak doesn't. Unsloth's dynamic 4-bit quants leave some blocks unquantized, so the pool is per signature.
  • A forward pre-hook waits on the block's copy and issues the next fetch on a side stream. The direction depends on the pass: Unsloth's checkpointer runs each layer under no_grad in forward and again under enable_grad during backward, in reverse, so the prefetcher looks ahead in forward and behind in recompute. Looking only forward fetches already-finished layers that never get evicted.
  • Eviction is grad-mode aware. Under no_grad the weight isn't needed until recompute, so the forward post-hook drops it. With grad on, the graph just built still has to be walked, so eviction waits until the block's backward has run (a hook on the gradient of the block's input).
  • The first swapped block's release is the last swap event in a step, so it arms the next forward's leading fetches. No trainer callback, no step-boundary API; gradient accumulation needs nothing because every micro-batch is a full forward+backward.
  • Each parameter records its origin device and is restored there, with one side stream per device.

MoE models install with a notice: every expert moves while only the routed ones compute, so steps can be copy-bound. Refused with the reason named: unified-memory GPUs (no separate RAM to swap to; same probe the checkpointer uses for its double buffer), and fast_inference (evicted weights would sync to vLLM as empty tensors). An unsloth_zoo without block_swap is an ImportError naming the upgrade, so the zoo pin is unchanged; bumping it is a release decision once the companion ships.

Why this is affordable

Per layer, compute scales with tokens per step and the fetch doesn't, and the layer's own size cancels out of the comparison:

T  >=  (bytes/param * FLOP/s) / (2 * 3 * PCIe_bytes/s)

At 4-bit on this box that's ~190 tokens per step, independent of model size. Every real run is well past it, which is why overhead is zero above 512 tokens. The H2D copy hides 92% behind compute in isolation.

What it enables

The binding constraint moves from VRAM to system RAM.

hardware effect
8–16 GB consumer cards (3060, 4070, 7700 XT, 7800 XT, 4060 Ti) the target: the card holds ~3 layers plus activations, everything else lives in RAM
AMD consumer cards more headroom than NVIDIA at the same VRAM. Break-even scales with compute-per-PCIe, and a card that computes slower relative to its link has more time to hide the fetch
24 GB cards (3090, 4090, 7900 XTX) 70B-class dense models, once loading straight to host lands. Today the whole model loads onto the card before the swap installs
80 GB datacenter cards almost nothing; they already hold what they need
APUs and unified memory (Strix Halo, GB10) refused. No separate RAM to swap to. Measured on Strix Halo, below
Apple Silicon (MLX) no effect: unified memory, nothing to swap to. The MLX path ignores the argument
PCIe 3.0 or an x8 link still works; the 512-token overhead roughly doubles, the 2048+ case has the slack to absorb it

Only the first row below is measured; the rest is arithmetic at ~0.55 bytes/param at 4-bit, keeping three layers resident. Rows marked † need the tail loaded straight to host, from_pretrained(block_swap_layers = N) (Llama, Mistral, Qwen2/Qwen3 text paths); get_peft_model(block_swap_layers = N) alone still loads the whole model onto the card first:

model 4-bit weights fits 12 GB today resident with swap RAM needed
Llama-3.2-3B (measured) 2 GB yes, easily ~150 MB trivial
Llama-3.1-8B, Qwen3-8B ~5.5 GB yes, short context ~500 MB 16 GB
Qwen3-14B ~8.5 GB barely, tiny context ~550 MB 16 GB
Gemma-3-27B, Mistral-Small-24B † ~15 GB no ~750 MB 32 GB
Llama-3.3-70B, Qwen2.5-72B † ~40 GB no, nor on 24 GB ~1.3 GB 64 GB
any MoE all experts n/a experts of ~3 layers all experts

The 8B and 14B rows are where a 12 GB user feels it first: the model already fits, but freeing 5–8 GB of weights is the difference between 1k context and 8k, or batch 1 and batch 4.

Two things the table hides. lm_head never swaps: ~1 GB in bf16 on a 128k vocab at 4096 hidden, ~2 GB at 8192 (offload_embedding already handles the input side). So 70B on 12 GB is plausible but tight; on 16 GB it's comfortable. And the host copies are pinned, which the OS caps below total RAM, so "64 GB" means 64 GB with most of it pinnable.

Not in this PR

  • Full fine-tuning. Free eviction depends on frozen base weights.
  • Auto-sizing. N is explicit and defaults to 0. A user who is not OOMing should never silently start paying PCIe for a step, and "why did training get 30% slower after I updated" is a bad way to find out a heuristic mispredicted.

Tests

tests/test_block_swap_install.py, ast-extracted in the style of test_offload_embedding_hooks.py, no torch CUDA stack: off at 0, happy path records the swapper on the model, each of the three refusals names its reason, old zoo is an ImportError, and refusal order checks the cheap thing first. 7 pass.

The scheduling tests live with the mechanism in the companion PR.

Test coverage

The rule: whether the fetch hides depends on the PCIe link and the card's compute, so a result on one host says nothing about another, and the feature's whole value is on hardware nobody runs CI on. The one AMD runner that exists (Strix Halo, on ooba's fork) is a unified-memory APU, exactly the case this PR refuses, so it can verify the refusal and nothing else; it has, below. This section is the test report.

Where it was run

  • R9700: 32 GB, gfx1201, Windows 11, ROCm 7.13, torch 2.11.0+rocm7.13.0, PCIe 4.0 x16 (13.3 GB/s measured). Measured at zoo 936f58d3, core 2c451f78. The zoo head has since moved to 5f932966 through review follow-ups (per-device copy streams, a fallback off pinned memory, state_dict aliasing, inference-mode handling); no R9700 row was re-run there.
  • Strix Halo: Radeon 8060S, gfx1151, 76.8 GiB unified, Windows, torch 2.11.0+rocm7.13.0, the AMD DevLab runner on oobabooga/unsloth. Core a29a28ae, zoo 5f932966.
machine ran result
R9700 Llama-3.2-3B 4-bit, 24/28 layers: sweep at 512/2048/4096, 3 reps; VRAM bisection; 60-step equivalence 1006 MiB saved; smallest card 5.00 → 4.06 GiB; 0% overhead at ≥2048; 60/60 bitwise
R9700 same, through get_peft_model(block_swap_layers=24) 60/60 bitwise; 610.7 MiB saved at 1024
R9700 Qwen3-0.6B 4-bit (tied embeddings, mixed quant), 16 layers, forward logits identical
Strix Halo get_peft_model(block_swap_layers=8), Qwen3-0.6B bf16, run refused with the unified-memory message; is_integrated reads 1

Requested runs

Everything below is arithmetic or untested. A row is a request, not a claim.

P0: blocks calling this mergeable

# on run proves
1 any NVIDIA card Llama-3.2-3B 4-bit: sweep + 60-step equivalence the mechanism on CUDA at all; every number above is ROCm
2 Colab T4 Llama-3.1-8B 4-bit, 24/32 layers: sweep at 512 and 2048 half this box's PCIe bandwidth; whether 512-token overhead stays under ~10%
3 12 GB card Gemma-3-27B or Mistral-Small-24B 4-bit: baseline OOMs, swap trains the headline. Needs from_pretrained(block_swap_layers = N) on a card the model does not fit
4 2× same card, DDP Llama-3.2-3B: one epoch vs single GPU side stream vs all-reduce; per-rank pools. Kaggle 2×T4 covers rows 2 and 4
5 any card GRPO, fast_inference=False, 20 steps evicted weights survive the inference/train toggle
6 any card generate() after training, swap on fixed: every custom decode loop (Llama, Gemma, Gemma2, Falcon-H1, Granite, Cohere, and zoo's gpt-oss) calls enter / leave. Verified on CUDA below
7 any card swap with use_gradient_checkpointing=False: 60-step equivalence refused in core. The zoo scheduler also no longer reuses a slot backward still reads (it grows the pool instead), which covers eval-mode or use_cache grad forwards that skip checkpointing

P1: blocks recommending it to users

# on run proves
8 2 cards, device_map sharding Llama-3.1-8B: forward equivalence + 20 steps origin-device restore alongside accelerate's hooks
9 24 GB card, 64 GB RAM Llama-3.3-70B 4-bit, ~75/80 layers: bisection at 2048 the 70B claim, and pinning ~40 GB on that OS. Blocked like row 3
10 any card Gemma-3-12B VLM or Qwen2.5-VL: equivalence + 20 steps picks the text decoder; the vision tower is untouched
11 RDNA3, Linux ROCm Llama-3.2-3B: sweep Linux vs Windows pinned memory; the first RDNA3 number
12 any card gradient_accumulation_steps=4: 60-step equivalence backward-hook arming across micro-batches
13 any card Llama-3.1-8B at 8192 and 16384 tokens the swap stays invisible at long context
14 any card save_pretrained_merged with swap on the merged save walks layers itself; evicted weights must come from the host copy

P2: completes the picture

# on run proves
15 any card Llama-3.2-3B 8-bit and bf16: equivalence each only Params4bit has been round-tripped
16 any card at x8 Llama-3.2-3B: sweep at 512 the link most likely to push overhead positive
17 2 mixed cards Llama-3.1-8B sharded: forward equivalence per-device pools with different free VRAM
18 any card Qwen3-Next-80B-A3B or Mixtral: block_swap_layers=8 MoE refusal, no partial install
19 Apple Silicon (MLX) block_swap_layers=8 runs unchanged; the MLX path prints a no-effect notice

CUDA verification (B200, torch 2.13 + cu130)

Maintainer runs at core a1864d25 + zoo a0337515 (performance rows at zoo 75d95d8a). B200 compute per PCIe byte is far above the break-even this PR targets, so step time here says nothing about consumer cards; the rows below are correctness and memory. "vs remove()" = the same trained weights with the swapper removed in the same process.

run result
Llama-3.2-1B 4-bit, 12/16 layers, 20 steps, get_peft_model peak 1.84 -> 1.59 GiB; loss within the A/A band (same code twice differs by up to 5e-4 by step 3 on this GPU)
same through from_pretrained(block_swap_layers = 12) 1.01 -> 0.75 GiB at load; peak 1.59 GiB
Qwen3-0.6B bf16, 20/28 layers, both routes peak 2.05 -> 1.55 GiB; 0.68 GiB at load via from_pretrained
generate() after training (row 6), both models, both routes tokens identical and logits bitwise vs remove()
save_pretrained + save_pretrained_merged 16-bit (row 14) byte-identical vs remove(); no empty tensors (bf16 merge reads the evicted modules)
20 AdamW steps from one LoRA init, in process step 0 bitwise; swap vs off max loss diff 4.5e-3 / 8.3e-3 vs same-code A/A 3.6e-3 / 6.3e-3, both first diverging at step 1
use_gradient_checkpointing = True trains; peak 1.90 -> 1.65 GiB
gradient_accumulation_steps = 4 (row 12) loss matches no-swap to 3-4 decimals
GRPO, fast_inference = False, 5 steps, 20/28 layers (row 5) loss, KL, reward std equal to no-swap at logged precision; every swapped weight equals its host copy afterwards
Qwen2.5-VL-3B (28 layers) and Gemma-3-4B (24 layers) vision path (row 10) one step: loss equal, LoRA grads bitwise, generate identical vs remove(); peak 4.05 -> 3.13 and 4.93 -> 3.93 GiB
transformers 4.57.6 + TRL 0.22.2 both routes train; generate / logits / saves identical vs remove()
step time, compute-bound: Llama-3.1-8B 4-bit, 28/32 swapped, batch 4 x 2048 / x 4096 +0.7% / -0.2% vs no swap (437 / 922 ms), peak 7.94 -> 5.40 / 9.34 -> 6.80 GiB; GPU compute per step identical with and without the swap
install time, Llama-3.1-8B 4-bit tail (2.84 GiB) 3-4 s (per-tensor pinning took 44-47 s)
pinned host RAM exact size (1.13 GiB for 1.13 GiB of Llama-3.2-3B tail; per-tensor pinning held 1.59), pinned only while max(4 GiB, 15%) of RAM stays free
swap off (default) base vs head jobs/sft.py, vision_sft.py (+ gemma4), vision_grpo.py, inference_smoke.py, tiny-model regression smoke: no regression; greedy decode tokens identical base vs head

Bottom line

Solid: the mechanism, the scheduling and numerical inertness, on one ROCm card with one 3B model, through the shipped parameter, plus the unified-memory refusal on a real APU. CUDA correctness is now covered (section above). Missing: any two-card run, a CUDA step-time number on a consumer PCIe link, and any model that didn't fit without the swap.

Generic rewrite (c91bb15b, zoo 762e068e)

  • Any architecture. Block discovery falls back to the largest layer list (transformer.h, decoder.block, decoder.layers).
    • 18 architectures via transformers + PEFT, 12 layers each with 8 swapped, last-N and spread placement. Logits, loss, LoRA grads under reentrant and non-reentrant checkpointing, and greedy generate are all bitwise equal to swap off.
    • The 18 are Llama, Qwen2, Qwen3, Qwen3-MoE, GPT-OSS, Mistral, Gemma2, Gemma3 text and multimodal, Phi3, GPT2, GPTNeoX, Falcon, Qwen2.5-VL, Qwen3-VL, Mllama, T5 and Bart.
    • The previous head could not find the layers of GPT2, Falcon, T5 and Bart, and its full backward hook moved 72/384 encoder LoRA grads on T5 and Bart.
  • Through Unsloth's loaders. 12-layer copies with 8 swapped: Qwen3, Qwen3-MoE, GPT-OSS, Mistral, Gemma2, Gemma3 and Phi3 train and generate bitwise equal to swap off.
  • Placement. Spread placement for get_peft_model. Llama-3.1-8B, 16/32 swapped, batch 1 x 512, step time vs swap off:
host link last 16 spread
B200 as is +0.6% +0.8% to +4.0% (within the 15-24% noise of this shared run)
4x slower (emulated) +45% +19%
8x slower (emulated) +155% +127%

Batch 4 x 2048: +0.4% / +0.2%, noise 1%.

  • Memory. Unchanged: Llama-3.1-8B batch 1 x 2048 peaks at 6.06 GiB with either head. Under a 7 GiB cap the model without swap runs out of memory, and with 16 swapped it trains.
  • End to end. Llama-3.2-1B 4-bit, 12/16 swapped:
    • Generate, logits, adapter save and merged save are identical to remove().
    • GRPO, 20 swapped: finite, LoRA moves, host copies intact.
    • Qwen2.5-VL-3B, 28 swapped: grads bitwise, generate equal.
  • MoE, Cohere, Granite and Falcon-H1 are no longer refused.

block_swap_layers = "auto" (36115fe5, zoo 379d85b1)

"auto" swaps only when training would not otherwise fit. When it fits, nothing is installed: no hooks and no pinned RAM.

  • from_pretrained(block_swap_layers = "auto") sizes the model on the meta device before loading, using zoo's plan_block_swap.
    • It loads nothing into host RAM if the weights plus a training reserve fit. Otherwise it keeps the fewest trailing layers in host RAM.
    • With device_map = "unsloth" / "unsloth_balanced" the multi-GPU planner places the resident layers across cards, and the host tail's slot pool is charged to the head's card. Otherwise it sizes the one card the load uses.
    • Batch size or an explicit reserve can be passed via device_map_planner_kwargs.
  • get_peft_model(block_swap_layers = "auto") on a loaded model swaps only each GPU's shortfall, as evenly spaced layers.
  • The reserve covers:
    • activations: 48 bytes per token per hidden unit, rounded up from Llama-3.1-8B
    • fp32 logits for up to 2048 rows
    • gradients and AdamW state of the LoRA parameters
    • a 256 MiB margin
  • Load restrictions (state_dict, gguf, 8-bit, packed formats, fast_inference) make "auto" load onto the GPU instead of raising.

Llama-3.1-8B 4-bit, batch 1 x 2048, process capped at 7 GiB:

load layers in host RAM peak trains
no swap 0 OOM no
from_pretrained(block_swap_layers = "auto") 17 of 32 5.96 GiB yes
get_peft_model(block_swap_layers = "auto"), 7 GiB left after load 6 of 32 6.58 GiB yes
from_pretrained(block_swap_layers = "auto"), 40 GiB cap 0 7.38 GiB yes, unchanged

The multi-GPU path is covered by planner unit tests on meta models only, because this host gives one GPU.

Embedding offload on every text path (b33452b8, zoo 33f8c3f9)

  • offload_embedding now works on FastLanguageModel. The fast Llama-family path (Llama, Mistral, Qwen2/3, Cohere, Granite, Falcon-H1) used to drop it with a notice. It now uses the same offload_input_embedding as FastModel.
  • block_swap_layers = "auto" moves the input embedding first, both at load (through the planner) and after load (in get_peft_model). Layers are swapped only for what is still short. Only the looked-up rows cross PCIe.
    • Tied embeddings, Windows/WSL, models split across GPUs and distributed runs keep the embedding on the GPU, as before.
    • offload_embedding = False opts out.
  • Without a memory plan, "auto" keeps the existing size rule.
  • Training embed_tokens moves an offloaded embedding back to the GPU.

Llama-3.1-8B 4-bit, batch 1 x 2048:

run in host RAM peak result
offload_embedding = False none 7.38 GiB baseline
offload_embedding = True embedding (0.98 GiB) 6.40 GiB step-1 loss bitwise, generation identical
from_pretrained(block_swap_layers = "auto"), 7 GiB cap embedding + 7 layers 6.00 GiB trains (was 17 layers without the embedding)
same, 6.5 GiB cap embedding + 12 layers 5.49 GiB trains
get_peft_model(block_swap_layers = "auto"), 6.5 / 6 GiB free embedding + 5 / 13 layers 5.68 / 4.97 GiB trains

Step-1 LoRA gradients are not bitwise run to run, even with the embedding on the GPU in both runs. So they were compared through the loss and generation only.

Every architecture, memory-driven embedding offload (06fb20c0, zoo f3f15781)

  • from_pretrained(block_swap_layers = N | "auto") on the generic path. FastModel and every model FastLanguageModel routes there (Gemma 3/4, Qwen3.5, Qwen2.5-VL, gpt-oss and anything the auto compiler patches) now load straight to host RAM. Before, only the Llama-family fast path could.
    • The loader wraps the transformers weight sink and moves each chosen layer to host RAM as soon as its last weight lands, after any on-the-fly 4-bit quantization. No per-architecture builder is needed.
    • The allocator warmup and the async prefetch are off while it runs, so the card never holds more than the resident layers plus one in flight.
    • Spread placement, as in get_peft_model. One GPU only; a multi-card map keeps the previous behaviour.
  • offload_embedding = "auto" follows free memory. Embeddings move only when the card lacks a training step's reserve: checked at load, again in get_peft_model, and first in any block swap plan. With room to spare nothing moves.
    • Every large token table lm_head does not share moves, not only the input embedding. A tied model like gemma-4-E4B therefore still offloads its 5.25 GB per-layer embedding.
    • The planner counts those tables, and the load streams them to host like the layers.
  • torch.compile. Swap and embedding hooks are torch.compiler.disabled.
    • Through Unsloth's loaders there are 0 graph breaks and the same unique_graphs with swap off and on (e.g. gpt-oss 34 / 34).
    • Per-layer compile() with swap is bitwise equal to per-layer compile without swap, with the same graph count.
    • A user torch.compile of the whole model now runs instead of failing to trace the stream ops. It breaks once around each swapped layer.
  • Reserve. Now counts expert LoRA on fused MoE weights, the foreach AdamW temporary, a 1/16 allocator margin, and set_per_process_memory_fraction.

B200, 4-bit, batch 1 x 1024, 6 steps. "Squeezed" leaves the stated free memory after load (get_peft_model(block_swap_layers = "auto")); "load cap" limits the card before the load (from_pretrained(block_swap_layers = "auto")). Step time is on a shared host, as a ratio only.

model run in host RAM load peak loss vs off
gpt-oss-20b-unsloth-bnb-4bit squeezed to 1 GiB embedding + 8 layers 11.70 14.73 -> 11.78 bitwise (loss, grad norms)
Qwen3.5-35B-A3B load cap 30 GiB embedding + 30/40 layers 18.39 -> 8.03 35.78 -> 25.41 bitwise (loss, grad norms)
Qwen3.5-35B-A3B squeezed to 12 GiB embedding + 23/40 layers 18.39 35.78 -> 28.15 within 5.2e-4
gemma-4-26B-A4B-it load cap 20 GiB 26/30 layers 14.26 -> 6.66 23.55 -> 15.95 within A/A (6.3e-3 vs 9.1e-3)
gemma-4-26B-A4B-it squeezed to 4 GiB 24/30 layers 14.26 23.55 -> 16.71 step 1 equal, then 1.1e-2 vs A/A 9.1e-3
gemma-4-E4B-it load cap 8 GiB per-layer embedding 10.21 -> 4.96 12.43 -> 7.18 step 1 equal, then 5.3e-3 vs A/A 3.5e-3 to 4.9e-3
gemma-4-E4B-it squeezed to 1 GiB per-layer embedding 10.21 12.43 -> 7.18 step 1 equal, then 3.7e-3 vs A/A 3.5e-3 to 4.9e-3
Qwen3.5-2B from_pretrained(block_swap_layers = 8) 8/24 layers 1.84 -> 1.76 2.50 -> 2.42 bitwise
Qwen3.5-2B squeezed to 1 GiB 23/24 layers 1.84 2.50 -> 2.04 bitwise
Qwen3-0.6B squeezed to 0.6 GiB 27/28 layers 0.60 1.39 -> 0.71 within 2.3e-4
Llama-3.2-1B-Instruct squeezed to 0.6 GiB 15/16 layers 1.08 1.80 -> 1.13 within A/A
  • Unchanged without memory pressure. With room to spare, "auto" moves nothing. gemma-4-E4B with the per-layer table forced to host (offload_embedding = True): peak -5.25 GiB; step time +1.6% and +23% in two runs on this busy host, so no speed claim.
  • Generation. Greedy output before training is identical in every row.
  • Tiny switchboard models, get_peft_model(block_swap_layers = 1) and from_pretrained(block_swap_layers = 1): loss, grad norms and generation bitwise equal to swap off.
    • Covered: Qwen3, Qwen3-MoE, GptOss, Gemma2, Gemma3, Gemma4, Qwen3.5, Qwen2.5-VL.
    • The tiny Llama-3.2 checkpoint fails with swap off on this GPU, since xformers has no kernel for head dim 2, so it says nothing either way.

Not covered here: multi-GPU load-to-host (it keeps the previous behaviour) and gradient-checkpointing-off timing. use_gradient_checkpointing = False followed by for_training(model) fails with _gradient_checkpointing_func missing on main too, independent of this PR; it is fixed separately in #12629.

checkpoint_skip_layers (2d290ccf)

get_peft_model(..., checkpoint_skip_layers = K | "max") keeps the activations of K evenly spaced decoder layers instead of recomputing them in backward. "max" means all of them. It is opt-in and 0 by default: each un-checkpointed layer costs 30 to 75 bytes per token per hidden unit, depending on the architecture, and the batch size is not known at get_peft_model time. Turning it on automatically could therefore run out of memory mid-training.

  • The skip survives for_training, gradient_checkpointing_enable and the trainer turning checkpointing back on.
  • It works on both the Llama-family fast path and the generic path.
  • Block-swapped layers stay checkpointed.

Batch 1 x 1024, median step time, checkpointing on vs skipped:

model setting step time peak loss
Qwen3-0.6B "max" 169 -> 115 ms (-32%) 1.39 -> 2.48 GiB within 4.6e-4
Qwen3-0.6B 14 of 28 169 -> 142 ms (-16%) 1.39 -> 1.93 GiB within 8.0e-4
Qwen3.5-2B "max" 304 -> 211 ms (-31%) 2.50 -> 5.70 GiB bitwise
gemma-4-E4B-it "max" 520 -> 295 ms (-43%) 12.43 -> 20.42 GiB within 2.3e-3 (A/A 3.5e-3 to 4.9e-3)
Llama-3.2-1B-Instruct "max" 116 -> 71 ms (-39%) 1.80 -> 2.79 GiB within 1.5e-4
  • Combined with block_swap_layers = "auto" on a squeezed Qwen3-0.6B, 27 layers swap and the one resident layer skips recompute. Peak is 0.75 GiB and the loss is within 6.7e-4.
  • Selective checkpointing that saves only matmul and attention outputs would need non-reentrant checkpointing, while Unsloth's checkpointer is reentrant. It is not attempted here.

PCIe step time (Colab L4, PCIe Gen3 x16, merge 46597af1, zoo 3a048a0c)

Batch 1 x 1024, 4-bit, median step time over 10 steps (8 for gemma). "squeezed" leaves only a little free VRAM so "auto" picks the count.

model setting layers in RAM peak step time loss
Qwen3-0.6B off 0 1.34 GiB 300 ms
Qwen3-0.6B block_swap_layers = 14 14 1.27 GiB 310 ms (+3%) step 1 equal
Qwen3-0.6B "auto", squeezed 27 0.66 GiB 323 ms (+8%) step 1 equal
Qwen3.5-2B off 0 2.46 GiB 472 ms
Qwen3.5-2B block_swap_layers = 12 12 2.30 GiB 488 ms (+3%) step 1 equal
Qwen3.5-2B "auto", squeezed 23 2.00 GiB 464 ms (noise) step 1 equal
Llama-3.2-1B-Instruct off 0 1.76 GiB 219 ms
Llama-3.2-1B-Instruct "auto", squeezed 15 1.08 GiB 239 ms (+9%) step 1 equal
gemma-4-E4B-it off 0 12.38 GiB (load 10.18) 1360 ms
gemma-4-E4B-it from_pretrained(block_swap_layers = "auto"), 8 GiB usable per-layer table 7.13 GiB (load 4.93) 1367 ms (+0.6%) step 1 equal
  • 0 graph breaks in every row.
  • The cost on PCIe is 0 to 9%, highest when almost every layer of a small model is in RAM (little compute per layer to hide the copy).
  • Later-step losses differ by up to about 1e-3 on this GPU; no A/A was run on the L4, and every pair converges to the same loss.

…rain past the card's VRAM

Adds block_swap_layers to get_peft_model on both the Llama fast path and
the generic vision path. The last N decoder blocks are kept in pinned host
RAM and fetched onto the card just before they run; under LoRA the base
weights are frozen, so nothing is ever copied back and only the fetch
costs bandwidth. Off at 0.

install_block_swap refuses the three cases where it cannot help or would
break, each with the reason: MoE moves every expert but computes with the
active ones, so the copy never hides; a unified-memory GPU has no separate
RAM to swap to; vLLM would sync evicted weights as empty tensors. An
unsloth_zoo without block_swap is an ImportError naming the upgrade.

The mechanism is unsloth_zoo.block_swap; this is the parameter and the
gate. Measured on Llama-3.2-3B 4-bit swapping 24 of 28 layers: 1006 MiB
less peak VRAM at every sequence length, the smallest budget that still
trains down from 5.00 to 4.06 GiB, step time within noise at 2048 tokens
and above, and 60 of 60 steps bitwise identical to the no-swap run.

Closes unslothai#3997.
@LeoBorcherding LeoBorcherding changed the title Stream frozen transformer blocks from host RAM so a dense model can train past the card's VRAM Block Swap: Stream frozen transformer blocks from host RAM so a dense model can train past the card's VRAM Sep 24, 2026
LeoBorcherding

This comment was marked as resolved.

…), refuse without checkpointing

from_pretrained(block_swap_layers = N) trims the config so the standard load
stops before the last N decoder layers, builds those in pinned host RAM from the
checkpoint, and installs the swap at load. A model larger than the card now
loads and trains; get_peft_model reuses the load-time swapper.

Unsloth's fast decode loop reads attention and MLP weights without calling the
decoder layer, so the swap's hooks never fired and evicted layers ran with empty
weights. The loop now drives the swap directly.

block_swap_layers is refused with use_gradient_checkpointing off: every swapped
block stays live until backward, so nothing is saved and the pool runs dry.
Loading straight to host covers the Llama, Mistral and Qwen2/Qwen3 text paths;
the generic path says to pass block_swap_layers to get_peft_model instead.
@danielhanchen danielhanchen self-assigned this Sep 26, 2026
danielhanchen and others added 6 commits September 26, 2026 12:13
…ew-model route

Inserting it after use_gradient_checkpointing shifted random_state and every later positional argument. UNSLOTH_USE_NEW_MODEL=1 delegated to FastBaseModel.get_peft_model without it, so the swap was silently skipped.
…ttributes to host-built layers, trim a copy of the config
…rs 4.x load

from_pretrained(block_swap_layers = N) trims the config so the standard load builds fewer layers, but on transformers 4.57 the tail's keys still went through the per-shard loader: bnb stat keys reached the quantizer (ModuleList has no attribute `10`) and plain weights logged 'were not used', which RaiseUninitialized raises. Drop them in _get_key_renaming_mapping for the duration of the load only; 5.x has no such method and already skips them. Verified bitwise-equal grads, logits, greedy decode and merged save vs no swap on 4.57.6 for Llama-3.2-1B 4-bit and Qwen3-0.6B bf16.
…'s skip list and variant

from_pretrained(block_swap_layers = N) built the swapped tail on torch.cuda.current_device(), so device_map = {"": 1} split the model across cards; it now follows the last resident layer. The tail was quantized with the static SKIP_QUANTIZATION_MODULES, dropping Falcon-H1's out_proj exclusion that its mamba kernels need, and read the default checkpoint even when variant= selected another one.
The host-built tail is read from safetensors, so a GGUF or BIN prefix would either mix two checkpoints or crash after the prefix loaded. Refuse before any download.
…ces and packed checkpoints

get_peft_model returned early for an already-wrapped model without installing the requested swap. The mechanism runs on CUDA/HIP streams, so XPU, NPU and CPU are refused up front instead of failing after the prefix loads. from_pretrained(block_swap_layers = N) refuses non-bitsandbytes quantized checkpoints (FP8, GPTQ, AWQ), whose packed tensors the host tail cannot rebuild.
Falcon-H1's decode loop calls attention, mamba and MLP submodules directly, so swapped weights were never fetched during generate(). A caller BitsAndBytesConfig quantized the prefix while the host tail was rebuilt from load_in_4bit alone, i.e. dense.
Granite's and Cohere's decode loops call attention and MLP submodules directly, like Falcon-H1, so generate() never fetched swapped weights. A caller state_dict fed the prefix while the host tail was read from the checkpoint files. Adds a test that every model-level decode loop either serves the swapper or is refused.
FastLanguageModel already routes 8-bit to FastModel, which refuses block_swap_layers; a direct FastLlamaModel.from_pretrained(load_in_8bit = True) would have rebuilt the host tail dense.
@unslothai unslothai deleted a comment from LeoBorcherding Sep 29, 2026
- get_peft_model(block_swap_layers = N) spaces the swapped layers evenly so each copy hides behind
  several layers of compute; from_pretrained keeps the last N, which it builds on the host.
- Cohere, Granite and Falcon-H1 decode loops call enter/leave, so they are no longer refused.
- MoE models install with a notice that steps can be copy-bound, instead of an error.
- Falls back to the last N on an unsloth_zoo without placement support.
- from_pretrained(block_swap_layers = "auto") sizes the host tail with unsloth_zoo's planner before
  loading: nothing when the model plus a training reserve fits, else the fewest trailing layers.
  device_map = "unsloth" / "unsloth_balanced" plans every GPU together; otherwise the one card the
  load uses. Batch size and reserve via device_map_planner_kwargs.
- get_peft_model(block_swap_layers = "auto") swaps only each GPU's shortfall on a loaded model.
- Load-to-host restrictions make "auto" load onto the GPU instead of raising.
- The host tail fetches onto the head's card.
- offload_input_embedding / restore_input_embedding shared by FastModel and FastLlamaModel; the
  Llama, Mistral, Qwen2/3, Cohere, Granite, Falcon-H1 path honours offload_embedding instead of
  dropping it.
- block_swap_layers = "auto" moves the input embedding first, at load (planner) and after load
  (get_peft_model), and swaps layers only for the rest. offload_embedding = False opts out.
- Without a memory plan, "auto" keeps the size rule.
- Training embed_tokens moves an offloaded embedding back to the GPU.
from_pretrained(block_swap_layers = N | "auto") now loads straight to host RAM on
the generic path too (any transformers architecture, the auto-compiled ones
included), not only the Llama-family fast path. offload_embedding = "auto" moves
embeddings only when the card lacks a training step's reserve, and moves every
large untied token table, so a tied model still offloads Gemma 3n / 4 per-layer
embeddings. Offload hooks are opaque to torch.compile.
… K layers

K evenly spaced decoder layers keep their activations instead of being
recomputed in backward, trading VRAM for step time. Opt-in, 0 by default.
The skip survives for_training, gradient_checkpointing_enable and the trainer
turning checkpointing back on; block-swapped layers stay checkpointed.
# Conflicts:
#	unsloth/models/llama.py
#	unsloth/models/vision.py
@danielhanchen
danielhanchen merged commit 7911672 into unslothai:main Oct 4, 2026
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Nov 18, 2026
…st RAM to fork (unslothai#17701)

With Block Swap on Qwen3.8-Flash-Next (180B MoE), every Unsloth Studio
run with default settings was OOM-killed before step 1. Tokenizing the
dataset forks the loaded trainer, through either the
`dataset.map(num_proc=N)` pool or the online-tokenization DataLoader
workers. A forked child shares the parent's pages copy-on-write, so
every page the parent rewrites while the child lives is held twice. On a
Colab G4 (177 GiB host RAM) the trainer held about 133 GiB, host RAM
went from 138 to 165 GiB right after the fork, and the run was killed.

Both fork sites now ask `host_memory_fork_veto`, which vetoes the fork
when Block Swap is on, or when the trainer's RSS is above the host RAM
still available:
- `dataset_num_proc` asks for 1 (in-process). `UNSLOTH_DATASET_NUM_PROC`
still wins.
- Online tokenization turns off with that reason.
`UNSLOTH_STUDIO_ONLINE_TOKENIZATION=1` still forces it on.

The log says why: `Tokenizing in process: Block Swap keeps offloaded
layers in host RAM, which a fork would duplicate`.

**Evidence:** with this branch and no env overrides, Flash-Next trains
under Block Swap on one G4 at Count 32, Count 36, Count 36 batch 2 and
Count 36 at ctx 4096. Runs and recordings:
LeoBorcherding/unsloth-zoo#44

**Host RAM over the run, main vs this PR** (Count 32, same settings):

![host RAM over
time](https://github.com/LeoBorcherding/unsloth-zoo/raw/8b83a943/flash-next-sweep/charts/pr-17701-host-ram.png)

![peak host RAM and steps
finished](https://github.com/LeoBorcherding/unsloth-zoo/raw/8b83a943/flash-next-sweep/charts/pr-17701-outcome.png)

**Tested stacked with the Block Swap work**

The Flash-Next runs ran this branch on top of the rest of the Block Swap
stack. Core was unslothai/unsloth main `211f0ee22`, which already has
unslothai#11832, unslothai#12996, unslothai#12998, unslothai#15159, unslothai#15632 and unslothai#15633, plus this PR. The zoo
was main plus unslothai/unsloth-zoo#1619, unslothai#2269 and unslothai#2499, all merged
since. With that stack, Qwen3.8-Flash-Next-FP8 (180B MoE) LoRA-trains on
one RTX PRO 6000 96 GB in Unsloth Studio, with default settings and no
env overrides:

| Block Swap setting | VRAM | s/step | tokens/s |
|---|---|---|---|
| Count 32, ctx 1024 | 82.8 GiB | 6.05 | 169 |
| Count 36, ctx 1024 | 75.4 GiB | 9.07 | 113 |
| Count 36, ctx 1024, batch 2 | 76.0 GiB | 9.07 | 226 |
| Count 36, ctx 4096 | 77.4 GiB | 39.3 | 104 |

Without this PR, the same stack is OOM-killed before step 1. Full data,
charts and recordings: LeoBorcherding/unsloth-zoo#44

**Outside Block Swap:** I ran the same LoRA on a Colab T4 (12.7 GiB host
RAM, 2 CPUs) with Block Swap off, main and this branch side by side.
Llama-3.2-1B and Llama-3.1-8B (4-bit) trained on both, with the trainer
peaking at the same RSS: 3.0 vs 3.1 GiB and 6.0 vs 5.9 GiB. That's well
under the free RAM, so the veto stayed off and behavior matched main.
Qwen3-14B ran on main only, peaking at 6.3 GiB; the VM for this branch
was reclaimed before its run.

**Tests:**
- `test_dataset_map_num_proc.py`: the new
`test_a_trainer_too_big_to_fork_tokenizes_in_process` fails on main and
passes here (34/34).
- `test_online_tokenization.py` and
`test_online_tokenization_wiring.py`: new cases cover the Block Swap
veto, an unreadable memory read (no veto), and the env flag overriding
the gate.

Hardware: Linux, RTX PRO 6000 96 GB (Colab G4). Windows and macOS
already tokenize eagerly, because their workers spawn instead of
forking.

---

## Follow-up commit on this branch

`57b883d29e` Fork veto: count Block Swap Auto only when it offloads, one
host memory reading per run, cover the batched packing pool.

1. **Block Swap Auto that offloads nothing no longer turns workers
off.** `offload_layers = "auto"` attaches no swapper when the model fits
the card (`unsloth/models/_utils.py`: `_auto_block_swap_indices` returns
nothing, so no `_unsloth_block_swap`), so nothing sits in host RAM. As
first submitted, any `"auto"` run lost its `dataset.map` workers and
online tokenization anyway. The veto now reads
`_block_swap_engaged(trainer)`: a fixed count stands as asked, `"auto"`
counts only once a swapper is attached.
2. **One host memory reading per run.** The `dataset_num_proc` site and
the online tokenization gate each took their own RSS / available
reading, so near the line they could disagree (in-process map, then
forked persistent DataLoader workers). The gate now reuses the reading
the `dataset_num_proc` site took.
3. **Multi-LoRA packing asks the same veto.** `_pack_num_proc` in
`multi_lora_trainer.py` forks a packing pool off the same loaded base
model (Block Swap is passed to its `load_model` too). It now goes in
process under the same veto.

Each new test fails with its fix reverted (negative controls below).

## Evidence

**Copy-on-write repro (CPU, no PR code).** A process holding 1.8 GiB of
touched host memory runs `Dataset.map` over 4,000 rows inside a 3 GiB
cgroup (`systemd-run --user --scope -p MemoryMax=3G -p
MemorySwapMax=0`). Unique memory = summed PSS of parent and children,
sampled every 50 ms.

| arm | parent rewrites its memory while the pool lives | extra host RAM
| outcome |
|---|---|---|---|
| `num_proc=None` (in process) | yes | +0.01 GiB | finishes, rc 0 |
| `num_proc=2` (forked pool) | no | +0.05 GiB | finishes, rc 0 |
| `num_proc=2` (forked pool) | yes | climbs to the limit | OOM-killed,
rc 137 (`memory.events` oom_kill 1), orphaned workers hang |

Without a cgroup (3 GiB buffer, 1.6 TiB host) the same writing arm grew
by +1.27 GiB within 3.5 s, idle +0.05 GiB. The hazard is real, and its
size is what the parent rewrites while children live: persistent
online-tokenization workers live through all of training, the
`dataset.map` pool only through tokenization.

**Real cgroup reading.** `host_memory_snapshot()` in that 3 GiB scope
reads 2.98 GiB available (1597 GiB host-wide outside it); with 2.2 GiB
held it vetoes: `trainer holds 2.2 GiB of host RAM with 0.8 GiB
available, more than a fork can safely duplicate`. Cost: 245 to 355 us
per call, called once per run.

**Routing cells** (one subprocess per platform; `dataset_num_proc`
config value and the online tokenization decision; 4 Block Swap states x
4 memory states x `UNSLOTH_DATASET_NUM_PROC` unset / 3 = 96 cells):

| platform | cells | moved vs main, as first submitted | moved vs main,
with follow-up |
|---|---|---|---|
| macOS (darwin) | 32 | 0 | 0 |
| Windows (win32) | 32 | 0 | 0 |
| Linux | 32 | num_proc 13, online 26 | num_proc 10, online 20 |

On Linux every moved cell with the follow-up is a veto cell: a swapper
attached (fixed count or Auto that offloaded) or RSS above available.
The 3 num_proc / 6 online cells only the first version moved are Auto
with nothing offloaded. `UNSLOTH_DATASET_NUM_PROC` wins in every cell.

**Tokenized dataset and training parity** (Unsloth `SFTTrainer`, tiny
Llama, 4,000 rows, fp16 to mimic T4 numerics, 8 steps, correctness on
B200):

| dataset_num_proc | packing | rows | sha256 of tokenized rows | losses
(first 3, last) | grad norms (first 2) |
|---|---|---|---|---|---|
| 1 (veto) | off | 4000 | `bb48fd178fb0f72c` | 10.3799, 10.3837,
10.3826, 10.3557 | 0.380899, 0.341375 |
| 4 (pool) | off | 4000 | `bb48fd178fb0f72c` | 10.3799, 10.3837,
10.3826, 10.3557 | 0.380899, 0.341375 |
| 1 (veto) | on | 3019 | `c540da4422293d57` | 10.3801, 10.3783, 10.3664,
10.3604 | 0.349844, 0.373813 |
| 4 (pool) | on | 3019 | `c540da4422293d57` | 10.3801, 10.3783, 10.3664,
10.3604 | 0.349844, 0.373813 |

Byte-identical rows and bit-identical losses and grad norms in both
modes.

**Tests, main vs branch** (`test_dataset_map_num_proc.py`,
`test_online_tokenization.py`, `test_online_tokenization_wiring.py`):

| arm | result |
|---|---|
| main code + branch tests (`num_proc` + wiring files) | 2 failed, 66
passed (the two new veto tests) |
| first submitted head | 68 passed; with the online file 139 passed |
| head with follow-up | 148 passed |
| head with follow-up merged with current main (+
`test_multi_lora_trainer.py`) | 188 passed, 8 skipped |
| negative control: Auto counted as engaged | 2 failed (`[auto-None-0]`,
`..._offloaded_nothing_still_goes_online`) |
| negative control: online gate rereads memory | 1 failed
(`test_the_gate_reuses_the_reading...`) |
| negative control: packing ignores the veto | 1 failed
(`test_the_batched_packing_pool_asks_the_same_veto`) |

**Cross-platform.** Staging CI on the first submitted head:
ubuntu-latest green. macos-15 (70 of 139 failed) and windows-latest red.
These three test files pin `sys.platform = "linux"` but not the
multiprocessing start method, so on spawn hosts the start-method gate
answers before the gates under test. Emulating spawn on Linux, main's
own tests already fail 69 times. The new tests fail the same way (12
more), and none of them are production paths. In production on macOS and
Windows, `dataset_map_num_proc` returns None and online tokenization is
refused by its platform gate before the memory gate runs, so behaviour
there is unchanged (64 of 64 cells identical).

**Not proven here:** the 180B Flash-Next OOM itself (no reproduction on
this host; the contributor's G4 runs are the evidence); speed numbers
for in-process vs pooled tokenization (only reached on veto cells, never
for runs that fit); real macOS / Windows base-arm failure IDs for the
three test files.

---------

Co-authored-by: danielhanchen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Transformer Block Swap

3 participants