Repository navigation
Fold 16-bit LoRA into the base weights for long generate calls - #16576
Conversation
…nerate Decode with one GEMM per projection instead of base + shrink + expand: when a generate call asks for at least UNSLOTH_LORA_FOLD_GENERATE_MIN_TOKENS (16) new tokens on a plain 16-bit LoRA model, the adapters are folded in place with unsloth_zoo's exact kernel, the PEFT layers are flagged merged, and the fold is undone bit for bit (checksummed) in a finally block. Refuses quantized bases, DoRA, lora bias, multiple adapters, tied weights, vLLM, FSDP / TP / PP / DTensor, multi-device maps and anything the exact kernel cannot check; UNSLOTH_LORA_FOLD_GENERATE=0 disables it.
…up store Fold + unfold costs 0.22 s on Llama-3.2-1B and 0.27 s on gemma-3-1b (Kaggle T4), so the fold pays off from about 37 new tokens in eager decode and about 57 with decode CUDA graphs, where the LoRA cost per token is smaller. The default UNSLOTH_LORA_FOLD_GENERATE_MIN_TOKENS is now 128 (still overridable). The fold stats also record the host RAM of the fix-up store (indices + original values, kept until the unfold) and whether it is pinned.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
[skip ci]
…e calls [skip ci]
[skip ci]
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
pre-commit.ci run |
…ghts on one device, refuse MoE, restore guards all post-fold bookkeeping, per-model poison, inputs= prompt length [skip ci]
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
pre-commit.ci run |
1 similar comment
|
pre-commit.ci run |
|
I cancelled the CI runs on this PR for now, since Codex hasn't converged at the current head yet: the latest push hasn't been reviewed by Codex yet. CI here runs on the team's shared runner pool, and it's backed up right now (380+ runs queued), so runs on code that's still changing push everyone else's back. Once Codex says "Didn't find any major issues" on the head commit, one push or a re-run brings CI back. A small ask going forward: hold the push until Codex is clean, and batch follow-up fixes into a single push. Thanks! |
…are on (L4: break-even 43-216 tokens under graphs vs 5-16 eager)
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…eeds little GPU memory while the KV cache is live [skip ci]
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…FOLD_GENERATE=1 (bf16 rounding of W + B @ A drifts further from fp32 than the unfolded path)
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…m, word counts, escapes) Newer unsloth_zoo keeps the fix-up store as a per-tile correction stream plus word counts and a short escape list; the stats and the restore chunks counted only the escape positions and values. Both now read the target's host_store_bytes() (every host buffer as a fallback). [skip ci]
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
A finite low-rank product can overflow when materialised: W + B @ A past fp16's 65504 made the folded layer return inf where the unfolded LoRA output is finite. After folding, every folded weight is checked finite (one reduction each, one host sync); otherwise the fold is undone before any forward and generate() takes the LoRA path (refusal fold_nonfinite).
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…4, tokens equal to eager) (unslothai#16587) ## Summary Decode CUDA graphs for every FastModel model, on by default in plain `model.generate()`. Gemma 3 / 4, Muse-Glimmer, Qwen3 and Qwen3-VL text, Llama, Mistral 3, Granite, Phi-4, OLMo 2, Cohere 2, GLM-4 and others now replay a captured one-token decode step instead of paying kernel launch overhead on every token. Until now only the Llama-path models (Llama, Qwen2, Qwen3 via `FastLanguageModel`, unslothai#16691) had this by default. Each one-token decode step of `unsloth_base_fast_generate` over a transformers `StaticCache` is captured once per graph key and replayed. The key covers batch size, argument structure / dtypes / strides / inference-ness, cache layout and autocast state. The captured step is exactly the eager one: static buffers keep each argument's inference-ness, dtype and strides, the caller's autocast cache setting is kept, and compiled regions run as compiled. ### When it runs * By default in plain `generate()`, RL rollouts and Studio, on NVIDIA CUDA (not native Windows), the same policy as unslothai#16691. * The graph and its `StaticCache` are kept across inference calls, so repeated and short calls replay without capturing again. They are released on `for_training`, on the first training forward, and when weights, adapters or quant state change (including an in-place LoRA fold, which bumps a weight epoch). * Calls too short to repay a capture run eagerly. An out-of-memory error in a graphed call releases the graphs and redoes the call eagerly once. * A model on a card other than `cuda:0` (accelerate's device hook) and a model split over several cards (Unsloth's balanced placement, for example Muse-Glimmer 4-bit on two T4s) are graphed: one graph per card, with the cross-card copies run eagerly between replays, so cards without peer access work. * An input embedding offloaded to the host (`offload_embedding=True`, as in the gpt-oss notebooks) is looked up eagerly outside the graph. * Placeholder-masked ids (Muse-Glimmer, Muse-Spark, Kimi-K2.5) are embedded outside the graph. ### Safety checks * The first replay of every key is compared bitwise with the eager step; a mismatch refuses that key, and refusals are cached so unsupported shapes never re-attempt capture. * A capture that syncs the host, or a step that changes cache host state beyond the length counters, refuses the key. * Recurrent / linear-attention / offloaded caches stay eager (for example LFM2's convolution layers). * Past a full sliding window (Gemma 3 / 4, gpt-oss) every step rolls the window; transformers builds that roll's index with a host-to-device copy, which a capture refuses, so the warm-up and recording run the same ops on an index made outside the capture. The one step that fills a window always runs eagerly. * Per-token type ids a trainer passes to `generate()` (TRL's GRPO forwards the processor's `mm_token_type_ids`) reach every decode step at full length; with the step's masks prebuilt (the only case where Gemma 3 / 4 skip reading them) the graphed step gets the step's columns, as transformers slices them. * A call whose graph key still changes every step stops capturing after four captures without a replay and decodes eagerly; an out-of-memory capture stops capturing for that call only. * Streamers, caller `past_key_values`, custom stopping criteria and logits processors stay eager. * A kept graph is dropped when any LoRA layer's scale changes (PEFT `set_scale` / `scale_layer` move a Python float, not a parameter); checked on a T4: after `set_scale(0)` the graphed tokens equal eager. * The hook that frees a kept graph when training resumes without `for_training()` does nothing while Dynamo traces, so a `torch.compile(fullgraph=True)` training forward after sampling compiles as before. * Capture keeps only the length counters (a recording runs no device work); the first-replay check undoes a full window's roll from the one slot it drops instead of copying every window. Knobs: `UNSLOTH_DECODE_CUDA_GRAPHS=0` (all decode graphs off), `UNSLOTH_DECODE_GENERIC_GRAPHS=0` (this path off), `UNSLOTH_DECODE_MULTIDEVICE_GRAPHS=0` (split models stay eager), `UNSLOTH_DECODE_GENERIC_GRAPH_MAX_BSZ` (default 16), `UNSLOTH_DECODE_GENERIC_GRAPHS_VALIDATE_ALL=1` (debug: compare every replay with eager). ## Results (Kaggle T4, torch 2.14.1, transformers 5.17) Default `generate()` call time, this PR vs main (main measured 0.95-1.05x vs its own eager on every row, i.e. no graphs). First call includes the capture; the kept call replays the graph kept from the first. Greedy tokens are identical to eager on every row. | Model | Weights | bsz 1 first / kept | bsz 8 first / kept | |---|---|---|---| | gemma-3-1b-it | 16-bit (fp32 on T4) | 3.19x / 4.11x | 3.28x / 3.94x | | gemma-3-1b-it | 4-bit | 3.81x / 5.04x | 2.77x / 3.17x | | Qwen3-0.6B (FastModel) | 16-bit | 4.60x / 6.59x | 4.14x / 5.39x | | Qwen3-0.6B (FastModel) | 4-bit | 5.34x / 8.22x | 3.45x / 4.51x | | Llama-3.2-1B-Instruct (FastModel) | 16-bit | 2.16x / 2.27x | 1.86x / 2.00x | | Llama-3.2-1B-Instruct (FastModel) | 4-bit | 2.66x / 3.21x | 1.65x / 1.67x | | gemma-4-E2B-it | 4-bit | 3.68x / 4.55x | 3.08x / 3.37x (bsz 4) | | gemma-4-E2B-it | 16-bit (fp32 on T4) | 2.86x / 3.40x | 2.94x / 3.34x (bsz 4) | Tiny copies of real configs (Gemma 3, Qwen3, Qwen3-VL, Llama, Gemma 4, Muse-Glimmer) get 1.4-3.9x on the first call and 2.4-6.4x kept, tokens equal. **Models on other cards (Kaggle T4 x2):** | Case | bsz | eager ms/token | graphed | speedup | |---|---|---|---|---| | gemma-3-1b-it 4-bit on cuda:1 | 1 / 4 | 96.5 / 98.0 | 13.1 / 17.1 | 7.3x / 5.7x | | gemma-4-E2B-it 4-bit on cuda:1 | 1 / 4 | 164.2 / 165.0 | 25.7 / 34.7 | 6.4x / 4.8x | | gemma-3-4b-it 4-bit split over both T4s | 1 / 4 | 123.2 / 126.1 | 28.8 / 44.6 | 4.3x / 2.8x | | Muse-Glimmer-30B 4-bit, Unsloth's default split | 1 / 2 | 242.2 / 252.9 | 141.2 / 224.2 | 1.72x / 1.13x | | gemma-3-1b-it 16-bit split over both T4s | 1 / 4 | 83.4 / 84.1 | 16.0 / 16.3 | 5.2x / 5.2x | | Qwen3-0.6B 16-bit split over both T4s | 1 / 4 | 90.2 / 92.1 | 11.9 / 12.4 | 7.6x / 7.4x | | Qwen3-30B-A3B 4-bit split over both T4s (with unslothai/unsloth-zoo#2442) | 1 / 4 | 178.8 / 183.2 | 47.8 / 81.2 | 3.74x / 2.26x | Tokens equal on every row (teacher-forced KL 0 on Qwen3-30B-A3B), nothing allocated on `cuda:0` for the `cuda:1` rows, and `UNSLOTH_DECODE_MULTIDEVICE_GRAPHS=0` refuses the split rows. A flex attention decode mask (gpt-oss with unslothai/unsloth-zoo#2463) crosses cards with the tensors its `mask_mod` reads: `BlockMask.to` alone left them on `cuda:0`, so gpt-oss-20b 4-bit split over both T4s raised a device mismatch in the warm-up step. With the fix: 1 capture / 93 replays at bsz 1 and 2, 48 of 48 greedy tokens equal to graphed SDPA. **GRPO (Kaggle T4 x2, DDP 2 ranks, gemma-3-1b-it, 3 steps):** graphs engaged on both ranks (45 / 42 graph steps), loss and grad_norm bit-identical to main at every step. **Earlier rows (L4 / A100, opt-in policy at the time, same capture path):** Qwen3-0.6B NF4 LoRA 10.2x / 8.2x (A100, bsz 1 / 8), gemma-3-1b NF4 8.9x / 7.4x, Llama-3.2-1B 16-bit LoRA folded (unslothai#16576) 4.6x / 4.4x; L4 Qwen3-0.6B NF4 LoRA 10.3x / 8.1x. GRPO gemma-3-1b single T4: 1647 -> 918 ms per step, loss and grad_norm bit-identical. **Notebooks (Kaggle T4, the unchanged notebooks with this PR installed):** | Notebook | main | this PR | |---|---|---| | Gemma4_(E2B)_GRPO, 3 steps (16-bit LoRA, 2 generations up to ~3.9k tokens) | 342.1 s | 205.8 s (1.66x) | | Kaggle-gpt-oss-(20B)-GRPO, 3 steps (own kernel each) | 490.6 s | 450.6 s (1.09x) | | Kaggle-Muse_Glimmer_(30B)-GRPO, 3 steps (split over both T4s) | 1096.9 s | 765.7 s (1.43x), identical training loss | | Gemma4_(E2B)-Text, training | 41.0 / 40.7 s | 40.5 / 40.2 s, peak 10.818 vs 10.840 GB | | Kaggle-gpt-oss-(20B)-Fine-tuning, training | 211.1 s | 211.8 s, peak 7.346 vs 7.367 GB | The Gemma 4 rows pair main and this PR in one kernel, one T4 each. In the GRPO run this PR's third rollout happened to sample 1090 tokens (627 in the other runs) and it was still faster; each rollout `generate()` took 68 / 28 / 58 s against 179 / 91 s eager for the first two (7 captures, 2765 replays, no eager steps). The Muse row is from an earlier head of this PR. **Accuracy.** Greedy tokens equal eager on every row above; teacher-forced KL between graph and eager logits is 0 on the dense models; KL to an fp32 reference equals eager's. **Memory.** The graph pool adds 8-16 MiB peak on these models; the KV cache is the one generate already allocates. ## gpt-oss and MoE With unslothai/unsloth-zoo#2442 (dense one-token gpt-oss decode attention and routed MoE kernels inside graph-planned decode), gpt-oss and Qwen3-MoE also graph: * tiny gpt-oss 2.1x / 2.4x / 2.4x (bsz 1 / 4 / 16), tiny Qwen3-MoE 4.1x / 4.4x / 4.5x; teacher-forced KL graph vs eager 1e-6 (fp16 rounding); * gpt-oss-20b 4-bit on T4 (notebook load, `offload_embedding=True`): the new dense decode is 1.45-1.63x faster per token than the current flex decode at bsz 1 (1024 context: 102.1 -> 70.2 ms), ties at bsz 2 / 4, with KL to eager attention equal to the current path's. GRPO rollouts at 2 generations per prompt do not get faster (62.5 s graphed vs 61.7 s with the kill switch), as the MoE experts dominate there. Without that zoo change these models stay eager, unchanged. ## Testing * CPU: generic, default-on and multi-device suites plus the existing decode graph suites: 137 passed, 40 skipped (CUDA only). * GPU: every table above on Kaggle T4 / T4 x2 and Colab L4 / A100. Not covered: H100 / B200 timing; native Windows and ROCm (off by default there); a real Qwen3-MoE on a single T4 (the smallest does not fit one card; covered split over two).
Inside generate_scope() decode graphs are allowed for every call, so enabled() is True even when FastModel's generate() decodes this call eagerly (ineligible model, short call, dynamic cache). The fold then waited for 512 new tokens instead of 128. Read _decode_graphs.call_plan() first and fall back to enabled() only outside Unsloth's generate(). [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c34a310cf7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # Chunked: the KV cache is still live, so only one chunk's fix-up store is on the GPU at a time. | ||
| for chunk in _restore_chunks(targets): | ||
| api.exact_unfold(chunk, stream = stream) |
There was a problem hiding this comment.
Split fix-up stores before folding to bound restore memory
For long generations that leave less free VRAM than the full fix-up store, this chunking does not prevent an OOM during restoration. The Zoo implementation of exact_fold(targets, ...) creates one shared store per device; exact_unfold(chunk, ...) uploads that store's entire host buffer and retains its device allocation until every target sharing it is restored. Since all targets are folded together here, the first supposedly 64 MiB restore chunk still uploads the whole model's store while the KV cache is live. An otherwise successful generation can therefore fail at exit and poison the model, requiring a reload. Create independently bounded stores during folding, or use an API that uploads only the selected targets' store slices; the reference-API test currently checks call partitioning rather than actual upload size.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 417d9cf: the fold now runs in groups of at most 256 MiB of weights, each its own store, and the restore unfolds those same groups one at a time. The test checks that each exact_unfold call gets exactly one exact_fold call's targets.
…oads one bounded store exact_fold keeps one fix-up store per call and device and exact_unfold uploads a store whole, so the 64 MiB restore chunks still uploaded every target's store on the first chunk while the KV cache was live. Fold in groups of at most 256 MiB of weights and unfold the same groups. [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Summary
Speeds up
generateon 16-bit + LoRA models by folding the LoRA weights into the base weights for the duration of the call, then restoring the base weights bitwise afterwards.Every decode step currently runs the base matmul plus the LoRA A / B matmuls for every adapted projection. For long generations, a one-time fold
W + scale * B @ Amakes each step a single matmul.The fold uses unsloth-zoo's exact fold / unfold (
merged_rollout_exact). The rounding fix-up for each element is stored on the host (pinned). The original weights are restored bit for bit when generate returns, including on an exception.When it engages
max_new_tokens >= 128when the call decodes eagerly, or>= 512when the call decodes through CUDA graphs (now the default for plaingenerate()on NVIDIA Linux). The threshold follows the plan Unsloth'sgenerate()picked for this call (_decode_graphs.call_plan()), so a FastModel call that decodes eagerly (ineligible model, short call, dynamic cache) uses the eager threshold;nn.Linearbase weights on one CUDA device. bf16 bases fold only withUNSLOTH_LORA_FOLD_GENERATE=1(see Accuracy). 4-bit / 8-bit / fp8 / torchao bases are refused and run the normal path;It also refuses QAT / fake-quantized layers, custom
nn.Linearsubclasses, adapters with a bias or on another device, MoE models, mixed-adapter calls (adapter_names, PEFT's per-example hooks) and folds whose weights would not be finite in fp16 (fold_nonfinite, undone before any forward).Anything else runs the normal LoRA path unchanged. Other threads generating on the same model wait while the weights are folded. A failed restore makes that model's later generate calls raise instead of running on unknown weights. A nested generate call does not fold twice.
UNSLOTH_LORA_FOLD_GENERATE=0disables it.UNSLOTH_LORA_FOLD_GENERATE_MIN_TOKENSsets the threshold.Hooks live in
llama.py(FastLanguageModel) andvision.py(FastModel) generate wrappers. The new module isunsloth/models/_lora_fold_generate.py.Changes in this round
main(0945ac0, 622 commits). No conflicts. Main now runs decode CUDA graphs by default in plaingenerate()for every FastModel model, keeps the graph and its StaticCache across calls, and exposes the per-call decode plan._decode_graphs.enabled(), which is True for every call insidegenerate()now that graphs are on by default, so a FastModel call that decodes eagerly waited for 512 new tokens instead of 128. New testtest_threshold_follows_the_call_planfails on the previous head (assert 512 == 128) and passes here.Results on current main
ms per generated token, 640 new tokens, bsz 1, LoRA r16 on all projections (nonzero B), greedy, fp16. Median of 3 rounds interleaved with main in the same session (round order alternated); the range is min-max over the rounds, so main's range is the A/A spread. "Default" = what plain
generate()does on main now (decode CUDA graphs on); "eager" =UNSLOTH_DECODE_CUDA_GRAPHS=0.Kaggle T4, fp16 (Llama and Qwen3 rows torch 2.11, gemma rows torch 2.14.1):
With
UNSLOTH_LORA_FOLD_GENERATE=0this branch matches main: identical tokens on every row, and times within main's range (Llama 14.18 / 27.08, Qwen3 10.55 / 45.11, gemma 17.86 / 86.33). The fold engaged on every folded call and restored after each (engagement counter 3 of 3, kill-switch rows 0).Colab L4, torch 2.14.1 (fp16 unless noted):
bf16)UNSLOTH_LORA_FOLD_GENERATE=1UNSLOTH_LORA_FOLD_GENERATE=1With the kill switch the L4 rows match main as well (identical tokens; Llama 12.26 / 27.74, Qwen3 8.75 / 46.61, gemma 14.10 / 87.32).
So on current main, where plain
generate()decodes through CUDA graphs by default, the fold adds 1.04-1.16x on these 0.6-1B models (Qwen3-0.6B on L4 is a tie); with graphs off it is 1.41-1.49x, as before.Folding is not bitwise equal to the unfolded LoRA forward (a different rounding order), so long greedy runs can diverge late: in fp16, Llama-3.2-1B first differs at token 199 (T4) / 342 (L4) of 640 and gemma-3-1b at 205 on L4; Qwen3-0.6B matches through all 640 tokens. Peak memory is up to 0.1 GB higher during a folded call (the fold's working buffers).
Accuracy (from the earlier rounds, unchanged code): teacher-forced KL against an fp32 reference of the same LoRA model is at or below the unfolded path's in fp16 (Llama-3.2-1B 3.8e-6 vs 5.2e-6, gemma-3-1b 1.35e-5 vs 1.25e-5, top-1 agreement 0.996 - 1.0 in both arms). bf16 adds rounding the unfolded path does not have (A100 mean KL 3.8e-4 vs 2.8e-4 on Llama-3.2-1B), so bf16 folds only with
UNSLOTH_LORA_FOLD_GENERATE=1.Weights: bitwise equal to the originals after every call; the host fix-up store (about 270 MB for Llama-3.2-1B) is held only during the call.
Testing
tests/test_lora_fold_generate.py: 47 passed on CPU (fold / unfold bit-exactness, restore on exception and on a fold failing part way, checksum mismatch, thresholds incl. the per-call plan, nesting, kill switch, every refusal leaving the model untouched, training after generate bitwise unchanged, every generate entry point wrapped), 64 passed together withtest_dia_generate_pad_token.pyandtest_fa2_fast_generate_bypass.py.test_generic_decode_graphs{,_default}.py,test_decode_cuda_graphs{,_default}.py): 66 passed, 36 skipped (GPU only) on CPU.Not covered