Skip to content

Decode CUDA graphs on by default for every FastModel model (2-8x on T4, tokens equal to eager) - #16587

Merged
danielhanchen merged 48 commits into
mainfrom
dec-generic-graphs
Nov 10, 2026
Merged

danielhanchen merged 48 commits into
mainfrom
dec-generic-graphs

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

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, #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 Decode with CUDA graphs by default in plain generate(), with memory release and an eager fallback #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 (#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).

Each one-token decode step of unsloth_base_fast_generate replays a CUDA graph of the
model's eager forward when decode graphs are enabled (RL rollouts, Studio,
UNSLOTH_DECODE_CUDA_GRAPHS=1) on NVIDIA CUDA. Static attention layers only (sliding
layers until their window fills); recurrent, offloaded and dynamic caches stay eager.
A capture that syncs the host or a first replay that differs from the eager step
refuses the key. UNSLOTH_DECODE_GENERIC_GRAPHS=0 turns it off.
…cord capture errors; VALIDATE_ALL debug mode
…/ strides of static buffers, ambient autocast cache
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T07:37:09.288893Z 6c1cb1b Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen danielhanchen self-assigned this Nov 3, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: c3f7ca8830

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

…r-key decisions, prefill never graphed, setup failures run eagerly, validation leaves the eager step's cache rows

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 4820c1d455

ℹ️ 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".

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

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!

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: d50c96c79b

ℹ️ 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".

…ps the model's own forward (mixed-precision autocast) or GRPO wraps it; device hooks stay eager
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 4, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 01a62b8c98

ℹ️ 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".

…f compiled training

A LoRA layer's scale is a Python float the captured kernels baked in, and PEFT's set_scale /
scale_layer change it without touching a parameter, so a kept graph replayed the old scale.
The fingerprint now includes every LoRA layer's scaling.

The pre-hook that frees a kept graph when training resumes removed its own handle while
Dynamo traced a compiled training forward: a graph break, and an error under fullgraph. It
now does nothing while compiling; the next eager training forward, for_training() or the next
generate() fingerprint check still release it.

Tests: the CPU capture stand-in puts back every cache row (it runs the step, a real capture
does not), and the helper disables transformers' static-cache auto-compile so the GPU tests
exercise the graph path.

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 3334a58d8d

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 9, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: ebe3496176

ℹ️ 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".

danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Nov 9, 2026
… sm80 inside graph-planned generate (#2442)

## Summary

Lets Unsloth's decode CUDA graphs (unslothai/unsloth#16587) capture
gpt-oss and the routed MoE models. Outside graph-planned decode every
dispatch decision is unchanged.

* **`unsloth_zoo/decode_graph_state.py`:** two scopes Unsloth enters,
`graph_generate()` for a generate call that plans to graph and
`graph_decode_step()` for each one-token step (warm-up, capture and
every eager step alike), so kernels are chosen the same way for the
eager step and the replay.
* **gpt-oss:** inside those scopes a one-token step builds a dense mask
of fixed shape (sliding offsets are values, not shapes) and runs a
grouped attention with the attention sinks at the eager rounding points.
Today's flex decode passes a `BlockMask` whose closure tensors cannot be
graph inputs, and its sliding windows fill, so every gpt-oss step stayed
eager. `UNSLOTH_GPT_OSS_GRAPH_DECODE_ATTENTION=flex` keeps flex decoding
and publishes the `BlockMask` closure tensors for refill instead. The
dense attention reads shared `[B, 1, 1, L]` and per-head `[B, H, 1, L]`
masks (any number of KV heads) and runs its value matmul outside
autocast, as the eager path's `out=` matmul does. In flex mode the
`BlockMask` also carries the mask function's identity (bytecode digest,
captured scalars, scalar globals it reads), which the graph key
includes; a mask function holding anything else (a dict, a tensor, a
partial, an object) publishes no contract and stays eager.
* **Graphed flex decode
(`UNSLOTH_GPT_OSS_GRAPH_DECODE_ATTENTION=flex|auto|dense`):** the
padding mask is now one column per physical KV slot (`[B, kv_length]`),
so a rolling sliding window keeps the same shapes and the graph key
stops changing every step (before, flex mode captured a new graph each
step and never replayed). `auto` uses flex where the mask publishes a
graph contract and the dense mask otherwise. **Default:** `auto` on
compute capability 8.0 and newer, `dense` on older GPUs (T4), where
graphed flex was slower at batch 4 and 8. The env var still overrides.
* **transformers 4.57:** its `generate` passes a CPU `torch.empty`
placeholder as `input_embeds`, which turned the flex mask off on 4.57
(eager attention ran instead). The mask device now comes from
`cache_position`, `position_ids`, the 2D mask or the cache.
* **Zoo's fused static cache update** is verified through the update
Unsloth's graphable roll wraps, instead of caching a refusal when the
first check happens during warm-up.
* **Routed MoE below sm80:** `torch._grouped_mm` copies its offsets to
the host, which cannot be captured, so Qwen3-MoE at batch 4 and up never
graphed on T4. Inside the scopes the routed kernels serve every decode
row up to `UNSLOTH_MOE_ROUTED_GRAPH_MAX_SLOTS` (default 128).

## Results (Kaggle T4, torch 2.14.1, transformers 5.17, with
unslothai/unsloth#16587)

| Model | bsz 1 | bsz 4 | bsz 16 |
|---|---|---|---|
| tiny gpt-oss, graphed vs eager | 2.08x | 2.38x | 2.41x |
| tiny Qwen3-MoE, graphed vs eager | 4.14x | 4.41x | 4.54x |

Without this change both stay eager (0.89-1.02x).

**Real Qwen3-30B-A3B 4-bit** (`unsloth/Qwen3-30B-A3B-bnb-4bit`, split
over Kaggle's two T4s): 178.8 -> 47.8 ms per token at bsz 1 (3.74x),
183.2 -> 81.2 at bsz 4 (2.26x); the routed kernels run in every graph
step, tokens are identical to eager and teacher-forced KL is 0. On main
the same run stays eager (1.00x). Teacher-forced KL between graphed and
eager logits is at most 1e-6 (fp16 rounding); greedy tokens differ at
bsz 4 / 16 on near-ties of the random tiny weights.

**gpt-oss-20b, 4-bit, notebook load (`offload_embedding=True`), ms per
token:**

| Context, bsz | eager attention | current flex decode | dense decode,
graphed |
|---|---|---|---|
| 116, 1 | 102.1 | 121.8 | 74.8 (1.63x) |
| 1024, 1 | 99.8 | 102.1 | 70.2 (1.45x) |
| 1024, 2 | 125.5 | 116.1 | 114.9 |
| 1024, 4 | 221.0 | 199.1 | 200.6 |

KL to the eager attention is the same as the current flex decode's (bsz
1: 3.8e-4 vs 4.0e-4; bsz 4: 0.019 vs 0.022), top-1 agreement 97.7-100%.
At 2+ rows the MoE experts dominate, so GRPO rollouts with 2 generations
per prompt are not faster (62.5 s graphed vs 61.7 s with graphs off);
with graphs off, completions are identical to main.

**gpt-oss-20b graphed flex, Colab A100 40GB, bf16, torch 2.14.1,
transformers 5.17, ms per token (lower is better):**

| Context, bsz | eager attention | flex, no graphs | dense, graphed |
flex, graphed (this PR) | flex, graphed (before) |
|---|---|---|---|---|---|
| 1024, 1 | 43.3 | 44.8 | 13.2 | 12.6 | 48.8 |
| 1024, 8 | 60.5 | 55.2 | 46.6 | 45.9 | 60.2 |
| 4096, 1 | 59.4 | 46.3 | 16.4 | 14.8 | 51.4 |
| 4096, 4 | 114.7 | 57.6 | 39.9 | 37.7 | 60.6 |
| 16384, 1 | | 58.9 | 33.9 | 27.5 | 62.0 |
| 16384, 4 | | 104.5 | 96.1 | 86.1 | 107.3 |

Every graphed cell now captures once and replays (377 replays); before
the padding fix flex mode captured 24 graphs and replayed none. KL to
eager attention in bf16 is the same for the dense and flex paths and the
same as before this change. On a T4 (fp16) graphed flex is slower than
graphed dense at 1024 context with batch 4 / 8 (252 vs 211, 420 vs 372
ms), hence the dense default there.

**transformers 4.57.6, Kaggle T4:** with flex back on, gpt-oss-20b goes
from 104.1 to 90.9 ms per token at 1024 context (batch 1), 335 to 266
(batch 4) and 318 to 186 at 4096 context; KL to eager 6e-4 to 1.3e-3,
top-1 agreement 97-100%.

## Tests

`tests/test_decode_graph_dispatch.py`: scope nesting, per-thread scopes
and exit on exception; the bf16 / NF4 routed gates with and without the
graph scope (unchanged outside it); dense decode selection; the dense
one-token attention against the eager sink attention over dtypes, batch
sizes, GQA and cache lengths, including a cache longer than the mask;
the flex fallback rebuilding the same mask, refusing unknown closures,
and giving different identities to different windows, same-line lambdas
and changed globals; one-KV-head per-head masks; dtype under autocast.
Also: the fixed-shape padding over a rolling window, the mask device
past the 4.57 placeholder, the static update check after a graphable
roll, a refill across several 128-token blocks, and the default per
compute capability. The gpt-oss, flex mask and routed MoE suites give
239 passed on CPU; the 1 failure and 12 errors there fail identically on
the base commit.

Not covered: sm80+ uses the existing Triton grouped GEMM path and is
unchanged.
… it to another card of a split model

[skip ci]
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 8fb6d45ed2

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: e4b2f6ac29

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: dd5b89d5f1

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 6c1cb1b132

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 00d1056 into main Nov 10, 2026
@danielhanchen
danielhanchen deleted the dec-generic-graphs branch November 10, 2026 08:45
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Nov 10, 2026
…es (unslothai#17324)

## Summary

Stacked on unslothai#16587 (generic decode CUDA graphs). Qwen3.5 and Qwen3.6
(`qwen3_5`, `qwen3_5_moe`) mix Gated DeltaNet layers with full
attention. On transformers 5.x their StaticCache holds a
`LinearAttentionLayer` per Gated DeltaNet layer, and unslothai#16587 refused
every decode step of those models ("layer LinearAttentionLayer"), so
they always decoded eagerly. This PR makes the generic decode graphs
replay them.

* **Linear-attention layers are graphable once prefill has set their
states.** Their conv and recurrent states have fixed shapes and are
updated in place by every one-token step, so a replay addresses them
like KV rows. A layer still recording its past (speculative decoding
grows conv states) or not yet initialised stays eager with its own
refusal reason.
* **Graph key and cache signature** include the conv / recurrent state
shapes, dtypes and addresses, so a new cache re-captures and a moved one
stays eager, as for KV rows.
* **Snapshot / restore** (the validation replay and the eager step after
a refused capture) put the conv and recurrent states back, so a step is
never applied twice.
* Batch size and cache length are read from the attention layers (a
linear layer has no KV rows).

No `vision.py` change was needed: transformers 5.17 / 5.22 already set
`_can_compile_fullgraph` for these models, so generate uses a static
cache.

## Results

torch 2.14.1, transformers 5.17.0, greedy, 128 new tokens, ms/token
eager vs graphed (this PR). Every graphed row: 1 capture, 126 replays, 0
refusals, 0 recompiles, tokens identical to eager, KL 0, final linear
states bitwise equal to eager. unslothai#16587 alone refuses every step and runs
at eager speed.

| GPU | Model | ctx x bsz | eager | graphs | speedup |
|---|---|---|---|---|---|
| A100 40GB | Qwen3.6-35B-A3B 4-bit | 1024 x 1 | 106.1 | 15.6 | 6.78x |
| A100 40GB | Qwen3.6-35B-A3B 4-bit | 1024 x 4 | 109.3 | 23.8 | 4.59x |
| A100 40GB | Qwen3.6-35B-A3B 4-bit | 1024 x 8 | 110.4 | 32.7 | 3.37x |
| A100 40GB | Qwen3.6-35B-A3B 4-bit | 4096 x 1 | 108.1 | 18.7 | 5.78x |
| A100 40GB | Qwen3.6-35B-A3B 4-bit | 4096 x 8 | 109.8 | 42.6 | 2.58x |
| A100 40GB | Qwen3.5-4B 16-bit | 1024 x 1 | 58.6 | 14.6 | 4.01x |
| A100 40GB | Qwen3.5-4B 16-bit | 4096 x 8 | 62.7 | 27.3 | 2.30x |
| T4 | Qwen3.5-4B 4-bit | 1024 x 1 | 85.2 | 34.8 | 2.45x |
| T4 | Qwen3.5-4B 4-bit | 1024 x 4 | 87.4 | 68.1 | 1.28x |
| T4 | Qwen3.5-4B 4-bit | 4096 x 1 | 84.3 | 44.1 | 1.91x |
| T4 | Qwen3.5-4B 16-bit | 1024 x 1 | 63.5 | 48.1 | 1.32x |

Peak memory with graphs: equal to eager or 0.2 to 2.8 GB higher (the
graph pool). The Qwen3.6 MoE decode step captures with the routed MoE
kernels of unsloth-zoo main (unslothai#2442); with an older zoo the grouped MoE
path copies to the host during capture, the capture is refused and the
step runs eagerly (tokens still equal).

## Tests

`tests/test_generic_decode_graphs_hybrid.py` (new): tiny dense (GQA 4:1)
and MoE (8:1) models with the real Qwen3.5 layer pattern, 200 steps at
bsz 1 and a ragged left-padded bsz 4: tokens equal to eager and every
conv / recurrent state bitwise equal after every step (1 capture, 1
validation, 198 replays), states restored after a validation, refusals
for an uninitialised or recording layer; plus a real CUDA capture test.
On the host stand-in 6 of them fail on unslothai#16587 alone. With the existing
generic decode graph suites: 76 passed / 4 skipped on transformers
5.22.1, 68 passed / 3 skipped on 4.57.6 (no hybrid cache there).

Not covered: Qwen3.6-35B-A3B in 16-bit (72 GB) did not fit any GPU
available for this run.
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Nov 10, 2026
## Summary

Adds a growable KV cache to the generic FastModel decode path (the CUDA
graph path from unslothai#16587). On by default where that path runs;
`UNSLOTH_GROWABLE_KV=0` keeps transformers' full-length `StaticCache`.
Models whose mask or ALiBi is sized by the cache's full limit
(`get_max_cache_shape()` / `get_max_length()`, e.g. BLOOM) keep
`StaticCache`.

A transformers `StaticCache` allocates prompt + `max_new_tokens` slots
for every full-attention layer at prefill, and attention reads every
slot each step however early the reply stops. Under decode graphs the
kept cache also stays at the largest size a previous call asked for, so
a short call after a long one pays for the long one.

* **`unsloth/models/_kv_cache.py` (new):** `GrowableLayer` is a
transformers `StaticLayer` whose full-attention layers allocate a
power-of-two bucket (at least `UNSLOTH_GROWABLE_KV_MIN`, default 256,
never above the limit `generate` sized for) and double when a step would
pass it. Writes are transformers' own `update` (`index_copy_` at device
positions), buffers are `mark_static_address`, and the mask reads the
bucket length, so within a bucket every tensor keeps its shape and
address. Sliding and chunked layers stay transformers' own.
* **Growth happens outside the graph:** `generate`'s
`prepare_inputs_for_generation` re-syncs the host counter from
generate's own lengths and reserves the next bucket eagerly, before the
step's mask is built. No growth can happen inside a capture (frozen
during recording and while a CUDA stream is capturing), and a step that
would fill its bucket with no graph yet runs eagerly.
* **Hybrid models (unslothai#17324):** linear-attention layers keep their own
states; the graph key and cache signature carry both their shapes and
the growable buckets.
* **Memory:** layers hold their growth group by weak reference (no
cycle), so a released cache frees its KV at once; a layer built directly
joins its group.
* **Decode graphs:** the graph key uses the bucket and the cache
signature carries a growth epoch, so a growth re-captures once per
bucket instead of being refused as "cache moved"; the previous bucket's
graph is dropped.
* **Kept cache:** reused across calls when its capacity is at most
max(2x the new call's need, that call's own minimum bucket), so repeated
short calls do not re-capture; its limit is raised to the new call's
(5.x `_prepare_static_cache` hook, 4.57 `_get_cache` wrapper).

## Results

Kaggle T4, fp16, decode graphs on, greedy, `max_new_tokens` 512 / 3800
with replies that stop at the chat EOS, tokens equal to `StaticCache` on
every row, 0 recompiles, 0 refusals:

| torch / transformers | Model, bsz | Tokens of budget | StaticCache
ms/token | Growable ms/token | KV MiB static / growable |
|---|---|---|---|---|---|
| 2.14.1 / 5.17.0 | Qwen3-0.6B, 4 (after a 3800 call) | 512 of 512 |
51.8 | 21.2 | 1673 / 448 |
| 2.14.1 / 5.17.0 | Qwen3-0.6B, 4 | 1139 of 3800 | 52.1 | 32.4 | 1673 /
896 |
| 2.14.1 / 5.17.0 | Llama-3.2-1B, 4 | 189 of 3800 | 44.4 | 16.1 | 481 /
32 |
| 2.14.1 / 5.17.0 | gemma-3-1b, 4 | 180 of 3800 | 18.3 | 15.8 | 208 / 96
|
| 2.10.0 / 4.57.6 | Llama-3.2-1B, 4 | 181 of 3800 | 44.2 | 16.1 | 481 /
32 |
| 2.10.0 / 4.57.6 | gemma-3-1b, 4 | 180 of 3800 | 27.6 | 22.8 | 208 / 96
|

Colab L4 (bf16): Qwen3-0.6B bsz 1, 845 of 3800 tokens: 16.1 vs 9.0
ms/token, KV 418 vs 112 MiB; 4-bit, 737 tokens: 13.8 vs 6.9. A call that
runs to its full budget ends in the same final bucket as the limit, so
it costs the same as `StaticCache` (Qwen3-0.6B bsz 4, 3800 of 3800: 56.1
vs 56.1).

Default-on check (Kaggle T4, torch 2.14.1, transformers 5.17.0, graphs
on, 2 repeats; tokens equal on every row): never slower beyond noise,
e.g. Qwen3-0.6B bsz 4 early stop 33.8 -> 21.2 ms/token (KV 906 -> 448
MiB), Llama-3.2-1B bsz 4 36.4 -> 22.2 (KV 262 -> 32 MiB), Qwen3-0.6B bsz
1 full 2048 budget 17.1 -> 16.5. A short call after a long one adds 0
captures. Cost: about 20 to 190 MiB more reserved (one graph pool per
bucket) and one capture plus one compiled mask builder per bucket. Split
over 2 x T4 and on L4 with flex decode, growable vs static is at parity.
AMD gfx1151 (ROCm): the growable and generic decode graph suites pass
(90 / 90).

## Tests

`tests/test_growable_kv_cache.py` (12 tests, CPU host stand-in): tokens
equal to `StaticCache` for llama, a left-padded batch of 2 and gemma3
with sliding + full layers; captures per bucket with no refusals; a
short call after a long one replays the kept graph; early EOS allocates
one bucket; rows equal across bucket growths; the compiled update is
fullgraph with one graph per bucket; no growth inside a capture; a stale
host counter (updates that skip it, as a compiled update or a replay
would) and a prepare hook already owned by another wrapper still grow
correctly. They pass on transformers 4.57.6 and 5.22.1, and on GPU with
torch 2.14.1 / transformers 5.17.0 and torch 2.10.0 / transformers
4.57.6. With the flag off the existing decode-graph suites give the same
results before and after.

Not covered: the Llama-path KV buffers (`_decode_graphs.py`) and the
per-model copies are unchanged; the attention still reads up to 2x the
written length inside a bucket.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 11, 2026
…ecode CUDA graphs (unslothai#17329)

## Summary

Builds on the generic decode CUDA graphs (unslothai#16587). Decodes the one-token
steps of `FastModel.generate()` on flex attention (`flex_decoding`) for
Gemma 4 (`gemma4`) and Qwen3.5 / Qwen3.6 (`qwen3_5`, `qwen3_5_moe`). It
uses the shared decode mask and attention from unsloth-zoo
(unslothai/unsloth-zoo#2464); with an older unsloth-zoo nothing changes.

* **Routing (`unsloth/models/_flex_decode.py`, `vision.py`):** prefill
keeps its attention. During one-token steps over a StaticCache, the text
attention configs switch to an attention + mask interface pair,
`"unsloth_flex_decode_routed"`.
* **Mask side:** per layer type (full / sliding), it builds zoo's decode
BlockMask from transformers' own mask function (graph-refillable: fixed
shapes, offsets and padding as tensors) when every layer of that type
has a shape flex decode supports. Otherwise it builds transformers' SDPA
mask.
* **Attention side:** runs flex decode on a BlockMask and SDPA on a
dense mask, so a model can mix both (Gemma 4's head_dim 512 full layers
below sm80 stay on SDPA).
* A shape zoo reports it cannot compile (`FlexDecodeUnavailable`) is
counted and served by SDPA over the same visibility.
* Prefill, dynamic caches, custom mask functions, chunked layers and
gpt-oss (zoo owns it) are untouched.
* **Policy, `UNSLOTH_FLEX_DECODE`:**
* `auto` (default) routes only on compute capability 8.0+, only for the
model types above, only in a `generate()` call that decodes through CUDA
graphs (eager flex decode is 6 to 10% slower than eager SDPA), and only
at batch size up to `UNSLOTH_FLEX_DECODE_MAX_BATCH` (default 4; head_dim
512 at batch 8 was slower on an A100).
  * `1` forces it on, `0` turns it off.
* **Stats:** per layer, how many steps ran on flex and which ones fell
back and why (`_flex_decode.stats(model)`).

## Results

torch 2.14.1, transformers 5.17.0, greedy, 64 new tokens. ms/token with
decode CUDA graphs, SDPA vs flex (this PR). Every row: 1 capture, 377
replays, 0 recompiles. KL is teacher-forced against eager SDPA on the
eager greedy sequence.

| GPU | Model | ctx x bsz | graphed SDPA | graphed flex | speedup | KL
max |
|---|---|---|---|---|---|---|
| L4 | gemma-4-E2B 4-bit | 1k x 1 | 17.94 | 16.89 | 1.06x | 1.3e-2 |
| L4 | gemma-4-E2B 4-bit | 4k x 1 | 25.52 | 22.57 | 1.13x | 4.4e-3 |
| L4 | gemma-4-E2B 4-bit | 4k x 4 | 53.24 | 50.60 | 1.05x | 1.7e-2 |
| L4 | gemma-4-E2B 16-bit | 4k x 1 | 32.83 | 29.78 | 1.10x | 2.3e-3 |
| L4 | gemma-4-E2B 16-bit | 4k x 4 | 57.66 | 55.24 | 1.04x | 7.9e-3 |
| L4 | Qwen3.5-4B 4-bit | 1k x 4 | 45.21 | 40.97 | 1.10x | 5.9e-3 |
| L4 | Qwen3.5-4B 4-bit | 4k x 1 | 37.10 | 32.53 | 1.14x | 5.5e-4 |
| L4 | Qwen3.5-4B 16-bit | 4k x 4 | 111.45 | 92.49 | 1.20x | 9.2e-3 |
| A100 40GB | Qwen3.6-35B-A3B 4-bit | 1k x 1 | 18.28 | 17.50 | 1.04x |
4.6e-2 |
| A100 40GB | Qwen3.6-35B-A3B 4-bit | 4k x 1 | 21.94 | 18.03 | 1.22x |
4.4e-1 |
| A100 40GB | Qwen3.6-35B-A3B 4-bit | 4k x 4 | 38.88 | 31.88 | 1.22x |
1.9 |
| A100 40GB | gemma-4-26B-A4B 4-bit | 1k x 1 | 18.70 | 16.13 | 1.16x |
9.5e-2 |
| A100 40GB | gemma-4-26B-A4B 4-bit | 4k x 1 | 22.93 | 18.36 | 1.25x |
2.2e-2 |
| A100 40GB | gemma-4-26B-A4B 4-bit | 4k x 4 | 52.34 | 44.37 | 1.18x |
1.1 |

Ragged left-padded batches give the same speedups (for example E2B 4-bit
4k x 4 ragged: 63.0 vs 60.3).

**The large KL on the MoE models is the router amplifying rounding, not
flex.** On Qwen3.6's 4k x 4 cell (a separate run), eager decode on
SDPA's other kernels differs from the default flash kernel more than
flex does:

| Kernel | KL max | KL mean | top-1 |
|---|---|---|---|
| SDPA math | 8.2 | 0.046 | 0.981 |
| SDPA efficient | 4.5 | 0.032 | 0.981 |
| flex | 1.2 | 0.014 | 0.965 |

gemma-4-26B-A4B shows the same pattern: on its cells, the SDPA math
kernel reaches KL max 11 and the efficient kernel 2 to 4.5, against flex
0.25 to 9.5 (top-1 0.97 to 0.99 for flex).

**What `auto` does on other hardware:** batch 8 stays on graphed SDPA
(E2B, 26B-A4B and Qwen3.6). A T4 stays on SDPA (graphed SDPA 29.9 ms vs
forced flex much slower; head_dim 512 does not fit a T4 tile). Without
decode graphs, every model keeps SDPA.

## Tests

* `tests/test_flex_decode_gemma4.py`, `tests/test_flex_decode_qwen35.py`
(new, CPU, float64): greedy `generate()` with flex decode steps equals
SDPA decode, tokens equal and logits within 1e-9, covering:
* Gemma 4 E2B-like (KV-shared consumer layers, head_dim 256 / 512) and
26B-A4B-like (k_eq_v, 16/8 and 16/2 heads);
  * past the sliding window, including the real 512 / 1024 windows;
  * batch 1 and a ragged left-padded batch;
  * zoo's own BlockMask;
  * head_dim 512 left on SDPA;
* tiny `qwen3_5` and `qwen3_5_moe` models with the gated full attention
between Gated DeltaNet layers.
* `tests/test_flex_decode_routing.py` (new): steps switch and prefill
keeps SDPA, `auto` only for graph-planned calls and up to the batch cap,
off switch, unlisted / excluded models unchanged,
`FlexDecodeUnavailable` served by SDPA exactly.

With the existing generate / decode graph suites: 136 passed, 3 skipped
(slow excluded) on transformers 5.22.1, plus
`test_flex_mask_graph_breaks.py::test_compiled_flex_mask_has_no_graph_breaks_and_matches_eager`,
which fails on 5.22.1 identically on unslothai#16587 alone (transformers'
`fast_all` branch). 124 passed, 6 skipped on 4.57.6 (no 5.x mask
interface: routing off). Real GPU: the routing, Gemma 4, Qwen3.5 and zoo
contract suites pass on Kaggle T4 (128 passed, 2 skipped) and the
Qwen3.5 file on Colab T4 (8 passed); the CPU stand-ins pin transformers'
torch Gated DeltaNet functions and the native MoE loop, since FLA
kernels and the host-wide grouped_mm backend reject float64 CPU tensors
on GPU hosts. AMD gfx1151 (ROCm): 86 passed, 6 skipped; auto stays off
on ROCm. Split over 2 x T4 (Gemma 4 E2B 4-bit): forced flex decode
matches eager (KL <= 1.6e-4) with the BlockMask moved per card. When
generate requests attention weights, decode steps keep the model's own
attention (flex decode returns none).

Not covered: Qwen3.6 and Gemma 4 26B in 16-bit (do not fit a 40 GB
card).
bestoffersdirect-fork-sync Bot pushed a commit to BestOffersDirect/unsloth that referenced this pull request Nov 15, 2026
…thai#16576)

## Summary

Speeds up `generate` on 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 @ A` makes 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

* grad disabled (the normal generate path);
* `max_new_tokens >= 128` when the call decodes eagerly, or `>= 512`
when the call decodes through CUDA graphs (now the default for plain
`generate()` on NVIDIA Linux). The threshold follows the plan Unsloth's
`generate()` 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;
* one active plain LoRA adapter: no DoRA, no LoRA bias, no active
dropout;
* frozen, untied, plain fp16 `nn.Linear` base weights on one CUDA
device. bf16 bases fold only with `UNSLOTH_LORA_FOLD_GENERATE=1` (see
Accuracy). 4-bit / 8-bit / fp8 / torchao bases are refused and run the
normal path;
* no vLLM engine sharing the weights, and no FSDP / TP / PP / DTensor /
DeepSpeed parameters;
* the exact kernel's self-check passed.

It also refuses QAT / fake-quantized layers, custom `nn.Linear`
subclasses, 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=0` disables it.
`UNSLOTH_LORA_FOLD_GENERATE_MIN_TOKENS` sets the threshold.

Hooks live in `llama.py` (FastLanguageModel) and `vision.py` (FastModel)
generate wrappers. The new module is
`unsloth/models/_lora_fold_generate.py`.

## Changes in this round

* Merged current `main` (0945ac0, 622 commits). No conflicts. Main
now runs decode CUDA graphs by default in plain `generate()` for every
FastModel model, keeps the graph and its StaticCache across calls, and
exposes the per-call decode plan.
* The token threshold now reads the call's own decode plan. Before, it
read `_decode_graphs.enabled()`, which is True for every call inside
`generate()` now that graphs are on by default, so a FastModel call that
decodes eagerly waited for 512 new tokens instead of 128. New test
`test_threshold_follows_the_call_plan` fails on the previous head
(`assert 512 == 128`) and passes here.
* Kept graphs stay correct across folded and unfolded calls: the decode
graph fingerprint includes each adapter layer's merged state, which the
fold sets for the duration of the call, so a graph captured during a
folded call is never replayed by an unfolded one (and the other way
round).

## 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):

| Model | mode | main | this PR | speedup | peak GB main / PR | tokens
vs main |
|---|---|---|---|---|---|---|
| Llama-3.2-1B-Instruct | default (graphs) | 13.88 [13.39-13.93] | 13.35
[13.24-13.60] | 1.04x (inside A/A) | 2.44 / 2.54 | first difference at
199 |
| Llama-3.2-1B-Instruct | eager | 27.71 [26.80-28.35] | 19.43
[19.31-19.44] | 1.43x | 2.48 / 2.59 | first difference at 199 |
| Qwen3-0.6B | default (graphs) | 10.46 [10.34-10.68] | 9.12 [9.03-9.19]
| 1.15x | 1.29 / 1.32 | identical |
| Qwen3-0.6B | eager | 47.67 [44.65-47.69] | 31.94 [31.40-33.17] | 1.49x
| 1.41 / 1.45 | identical |
| gemma-3-1b-it (FastModel) | default (graphs) | 17.84 [17.83-17.86] |
15.37 [15.34-15.40] | 1.16x | 1.96 / 2.02 | identical |
| gemma-3-1b-it (FastModel) | eager | 84.56 [84.33-85.59] | 60.09
[59.37-60.18] | 1.41x | 1.95 / 1.98 | identical |

With `UNSLOTH_LORA_FOLD_GENERATE=0` this 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):

| Model | mode | main | this PR | speedup | peak GB main / PR | tokens
vs main |
|---|---|---|---|---|---|---|
| Llama-3.2-1B-Instruct | default (graphs) | 12.24 [12.24-12.32] | 11.77
[11.77-11.79] | 1.04x | 2.44 / 2.54 | first difference at 342 |
| Llama-3.2-1B-Instruct | eager | 27.95 [27.53-28.22] | 19.72
[19.67-19.89] | 1.42x | 2.48 / 2.59 | first difference at 342 |
| Qwen3-0.6B | default (graphs) | 8.76 [8.64-8.89] | 8.66 [8.66-8.84] |
1.01x (inside A/A) | 1.29 / 1.32 | identical |
| Qwen3-0.6B | eager | 46.34 [46.33-47.15] | 32.93 [32.77-33.39] | 1.41x
| 1.41 / 1.45 | identical |
| gemma-3-1b-it (FastModel) | default (graphs) | 14.20 [14.19-14.41] |
12.68 [12.68-12.83] | 1.12x | 1.96 / 2.02 | first difference at 205 |
| gemma-3-1b-it (FastModel) | eager | 85.83 [85.32-88.38] | 60.04
[59.28-60.82] | 1.43x | 1.95 / 1.98 | first difference at 205 |
| Llama-3.2-1B-Instruct bf16, default settings | default (graphs) |
12.26 [12.23-12.27] | 12.27 (refused: `bf16`) | 1.00x | 2.44 / 2.44 |
identical |
| Llama-3.2-1B-Instruct bf16, `UNSLOTH_LORA_FOLD_GENERATE=1` | default
(graphs) | 12.26 | 11.80 [11.76-11.82] | 1.04x | 2.44 / 2.54 | first
difference at 62 |
| Llama-3.2-1B-Instruct bf16, `UNSLOTH_LORA_FOLD_GENERATE=1` | eager |
27.84 [27.59-27.90] | 19.76 [19.63-19.95] | 1.41x | 2.48 / 2.57 | first
difference at 62 |

With 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 with `test_dia_generate_pad_token.py` and
`test_fa2_fast_generate_bypass.py`.
* Main's decode graph suites on this branch
(`test_generic_decode_graphs{,_default}.py`,
`test_decode_cuda_graphs{,_default}.py`): 66 passed, 36 skipped (GPU
only) on CPU.
* GPU correctness (B200, sm100, not timing): the test file passes (47
passed); an end-to-end Qwen3-0.6B fp16 LoRA run engages the fold under
graphs and eagerly, and the kill switch gives tokens identical to main.

## Not covered

* A100 / H100 / sm120 on current main (A100 numbers in the previous
round were taken with unslothai#16587 before it merged).
* bsz > 1 on current main (earlier rounds: bsz 8 gains matched bsz 1).
* Windows, ROCm (decode graphs are off by default there, so the eager
threshold applies; not measured).
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.

2 participants