Skip to content

Compiled blocks: packed rows run the flash varlen kernel inside the graph - #15325

Merged
danielhanchen merged 8 commits into
mainfrom
packed-varlen-inside-compiled-blocks
Oct 26, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
packed-varlen-inside-compiled-blocks

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

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_attn is a torch.library.custom_op with a fake implementation, and it is a thin wrapper over aten._flash_attention_forward, which has a native backward. What could not trace was the host work hf_packed_attention does around it:

  • the longest segment length (max_seqlen) is a host integer read from the lengths (.max().item()),
  • the check that the dense mask is exactly block-causal ends in one host sync,
  • the wrapper bumps Python counters.

So under torch.compile the 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).
  • Inside the trace, the sdpa wrapper calls aten._flash_attention_forward directly with those inputs: no graph break, no Python custom op per call, grouped K / V heads taken as they are.
  • Whether a shape can take that call (device, dtype, head dim, heads, window, sdpa backend settings) is decided once with real tensors, including one forward and backward, and folded into the graph as a constant (assume_constant_result). A torch build that would refuse at run time keeps the dense path instead of failing inside the graph.
  • max_seqlen specializes once and is dynamic from the second distinct value on: 2 extra graphs per run, then none.
  • Unchanged: anything that is not a packed row inside an Unsloth compiled block, attention other than sdpa, layers whose forward takes no **kwargs, CPU, ROCm, GPUs below sm80 (T4), shapes torch's flash kernel does not take, and UNSLOTH_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:

GPU, torch batch 4 (~1.5k-token rows): main PR batch 32 (~10k-token rows): main PR
A100, 2.11.0 0.2227 / 0.2166 0.2156 / 0.2187 0.585 / 0.584 0.234 / 0.232
A100, 2.12.1 0.2244 / 0.2243 0.2198 / 0.2178 0.582 / 0.583 0.233 / 0.237
A100, 2.14.1 0.1855 / 0.1852 0.1794 / 0.1792 0.578 / 0.578 0.199 / 0.195
L4, 2.14.1 0.1823 / 0.1832 0.1738 / 0.1762 1.929 / 1.948 0.609 / 0.609
RTX PRO 6000 (G4), 2.14.1 0.0565 / 0.0542 0.0554 / 0.0553 0.499 / 0.495 0.103 / 0.104
T4 (Kaggle), 2.14.1 0.2456 / 0.2522 0.2520 / 0.2525 4.656 / 4.616 4.662 / 4.631

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_attn Python 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 under fullgraph=True and the private kwarg never reaches the wrapped sdpa; on CUDA, the real kernel compiled fullgraph=True with 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.
  • GPU tests pass on L4, A100 (torch 2.11, 2.12, 2.14) and RTX PRO 6000; the in-graph test fails when the traced branch is removed. CPU suites pass.

Not covered

  • H100 / B200 (no capacity during these runs); ROCm and Apple keep the dense path by construction (no flash varlen), not run.
  • On T4, five existing Gemma-4 / efficient-kernel tests in this file fail identically on main (no memory-efficient kernel past head dim 256 on sm75); not changed here.

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.
@danielhanchen danielhanchen self-assigned this Oct 26, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T07:07:35.732310Z 4f60c70 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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]
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. Delightful!

Reviewed commit: 14be5ebfc2

ℹ️ 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: 4f60c70512

ℹ️ 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 Oct 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 26, 2026
@danielhanchen
danielhanchen merged commit 85c9d20 into main Oct 26, 2026
29 of 30 checks passed
@danielhanchen
danielhanchen deleted the packed-varlen-inside-compiled-blocks branch October 26, 2026 08:44
danielhanchen added a commit that referenced this pull request Oct 27, 2026
… 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant