Skip to content

Compiled blocks: packed rows run varlen attention outside the graph - #14808

Merged
danielhanchen merged 7 commits into
mainfrom
fastmodel-packed-varlen-compiled-blocks
Oct 25, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
fastmodel-packed-varlen-compiled-blocks

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Since #10744 (in 2026.10.7), FastModel compiles each stock decoder layer as one torch.compile region. With padding-free packing on (the default), every step is one packed row whose length changes per step. Inside the compiled region hf_packed_attention cannot run its varlen kernel, so it falls back to SDPA over the dense block-causal mask. On SM100 (B200) that call goes to cuDNN attention, which builds a new plan for every new sequence length (forward, recompute and backward). On torch 2.11 and 2.12 those builds are slow enough to dominate the step. FastLanguageModel is not affected because its block wrapper already sends packed rows to the uncompiled forward.

Change

  • _block_compile sets hf_packed_attention.IN_COMPILED_BLOCK while one of its own compiled decoder blocks runs.
  • In that window, a packed call (packed_seq_lengths present) leaves the graph through a torch.compiler.disable copy of the wrapper and runs the varlen kernel as it does in eager mode (one graph break per layer; norms, MLP and LoRA around it stay compiled), but only when it pays off:
    • torch < 2.13 (compiled cuDNN plans per new length cost about 0.3 to 12 s on 2.11, about 0.15 s on 2.13, with cuDNN 9.19 or 9.20 alike),
    • the eager wrapper has a varlen kernel for that device / dtype / head dim / window (torch varlen, flash-attn or xformers),
    • SDPA over the dense mask would pick cuDNN (torch._fused_sdp_choice).
  • The verdict is computed once per (device, dtype, head dim, window) with real tensors and baked into the block's graph (assume_constant_result), so it adds no guard, recompile or per-call cost.
  • Everywhere else (T4 and other GPUs without a varlen kernel, ROCm, torch >= 2.13, a user's own outer torch.compile, unpacked batches, UNSLOTH_HF_PACKED_VARLEN=0) the code path is the same as before.

Numbers

Qwen3-0.6B LoRA SFT, 16bit, padding-free, alpaca rows, batch 4, 25 steps, median s/step of steps 6 to 25, base and head interleaved (base, head, head, base) in fresh processes on one B200 (shared host):

torch main always leave the graph (first commit) this PR
2.11 0.384 / 0.388 0.28 / 0.35 (15 steps) 0.245 / 0.257
2.12 0.392 / 0.379 0.339 / 0.287 0.292 / 0.287
2.13 0.189 / 0.158 0.282 / 0.253 same path as main (0 graph breaks)

Tesla T4 (fp16, no varlen kernel, Kaggle), same job, 20 steps: leaving the graph unconditionally was 0.335 / 0.345 s/step against 0.225 / 0.218 on main, every packed call falling back to SDPA anyway. With the gate T4 takes the main path (0 graph breaks): 0.209 / 0.206 against 0.211 / 0.225 (16bit), 0.241 / 0.215 against 0.324 / 0.215 (4bit).

Losses match main within about 3e-3 per step on every arm; peak memory equal (1.97 to 2.02 GB 16bit, 1.40 GB 4bit on T4).

Tests

  • tests/test_block_compile.py: the compiled block sets and restores the flag, never on the stock forward, and still runs when the packed module was never imported.
  • tests/test_hf_packed_attention.py: a packed row the gate sends out runs the wrapper eagerly while a CPU row, an outer compile without the flag and unpacked rows stay in the graph; the gate refuses non CUDA devices, unsupported windows, head dims past 256 or not a multiple of 8, and torch >= 2.13; the verdict is computed once with real tensors while tracing (an lru_cache wrapper would be traced through and always say no); on CUDA the traced verdict matches the eager probe and a row it sends out takes the varlen kernel (asserted on SM100 with torch < 2.13).
  • GPU tests pass on B200 with torch 2.11, 2.12 and 2.13.

Not covered

  • Unpacked batches with variable-length padding masks probably hit the same cuDNN plan rebuilds on SM100 with torch < 2.13; not changed here.
  • Not run on H100 / A100 with flash-attn installed, or with GRPO.

FastModel compiles each stock decoder layer as one region (#10744). Inside
it hf_packed_attention bailed out on is_compiling(), so padding-free packed
rows ran SDPA over the dense block-causal mask. On SM100 that picks cuDNN
attention, which builds a new plan for every new sequence length: three
plan builds per step (forward, recompute, backward), 1-2.5 s each on a
loaded host. Qwen3-0.6B LoRA SFT on a B200 went from 0.5 s/step to 8.5
s/step through FastModel while FastLanguageModel stayed at 0.35 s/step.

While a block's compiled call runs, packed calls now go through a
torch.compiler.disable'd copy of the wrapper (one graph break per layer),
so they take the varlen kernel as in eager; norms, MLP and LoRA stay
compiled. A user's own torch.compile is unchanged. Same model: 0.28 s/step,
same losses and peak memory.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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-25T10:26:05.599590Z 7ceaa58 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 6f0127d5f7

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

…e slow

The graph break per layer cost +50% on T4 (no varlen kernel: every call fell back) and +55% on
B200 with torch 2.13 (cheap cuDNN plans). Leave the block only on torch < 2.13 when the eager
wrapper has a varlen kernel and dense-mask SDPA would pick cuDNN; the verdict is computed once
per (device, dtype, head dim, window) with real tensors and baked into the graph.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 8a87f15644

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

A symbolic head dim cannot be folded by assume_constant_result; the GPU test now marks the
sequence dims dynamic the way _block_compile does instead of compiling fully dynamic.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 7ceaa5837f

ℹ️ 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 e6f72a0 into main Oct 25, 2026
18 of 30 checks passed
@danielhanchen
danielhanchen deleted the fastmodel-packed-varlen-compiled-blocks branch October 25, 2026 11:13
danielhanchen added a commit that referenced this pull request Oct 26, 2026
…raph (#15325)

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.
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.

1 participant