Repository navigation
Decode with CUDA graphs by default in plain generate(), with memory release and an eager fallback - #16691
Conversation
…training Eager native decode is host bound: about 1070 kernel launches per step for Qwen3-0.6B, so the GPU is busy for 5 of 47 ms per step on a Colab L4. The captured decode step (bitwise equal to eager) is already the default inside RL trainer generation and Studio chat; plain model.generate() now enters the same per-thread scope (generate_scope), with the same platform rules: NVIDIA CUDA, not native Windows, llama / qwen3 model types. UNSLOTH_DECODE_CUDA_GRAPHS=0 restores eager decode. for_training() now frees the captured graphs and the decode KV buffers, so training does not hold the memory a previous generate() left behind.
…do an OOM call eagerly Qwen3-4B NF4 / QLoRA at bs 16 x ctx 2048 on a 15 GB T4 ran out of memory with graph decode after the same process had decoded bs 1 and bs 4: the first decode step allocated the bs 16 KV cache while the two kept caches (and their graphs) were still held. - alloc_decode_buffers evicts the kept caches before allocating a new one, not after. - make_room() runs before a graphed generate(): when cudaMemGetInfo plus the allocator's cached free bytes is under ROOM_MARGIN (1.25, UNSLOTH_DECODE_GRAPH_ROOM_MARGIN) x the call's estimated KV cache and prefill working set, it releases the kept graphs and decode buffers and empties the cache. A kept cache of the same batch size with enough rows counts as reused. - generate_with_fallback(): an out-of-memory graphed generate() frees the graphs and buffers and is redone once eagerly (eager_scope), with one warning per process; a caller cache or streamer re-raises instead. CPU tests mock the memory query and the generate call (tests/test_decode_graphs_memory.py).
…erprint control for_training() now frees the decode graphs, which made the stale_control case recapture and match eager. The test is about the fingerprint catching adapter edits on kept graphs, so it keeps them.
…forward, count eager redos - After a graphed generate() only that call's batch size keeps its decode cache and graphs (keep_only); its graphs stay valid, so repeated calls of one shape still replay without capture. - The model is marked as holding decode memory; the next training forward with grad on (training resumed without for_training(), e.g. sampling inside a trainer callback) frees the graphs and decode caches before it allocates activations (release_if_training). - EAGER_REDOS counts generate() calls redone eagerly after an out-of-memory error. CPU tests cover keep_only, the training release, the held mark and the redo counter; GPU tests force a real allocator OOM in the graph path (eager tokens returned, one redo, one warning) and check that a training forward after generate() frees the decode memory.
…art, from measured peaks make_room() is replaced by plan_call(): a graphed generate() call's need is the measured peak of the first graphed call of its batch size and length bucket (x 1.05), else a calibrated estimate (1.15 x (KV cache + prefill working set) + 0.30 x KV cache, from Qwen3-4B NF4 / QLoRA bs 16 x ctx 2048 on a 15 GB T4). When free memory is short, the graphs and caches kept from earlier calls are released; when it is still short the call decodes eagerly from the start and is counted in EAGER_UNFIT, so a predictable shape no longer runs out of memory and gets redone. record_need() reads (never resets) the allocator's peak after the call. The out-of-memory redo stays as the safety net.
Codex Review SummaryThis 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]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d2b25dea5a
ℹ️ 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".
| release(model) | ||
| _empty_cache() | ||
| free = _free_bytes(device) |
There was a problem hiding this comment.
Drop local buffer references before rechecking free memory
When a call would fit only after reclaiming a previous call's KV buffers, this recheck still counts those buffers as allocated: the local stores list retains their dictionaries, and release() only removes the dictionaries from the modules rather than clearing them. Consequently, _empty_cache() cannot reclaim their storage until plan_call() returns, so a fitting call is incorrectly routed to eager decoding. This defeats the release-and-replan path when alternating batch sizes under memory pressure. Clear the retained dictionaries and any local bufs reference before querying free memory again.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7ef8c56. The scan of kept buffers moved into a helper, _kept_buffers(), which returns only a flag and a byte count, so plan_call() holds no reference to the old dictionaries or tensors when it calls release() and _empty_cache(), and the recheck sees the freed memory. New CPU test test_plan_holds_no_buffer_reference_when_it_empties_the_cache tracks the kept tensors with weak references: on the previous head all 6 were still alive when the cache was emptied, on this head none are. tests/test_decode_graphs_memory.py: 21 passed.
…ll, so empty_cache frees it [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: 7ef8c56fa7
ℹ️ 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".
| key, device, start, peak_before = token | ||
| peak = _alloc_stats(device)[1] | ||
| if peak > peak_before: | ||
| model.__dict__.setdefault(NEEDS, {}).setdefault(key, peak - start) |
There was a problem hiding this comment.
Normalize measured memory needs for already-held buffers
When the first measured call for a length bucket reuses KV buffers from an earlier call, peak - start excludes those buffers because they were already allocated at the start. However, plan_call() treats this measurement as a complete footprint and subtracts reusable KV bytes again; after releasing the buffers, it also continues using the incomplete measurement. Subsequent calls can therefore be admitted despite insufficient memory, causing avoidable OOM retries or an unrecovered OOM when a streamer is supplied. Include the reused allocation in the recorded footprint, or track incremental and total requirements separately.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f287cf9. plan_call() now passes the bytes of the kept cache it counts as reused into the token, and record_need() stores the whole footprint (peak above the start plus that reuse). The kept cache is then subtracted exactly once, and after a release nothing is subtracted, so the full footprint has to fit. New test test_measured_need_includes_a_reused_cache_and_is_discounted_once fails on the previous head and passes here.
| elif graphs: | ||
| ids = _generation_input_ids(args, kwargs) | ||
| if hasattr(ids, "shape") and len(ids.shape) >= 2: | ||
| _decode_graphs.keep_only(self, int(ids.shape[0])) |
There was a problem hiding this comment.
Keep buffers for the expanded generation batch size
For beam search or sampling with num_return_sequences > 1, generation expands the input batch before decoding, so the buffer and graph keys use the expanded batch size rather than ids.shape[0]. Calling keep_only() with the original batch size deletes every graph and KV buffer just captured for these requests. Repeated inference calls with the same settings consequently pay capture overhead every time instead of replaying the cached graphs. Use the actual decode batch size when selecting the cache to retain.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f287cf9. decode_batch() computes the batch generate() decodes at (num_beams above 1, else num_return_sequences, from kwargs or the generation config), plan_call() sizes the call with it, and keep_only() keeps the batch size the attention cache actually holds after the call, with the expected batch only as a fallback. On a T4, tiny Qwen3 with num_return_sequences=2 called twice: the previous head captured again on the second call and kept no graphs; this head keeps the graph and the second call replays (1 capture, 28 replays). CPU tests test_decode_batch_follows_generate_expansion, test_plan_sizes_the_expanded_batch and test_keep_only_keeps_the_batch_size_decode_used fail on the previous head and pass here.
…the expanded decode batch - record_need() stores the first graphed call's whole footprint: its peak above the start plus the kept cache it reused, which was already allocated at the start. plan_call() subtracts the reuse exactly once, and judges the full footprint once the cache is released. - decode_batch() computes the batch size generate() decodes at (num_beams, else num_return_sequences, from kwargs or the generation config); plan_call() sizes that batch, and keep_only() keeps the batch size the decode actually used (the attention's current cache), so sampling several sequences per prompt no longer drops the graphs it just captured. [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: f287cf9d9c
ℹ️ 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".
| def _shape_key(bsz, prompt, max_len): | ||
| return (bsz, _round_up(max(prompt, max_len) + 1, BUCKET)) |
There was a problem hiding this comment.
Include prompt length in the measured-memory key
When calls have the same batch size and total requested length but different prompt lengths, this key aliases their measurements even though their prefill working sets differ substantially. For example, batch-4 calls with prompts of 128 and 2048 tokens and a total length of 4096 both use (4, 4352). Once the short-prompt call records a measurement, plan_call() replaces the longer prompt's estimate with that smaller footprint, potentially admitting a call that needs an OOM retry—or fails outright when a streamer prevents retrying. Include the prompt-length bucket separately in the measurement key.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c683682. The shape key is now (batch, prompt-length bucket, total-length bucket), so a 128-token and a 2048-token prompt to the same total no longer share a measurement. plan_call() also never lets a measurement lower the need: it uses the larger of the calibrated estimate and 1.05 x the measured footprint. New test test_prompt_length_is_part_of_the_shape fails on the previous head and passes here.
| peak = _alloc_stats(device)[1] | ||
| if peak > peak_before: | ||
| model.__dict__.setdefault(NEEDS, {}).setdefault(key, peak - start + reused) |
There was a problem hiding this comment.
Avoid recording early-stopped calls as full-length measurements
With the default PREALLOC=False, a call that stops on EOS can allocate only the initial KV buffer, but its measured peak is stored under the full requested-length key. For example, a 128-token prompt requesting a total length of 4096 can stop while its cache still has only 768 rows. A subsequent call with identical length settings that generates to the limit needs a much larger cache, yet plan_call() trusts the early-stopped footprint instead of the full-length estimate. Because setdefault() preserves the first measurement indefinitely, this can cause repeated OOM retries or unrecovered streaming OOMs. Only record a full-length measurement when execution reached the relevant cache capacity, or retain a conservative bound for unobserved growth.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c683682. record_need() keeps the largest footprint seen for a shape instead of the first, and plan_call() uses the larger of the calibrated estimate and the measured footprint, so an early-stopped call can only ever leave the need at the full-length estimate, never below it. New test test_an_early_stop_measurement_never_admits_a_full_length_call fails on the previous head and passes here. On a T4 with the final head, EAGER_REDOS stays 0 in every cell and the decode-graph GPU suite is 171 passed, 0 failed.
…y prompt and total length - plan_call() needs max(calibrated estimate, 1.05 x measured footprint): the measurement corrects estimates that run low on other GPUs and never lowers them (a call that stopped on EOS before its cache grew peaks low). - record_need() keeps the largest footprint per shape instead of the first. - The shape key adds the prompt-length bucket: one batch size and total length with a longer prompt has a larger prefill, so a short prompt's measurement no longer stands in for it.
|
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". |
[skip ci]
Mistral, Qwen2, Gemma and Gemma2 reach plain generate() with graph mode on but always decode eagerly. An OOM there was redone once with a CUDA-graph warning; it now raises once as before, and the plan skips them.
… nothing is kept The first decode step after a prefill always runs eagerly, so a generate() with at most 2 new tokens never replays a captured step. With no kept graphs it now skips graph mode and the plan, as before this change.
memory_allocated(), memory_reserved() and max_memory_allocated() each rebuild and flatten the whole stats dict; one memory_stats_as_nested_dict() read gives all three (plan_call 1.1 -> 0.54 ms, record_need 0.27 -> 0.02 ms on a T4).
…n it back A new capture costs about 3 eager decode steps on a T4. With only the last batch size kept, calls that alternate batch sizes re-captured every call, and 3-4 new tokens ran 32-58% slower than eager. A step with no kept graph for its shape now runs eagerly when fewer than CAPTURE_MIN_STEPS (6) steps are left in the generate() call (MAX_LEN_HINT); a kept graph still replays, and decode loops without a length hint capture as before. Skips are counted in stats()['short_skips'].
Unless a captured step of its decode batch is kept, a generate() call with fewer than CAPTURE_MIN_STEPS steps left at its first graphed step skips graph mode altogether (planning, graph-sized buffers, per-step checks), so alternating batch sizes with a few new tokens cost what eager does. Beside kept graphs it only makes room for itself.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6bb8e52418
ℹ️ 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".
| kept, reused = _kept_buffers(model, (bsz, dtype, device), rows) | ||
| need -= reused |
There was a problem hiding this comment.
Avoid discounting graph-cache reuse for eager calls
When a short call runs with eager=True, the kept graph cache is still subtracted even though eager_scope() makes alloc_decode_buffers() allocate fresh eager buffers instead of reusing it. For example, a two-token request following a longer request at the same batch size can have a kept cache larger than the entire new estimate, making need negative and preventing release even with almost no free memory. The short call can then OOM despite fitting after releasing the kept cache, and graphs=False prevents the eager retry. Only credit reusable graph buffers when the planned call will actually use them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2f2e872. When the call runs eagerly (eager=True), plan_call() now judges it by the eager estimate only: no graph-capture extra, no measured graphed footprint, and no credit for a kept graph cache, since eager decode allocates fresh buffers. A short call beside a large kept cache therefore releases it when memory is short instead of planning a negative need. New test test_an_eager_short_call_gets_no_credit_for_a_kept_graph_cache fails on the previous head (the kept cache stays held) and passes here; tests/test_decode_graphs_memory.py 54 passed.
… or a kept-cache credit [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: 2f2e872f67
ℹ️ 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".
| if eager: | ||
| # Eager decode allocates fresh buffers: no graph extra and no credit for a kept graph cache. | ||
| full, reused = CALIB_WORK * (kv + work), 0 | ||
| need = full - reused |
There was a problem hiding this comment.
Bound the reuse credit for oversized retained caches
When a shorter graphed request follows a long request at the same batch size, _kept_buffers() credits the entire retained allocation, but the unmeasured full estimate includes only the smaller request's KV size. Subtracting those bytes can make need negative despite a nonzero prefill working set. For example, with Qwen3-4B dimensions, batch 4, an 8192-row retained cache, and a 128-token prompt requesting 32 new tokens, the planner admits graphs even with zero free bytes. This bypasses release-and-replan and can cause an avoidable OOM, which is unrecoverable with a streamer. Bound the estimated reuse credit by the KV allocation included in the estimate, or include the oversized retained allocation in the full footprint before subtracting it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in f1cf918. plan_call() now caps the reuse credit at the KV bytes the call's own estimate counts (reused = min(reused, kv)), so an oversized kept cache from a longer call can no longer cancel the prefill working set or push the need below zero; a same-sized kept cache still gets its full credit. New test test_an_oversized_kept_cache_is_credited_only_up_to_this_call_kv (batch 4, 8192-row kept cache, 128-token prompt, zero free bytes) admitted graphs on the previous head and now releases the cache and decodes eagerly; tests/test_decode_graphs_memory.py 55 passed.
…ate counts [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: f1cf918a93
ℹ️ 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".
| with eager_scope(): | ||
| return generate(*args, **kwargs) |
There was a problem hiding this comment.
Preserve callback state when retrying generation
When an OOM occurs after some tokens have been generated, the eager retry receives the same caller-supplied stopping criteria and logits processors, including any state they accumulated during the failed attempt. Stateful criteria are already used in tests/test_decode_graphs_kv_growth_device.py::_StopAfter: a stop-after-5 criterion invoked three times before an OOM stops the retry after only two tokens, silently returning a truncated completion. Like streamers and supplied caches, these callbacks make restarting unsafe unless their original state is restored; preserve that state before the initial attempt or propagate the OOM when a safe retry cannot be guaranteed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in eb3f47f. A caller-supplied, non-empty stopping_criteria or logits_processor now makes the OOM re-raise, the same as a streamer or a supplied past_key_values, since either can carry state from the failed attempt; an empty list (nothing stateful) still gets the eager redo. The re-raise test is parametrized over both new cases; they fail on the previous head and pass here. tests/test_decode_graphs_memory.py 57 passed.
…ors re-raises instead of a stateful redo [skip ci]
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6d497ac8de
ℹ️ 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".
| plan, token = _decode_graphs.plan_call( | ||
| self, ids, dtype, KV_CACHE_INCREMENT, max_len, bsz = bsz, eager = short, | ||
| ) # fmt: skip |
There was a problem hiding this comment.
Include configured max_length in the memory-planning limit
When the caller supplies GenerationConfig(max_length=4096) without max_new_tokens, _generation_max_len() returns 0 even though generation can run to 4096 tokens. Using that result for the new memory planner sizes its estimate for only the initial cache (prompt + KV_CACHE_INCREMENT + 1), rather than the configured limit. A long-running call can therefore be admitted to graph mode despite insufficient memory for cache growth, causing an avoidable OOM retry or an unrecovered OOM when a streamer disables retrying. Resolve the effective configured max_length for planning, including caller-supplied generation configurations, rather than treating it as an unknown length.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in cb68e34. Planning now uses _generation_plan_len(): when the call sets no max_new_tokens, a max_length that the caller's own GenerationConfig sets explicitly (read from to_diff_dict()) is the planning length, so the estimate covers cache growth up to it. The model's default generation config is still not treated as a request, and buffer sizing (start_generation) keeps using _generation_max_len() unchanged. New test test_planning_honours_an_explicit_max_length_in_the_caller_generation_config fails on the previous head and passes here.
…ets explicitly [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: cb68e34309
ℹ️ 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".
| if plan == "eager": | ||
| graphs = False | ||
| else: | ||
| _decode_graphs.start_generation(max_len) |
There was a problem hiding this comment.
Pass the resolved planning limit to cache growth
When the caller supplies GenerationConfig(max_length=4096) without max_new_tokens, plan_len is 4096 but max_len remains zero. With the default PREALLOC=False, passing zero to start_generation() leaves resize_decode_buffers() uncapped: a 128-token prompt grows through 768, 1536, 3072, and 6144 cache rows, although the planner budgets only 4352 rows. This can admit graph decoding without enough memory for its actual cache, causing an avoidable OOM that cannot be retried when a streamer is supplied. Pass the resolved explicit limit into the cache-growth hint as well as the planner.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 9c1ec63. start_generation() now gets the same planned length as short_call() and plan_call(), so a GenerationConfig(max_length=4096) call caps the graph-backed cache growth at the 4097 rows the planner budgeted instead of doubling past it. Added test_cache_growth_cap_uses_the_planned_length, which fails on the previous head.
The planner already budgets an explicit max_length from the caller's GenerationConfig, but start_generation still got the request length, which is 0 there, so the graph-backed cache doubled past what was planned (a 128-token prompt grows to 6144 rows against a 4352-row budget). Pass the planned length to both.
|
@codex review |
|
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).
Summary
Native decode in plain
model.generate()is host bound. A Qwen3-0.6B step launches about 675 kernels, and 1070 to 1430 with LoRA, so on a T4 the GPU is busy for only a fraction of each 30 to 75 ms step. The captured decode step already exists. It is bitwise equal to the eager step, and it is already the default inside RL trainer generation and Studio chat.This makes it the default for plain
generate()too, on the same platforms: NVIDIA CUDA, not native Windows, and the llama and qwen3 model types.UNSLOTH_DECODE_CUDA_GRAPHS=0restores eager decode. Plain decode becomes 2.9x to 5.4x faster at batch 1 on Qwen3-0.6B, and up to 1.9x on Qwen3-4B with 4-bit weights and LoRA.Turning graphs on for every
generate()turns their memory and capture costs into a default, so this change also controls them:for_training().The planner also runs inside the RL and Studio graph scopes, where graphs were already on. There it only changes behaviour under memory pressure: a call that fits takes the same graphed path as before.
Change
unsloth/models/_decode_graphs.pygenerate_scope()is a per-thread scope that turns graphs on by default. It follows the same rules as the Studio scope.eager_scope()is a per-thread override that forces eager decode.plan_call()runs before a graphed call.cudaMemGetInfoplus the allocator's reserved-but-free bytes. The allocator stats are read once per query.EAGER_UNFIT.CAPTURE_MIN_STEPS(6,UNSLOTH_DECODE_GRAPH_CAPTURE_MIN_STEPS) is the number of steps that must be left for a capture to pay off.short_call(): agenerate()call that cannot replay a step, or would have to capture one with fewer steps left than that, skips graph mode entirely. Skipping covers planning, graph-sized buffers and per-step checks. The exception is a call whose decode batch already has a captured step kept: it replays that step without capturing.decode_step()applies the same rule per step: a new capture is skipped when too few steps are left, counted instats()["short_skips"]. A kept graph of the step's shape still replays.record_need()reads the allocator's peak after a graphed call and never resets it.alloc_decode_buffersevicts the kept caches before it allocates a new one, instead of after.generate_with_fallback()is the safety net. A graphed call that still runs out of memory frees the graphs and caches and is redone once eagerly. It warns once per process and counts the redo inEAGER_REDOS. A caller-suppliedstreamerorpast_key_valuesre-raises instead. Model types that never graph keep their eager behaviour unchanged.keep_only()drops the caches and graphs of every other batch size after a call. The batch size decode actually ran at wins, including the expansion fromnum_beamsornum_return_sequences. The kept batch size still replays without a re-capture.release_if_training()frees what a graphed call left. It costs one dict read when nothing is held.unsloth/models/llama.pyunsloth_fast_generateentersgenerate_scope()and runsshort_call()andplan_call(), thengenerate_with_fallback(). After the call it runsrecord_need()andkeep_only(), and marks the model as holding decode memory.FastLlamaModel.for_training()callsrelease_for_training()._CausalLM_fast_forwardcallsrelease_if_training()on a training forward with grad enabled. This covers sampling inside a trainer callback, after which training resumes throughmodel.train()only.Testing
All GPU runs use a Kaggle T4 (fp16), one card per job. Base and head run on the same machine, in fresh processes, in alternating order (ABBA), 3 processes per arm unless noted. Base is the merge base of this branch. "Faster" means every head process beats every base process; "tie" means the ranges overlap.
Decode speed. Median ms per step over 32 greedy steps. LoRA is rank 16 on all 7 projections. The 4-bit weights are the
unsloth/Qwen3-*-bnb-4bitcheckpoints. The "after 1, 16" columns are the same calls made in one process in the order bs 1, bs 16, bs 4. A 32-step call is not a short call, so the short-call change does not touch these cells.EAGER_UNFIT= 6 per head process,EAGER_REDOS= 0 in every head process, and peak memory equals base (12.78 / 13.02 GB).Short calls with alternating batch sizes. Qwen3-0.6B, 16-bit, prompt 32. Each cell is 2 warm-up calls, then 10 timed calls alternating between the two batch sizes. Values are the median ms per call, with the max-min spread over the 3 processes in parentheses. Graph counts are per head process.
EAGER_REDOSis 0 in every head process.Logits. Greedy decoding, 24 steps, bs 1 and 4. Head logits are bitwise equal to base in every mode on Qwen3-0.6B and Qwen3-4B (max abs difference 0, token match 1.0). The error against an fp32 teacher-forced reference is the same in both arms. With
UNSLOTH_DECODE_CUDA_GRAPHS=0, head captures 0 graphs, runs at base speed, and produces base logits. These were measured before the plan and short-call changes. Neither change alters a graphed step, and an eager call takes the base path. The GPU tests below check bitwise equality on the final head.Memory and training.
Trainer, Qwen3-0.6B 4-bit + LoRA, 6 steps. Anon_step_endcallback at steps 2 and 4 callsfor_inferenceandgenerate()at bs 1 and bs 4. Peak / held GB for: train, callback, train, callback, trainmodel.train()only + 2 train steps. Held GB after each phasefor_training()Tests. The decode-graph suite ran on one T4 with
-o addopts= -m "gpu or not gpu", over these 10 files:tests/test_decode_cuda_graphs.pytests/test_decode_cuda_graphs_default.pytests/test_decode_cuda_graphs_studio.pytests/test_decode_full_graph.pytests/test_decode_graphs_eager_growth.pytests/test_decode_graphs_kv_growth_device.pytests/test_decode_graphs_memory.pytests/utils/test_decode_full_graph_stale_tail.pytests/utils/test_single_row_cached_attention.pytests/test_ppo_trainer_patches.pyEach arm imports its own tree.
tests/test_decode_graphs_memory.py, CPU. Covers: plan release, eager-from-start, measured peak, reuse, prompt-length keys, eager redo, redo counter,keep_onlywith expanded batches, training release, capture break-even, short callstest_out_of_memory_in_the_graph_path_redoes_the_call_eagerly, GPU. A real allocator OOM on the graph path only. Checks one redo, one warning, eager tokens and logits, then graphs againtest_training_forward_without_for_training_frees_generate_memory, GPUtest_short_calls_decode_eagerly_and_keep_the_kept_graph, GPU. A short call of another batch runs eagerly without graph buffers; a short call of the kept batch replays it; the kept graph is not re-captured; tokens equal eagertest_decode_cuda_graphs_studio.py::test_studio_generate_graphed_plain_generate_eager, fails on the merge base. Head updates that test, and the plain-generate default test, for the new default.test_lora_change_between_generations_recaptures, the stale-fingerprint control now keeps its graphs acrossfor_training(). The test still checks that the fingerprint catches adapter edits.Not covered
num_beamsabove 1.