Repository navigation
Block Swap: Stream frozen transformer blocks from host RAM so a dense model can train past the card's VRAM - #11832
Merged
Conversation
…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.
…), 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.
…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.
…layers on the new-model route
…ttributes to host-built layers, trim a copy of the config
# Conflicts: # unsloth/models/llama.py
…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.
- 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
…ves weights to host
…es it; headless tables return rows to the decoder card
…source check follow a wrapped condition
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):   **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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #3997.
Adds
block_swap_layers = Ntoget_peft_modelon 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:
set_per_process_memory_fractionThe 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 = 0is the default and installs nothing. With N > 0,install_block_swapruns after PEFT wrapping on both paths:get_peft_modelspaces them evenly, so each copy hides behind several layers of compute;from_pretrainedkeeps the last N, which it builds on the host. For bnbParams4bitonly the packed uint8 blob travels;quant_stateis small and stays resident, so dequant is unchanged.prefetch_depth + 1per 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.no_gradin forward and again underenable_gradduring 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.no_gradthe 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).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). Anunsloth_zoowithoutblock_swapis anImportErrornaming 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:
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.
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: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_headnever swaps: ~1 GB in bf16 on a 128k vocab at 4096 hidden, ~2 GB at 8192 (offload_embeddingalready 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
Nis 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 oftest_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 anImportError, 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
936f58d3, core2c451f78. The zoo head has since moved to5f932966through 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.a29a28ae, zoo5f932966.get_peft_model(block_swap_layers=24)get_peft_model(block_swap_layers=8), Qwen3-0.6B bf16, runis_integratedreads 1Requested runs
Everything below is arithmetic or untested. A row is a request, not a claim.
P0: blocks calling this mergeable
from_pretrained(block_swap_layers = N)on a card the model does not fitfast_inference=False, 20 stepsgenerate()after training, swap onenter/leave. Verified on CUDA belowuse_gradient_checkpointing=False: 60-step equivalenceuse_cachegrad forwards that skip checkpointingP1: blocks recommending it to users
device_mapshardinggradient_accumulation_steps=4: 60-step equivalencesave_pretrained_mergedwith swap onP2: completes the picture
Params4bithas been round-trippedblock_swap_layers=8block_swap_layers=8CUDA verification (B200, torch 2.13 + cu130)
Maintainer runs at core
a1864d25+ zooa0337515(performance rows at zoo75d95d8a). 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.get_peft_modelfrom_pretrained(block_swap_layers = 12)from_pretrainedgenerate()after training (row 6), both models, both routessave_pretrained+save_pretrained_merged16-bit (row 14)use_gradient_checkpointing = Truegradient_accumulation_steps = 4(row 12)fast_inference = False, 5 steps, 20/28 layers (row 5)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 headBottom 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, zoo762e068e)transformer.h,decoder.block,decoder.layers).get_peft_model. Llama-3.1-8B, 16/32 swapped, batch 1 x 512, step time vs swap off:Batch 4 x 2048: +0.4% / +0.2%, noise 1%.
remove().block_swap_layers = "auto"(36115fe5, zoo379d85b1)"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'splan_block_swap.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.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."auto"load onto the GPU instead of raising.Llama-3.1-8B 4-bit, batch 1 x 2048, process capped at 7 GiB:
from_pretrained(block_swap_layers = "auto")get_peft_model(block_swap_layers = "auto"), 7 GiB left after loadfrom_pretrained(block_swap_layers = "auto"), 40 GiB capThe 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, zoo33f8c3f9)offload_embeddingnow works onFastLanguageModel. The fast Llama-family path (Llama, Mistral, Qwen2/3, Cohere, Granite, Falcon-H1) used to drop it with a notice. It now uses the sameoffload_input_embeddingas FastModel.block_swap_layers = "auto"moves the input embedding first, both at load (through the planner) and after load (inget_peft_model). Layers are swapped only for what is still short. Only the looked-up rows cross PCIe.offload_embedding = Falseopts out."auto"keeps the existing size rule.embed_tokensmoves an offloaded embedding back to the GPU.Llama-3.1-8B 4-bit, batch 1 x 2048:
offload_embedding = Falseoffload_embedding = Truefrom_pretrained(block_swap_layers = "auto"), 7 GiB capget_peft_model(block_swap_layers = "auto"), 6.5 / 6 GiB freeStep-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, zoof3f15781)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.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 inget_peft_model, and first in any block swap plan. With room to spare nothing moves.torch.compiler.disabled.unique_graphswith swap off and on (e.g. gpt-oss 34 / 34).compile()with swap is bitwise equal to per-layer compile without swap, with the same graph count.torch.compileof the whole model now runs instead of failing to trace the stream ops. It breaks once around each swapped layer.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.from_pretrained(block_swap_layers = 8)"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.get_peft_model(block_swap_layers = 1)andfrom_pretrained(block_swap_layers = 1): loss, grad norms and generation bitwise equal to swap off.Not covered here: multi-GPU load-to-host (it keeps the previous behaviour) and gradient-checkpointing-off timing.
use_gradient_checkpointing = Falsefollowed byfor_training(model)fails with_gradient_checkpointing_funcmissing 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 atget_peft_modeltime. Turning it on automatically could therefore run out of memory mid-training.for_training,gradient_checkpointing_enableand the trainer turning checkpointing back on.Batch 1 x 1024, median step time, checkpointing on vs skipped:
"max""max""max""max"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.PCIe step time (Colab L4, PCIe Gen3 x16, merge
46597af1, zoo3a048a0c)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.block_swap_layers = 14"auto", squeezedblock_swap_layers = 12"auto", squeezed"auto", squeezedfrom_pretrained(block_swap_layers = "auto"), 8 GiB usable