Repository navigation
Compiled blocks: packed rows run the flash varlen kernel inside the graph - #15325
Conversation
torch's varlen_attn is a custom op with a fake impl, so it traces. What kept it out of the compiled decoder block was the wrapper's host work: max_seqlen needs a host read of the lengths and the block-causal mask check ends in a host sync. _block_compile.run now prepares (cu_seqlens, max_seqlen) and the mask verdict eagerly (cached per forward) and passes them in a private kwarg; the traced wrapper calls the op with them. No graph break; one recompile when max_seqlen first changes, then it is dynamic.
…he prep per step varlen_attn's Python custom op and autograd cost ~3 ms of host time per step in a compiled Qwen3-0.6B step (G4); aten._flash_attention_forward is what it runs, with a C++ backward and grouped K / V taken as is. The per-layer prep is now one lookup per layer after the first.
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. |
… cannot pass it [skip ci]
…licy every step The per-forward cache now keys on tensor versions (inference tensors are not cached), as _mask_is_block_causal does. Deterministic mode and the sdpa_kernel priority are read when the step's metadata is prepared instead of being cached with the hardware probe. [skip ci]
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…ot a traced counter
… a checkpoint's no_grad first trace keeps the varlen path (#15414) ## Problem `_varlen_in_graph_probe` (unsloth/utils/hf_packed_attention.py) decides once per (device, dtype, head_dim, heads, kv_heads, window) whether a compiled decoder block may call aten's flash varlen kernel. It runs a real forward and backward, catches any exception as "no", and caches the answer for every grad mode. The probe is evaluated while Dynamo traces the block. If that first trace runs without grad, the probe's `.backward()` raises, the probe returns False, and the cached False then also serves every later grad-enabled call. Two real ways to get there: a packed `torch.inference_mode()` (or `no_grad`) forward before training, for example a quick generation or evaluation pass, and a reentrant `torch.utils.checkpoint(..., use_reentrant=True)` around a compiled block, whose first forward runs under no_grad. Unsloth's own block compile already runs a grad-enabled trial first, so the default offloaded checkpointing path is not affected. When it happens, the packed row falls back to SDPA over the dense T x T mask for the whole run while the metadata preparation still runs every step. Outputs stay correct; the speedup from #15325 is lost. ## Fix The probe body runs under `torch.inference_mode(False), torch.enable_grad()`, so its verdict is the same whichever grad mode the first trace has. The cheap hardware/build checks now run before the two probe tensors are allocated. Nothing else changes: the cache key, the traced branch and the kernel call are untouched. ## Before / after B200, torch 2.13.0, transformers 5.17.0. Base = origin/main 0ea0473, head = this branch. | Test | Base | Head | | --- | --- | --- | | `test_varlen_in_graph_probe_runs_its_backward_with_grad_enabled[no_grad]` | FAIL (probe saw grad off) | PASS | | `test_varlen_in_graph_probe_runs_its_backward_with_grad_enabled[inference_mode]` | FAIL (probe saw inference mode) | PASS | | `test_varlen_in_graph_verdict_does_not_depend_on_the_first_grad_mode[no_grad]` | FAIL (False cached, grad answer True) | PASS | | `test_varlen_in_graph_verdict_does_not_depend_on_the_first_grad_mode[inference_mode]` | FAIL (False cached) | PASS | | `test_reentrant_checkpoint_first_trace_keeps_the_block_varlen_path` | FAIL (packed row fell back to dense SDPA) | PASS, forward and dQ / dK / dV match SDPA | | `tests/test_hf_packed_attention.py` + `tests/test_block_compile.py`, whole files | 175 passed, 15 failed | 180 passed, 10 failed | The 10 failures left on head are the same test IDs on base (`test_varlen_matches_sdpa_over_the_dense_mask[*-dispatch-*]` and `test_block_varlen_runs_inside_the_graph_and_matches_dense_sdpa[*]`, which pass when run alone). The two CPU-only tests also pass on CPU hosts, and the first one passes on torch 2.14.1. ## Not covered - An end-to-end packed training throughput A/B with Unsloth gradient checkpointing (exclusive GPU) was not run. The engagement test shows the varlen kernel now runs in both the checkpoint forward and its recompute. - `_leaves_block_probe` (used only on torch < 2.13) also reads grad state through `_fused_sdp_choice` and is not changed here. - torch 2.10 / 2.11 / 2.12 and ROCm were not run.
Follow-up to #14808. That PR sends packed rows out of a compiled decoder block (one graph break per layer) so they can run the varlen kernel eagerly, and only where compiled cuDNN plans are slow. This PR keeps the varlen kernel inside the compiled graph instead, on every GPU and torch version that has it.
Why the kernel was not in the graph
The kernel itself traces: torch's
varlen_attnis atorch.library.custom_opwith a fake implementation, and it is a thin wrapper overaten._flash_attention_forward, which has a native backward. What could not trace was the host workhf_packed_attentiondoes around it:max_seqlen) is a host integer read from the lengths (.max().item()),So under
torch.compilethe wrapper fell back to SDPA over the dense T x T block-causal mask.Change
_block_compile.run()is eager, just before a compiled decoder block. It now prepares(cu_seqlens, max_seqlen)and runs the mask check there (hf_packed_attention.block_varlen_kwargs), and passes the result to the layer in a private kwarg. The result is computed once per forward and reused by every layer and by the checkpoint recompute (weakrefs, so the mask never outlives its step).aten._flash_attention_forwarddirectly with those inputs: no graph break, no Python custom op per call, grouped K / V heads taken as they are.assume_constant_result). A torch build that would refuse at run time keeps the dense path instead of failing inside the graph.max_seqlenspecializes once and is dynamic from the second distinct value on: 2 extra graphs per run, then none.sdpa, layers whose forward takes no**kwargs, CPU, ROCm, GPUs below sm80 (T4), shapes torch's flash kernel does not take, andUNSLOTH_HF_PACKED_VARLEN=0.Numbers
Qwen3-0.6B LoRA SFT, 16bit, padding-free, alpaca rows, 25 steps, median s/step of steps 6 to 25, main and this PR interleaved (main, PR, PR, main) in fresh processes on one Colab / Kaggle card each:
Peak memory is equal at batch 4 and lower at batch 32 (for example A100 2.285-2.31 vs 2.43 GB, G4 1.85-1.88 vs 2.00 GB). Losses match main within bf16 noise; 0 graph breaks. T4 has no flash varlen (sm75), so it keeps main's path: 0 in-graph calls, same graphs, same times and losses.
A100 profile (steps 11 to 14): attention GPU time per step 19.1 ms (memory-efficient kernel over the dense mask) -> 5.5 ms (flash varlen); host time per step 207.5 -> 200.1 ms. An earlier version that called torch's
varlen_attnPython custom op from the graph cost about 3 ms of host time per step and was 4 to 11% slower at batch 4; calling the aten op directly and caching the prep removed that.Tests
tests/test_hf_packed_attention.py: every refusal of the eager prep keeps the dense path; the prep builds the metadata and rejects a mask that is not this block-causal one; a traced call with prepared metadata stays in the graph underfullgraph=Trueand the private kwarg never reaches the wrapped sdpa; on CUDA, the real kernel compiledfullgraph=Truewith dynamic sequence dims matches SDPA over the dense mask in forward and backward, with and without a sliding window, across four segment layouts in at most two graphs.Not covered