Skip to content

AsyncGRPO: run prefix-trie rows through the FlexAttention tree mask on fast backbones - #18614

Merged
danielhanchen merged 2 commits into
mainfrom
cg1-tree-attention
Nov 20, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
cg1-tree-attention

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

AsyncGRPO: run prefix-trie rows with a FlexAttention tree mask on fast backbones

TRL >= 1.17 packs each AsyncGRPOTrainer row as a prefix trie (TreeRow): tokens shared by several samples (the prompt, a common system prompt, a shared multi-turn prefix) are forwarded once, and TRL's tree_attention shows each segment the K/V of its root-to-segment path. Unsloth's fast backbones ignore that attention implementation, so _forward_tree_unrolled expanded every row back into one full copy per sample. That is exact, but it forwards every shared prefix once per sample, and because TRL budgets rows by unique tokens, the real forward length is the packing ratio larger than the budget (3x to 4x for a typical GRPO group).

What changes

  • unsloth/utils/prefix_grouper_kernel.py: a TreeSegInfo alongside PrefixSegInfo. TreeRow.pack lays the trie out in DFS pre-order, so every segment's subtree is one contiguous token range. One per-token tensor reach_end then defines the mask: kv token j is visible to query q iff j <= q < reach_end[j]. build_tree_seg_info checks the pre-order layout and raises on anything else. get_block_mask picks the tree mask_mod for a TreeSegInfo, and the existing flex path (compile check, padding, block-mask cache) is reused unchanged.
  • unsloth/models/rl.py: when the backbone's decoder layers apply prefix_seg_info (Llama, Mistral, Qwen3, Cohere, Granite, ...) the row is forwarded once over its unique tokens with prefix_seg_info=TreeSegInfo. It is also checked against TRL's own tree_cu_seqlens_k path lengths. Rows go through the unroll as before when any of these holds:
    • the row has no fork (plain packing, where varlen is faster),
    • a path is longer than the sliding window,
    • the model has softcapping, SSM / MoE layers or length-dependent RoPE,
    • context parallelism is active, the device is not CUDA, or the kernel fails its compile check (PrefixGrouperCompileError drops back to the unroll),
    • UNSLOTH_ASYNC_GRPO_TREE_ATTENTION=0 is set.
  • The unroll now prints once when it expands a row by 2x or more, with the unique and unrolled token counts, so an out-of-memory error under TRL's unique-token budget can be explained. _ASYNC_GRPO_TREE_COUNTS counts both paths.

Tests

  • tests/test_prefix_grouper_tree_mask.py (CPU):
    • FlexAttention forward with the tree block mask equals TRL's tree_attention definition on random DFS pre-order tries. That definition is per-segment varlen causal attention over the gathered path, aligned bottom-right.
    • Gradients through the same mask_mod match exactly (fp64).
    • A worked dense-mask example, and rejection of layouts that are not in pre-order.
  • tests/test_async_grpo_trl_tree.py: through TRL's real TreeRow.pack / unpad_tree and the patched fused head:
    • With tree attention, the backbone sees the unique-token length (not the unrolled one).
    • Per-token logprobs, entropies and gradients equal each sample run alone, and the unroll path still passes the same check.
    • Rows without a fork keep packed_seq_lengths.
    • A compile failure falls back to the unroll.

Before this change the new tests fail (the tree path and TreeSegInfo do not exist). With it, 83 tests in the AsyncGRPO and PrefixGrouper suites pass on CPU with TRL 1.17.1 and TRL 1.18.0.

GPU results

Setup: TRL 1.18.0, transformers 5.23.0, torch 2.14.1, bf16 LoRA r=16 on every linear layer, Unsloth gradient checkpointing, Colab. The row is GRPO shaped: a 1536-token prompt and 8 completions of 384 tokens, half of them sharing a 128-token fork, giving 4231 unique tokens for 15360 unrolled (packing ratio 3.63). The baseline is the unroll path (UNSLOTH_ASYNC_GRPO_TREE_ATTENTION=0, the same code path as main). Arms run interleaved A1 B A2 for 5 rounds after warmup, on an exclusive A100 80GB.

model unroll A1 (s) unroll A2 (s) tree (s) speedup peak unroll peak tree
Qwen3-0.6B 0.4448 (0.4420 to 0.4467) 0.4433 (0.4421 to 0.4438) 0.3034 (0.3020 to 0.3101) 1.46x 2.39 GiB 1.71 GiB
Llama-3.2-1B-Instruct 0.6018 (0.6006 to 0.6025) 0.6016 (0.6005 to 0.6019) 0.2463 (0.2450 to 0.2465) 2.44x 4.68 GiB 3.12 GiB

Qwen3-4B (2 groups, 8399 unique / 30720 unrolled tokens, same A100): unroll 3.986 s / 3.987 s, tree 1.616 s (2.47x), peak 13.74 GiB -> 9.64 GiB.

On a T4 (fp16, sm75) the flex kernel fails its compile check on shared memory, so the row falls back to the unroll. Logprobs there are identical to the unroll, and the step time stays inside the A/A spread.

Times are the median fwd+bwd step, with min to max in brackets. The A/A spread between A1 and A2 is under 0.5%, and peak memory includes the weights. Every tree-arm forward ran the tree path and every unroll-arm forward ran the unroll (engagement counters 1 vs 0).

Correctness on a small forked row (527 unique tokens, 1152 unrolled), compared with each sample forwarded alone:

model, dtype path logp max abs grad rel L2
Qwen3-0.6B fp32 (L4) unroll 2.1e-5 2.2e-6
Qwen3-0.6B fp32 (L4) tree 1.7e-5 3.2e-6
Llama-3.2-1B fp32 (L4) unroll 2.1e-5 3.9e-6
Llama-3.2-1B fp32 (L4) tree 4.5e-5 4.4e-6

In bf16 both paths sit in the same noise band against the per-sample reference:

  • Qwen3: mean abs 0.026 for both paths, grad rel L2 0.014 (unroll) vs 0.016 (tree).
  • Llama: mean abs 0.012 (unroll) vs 0.011 (tree), grad rel L2 0.022 (unroll) vs 0.020 (tree).

Not covered

  • AMD gfx1151 (ROCm flex attention compile) and a full AsyncGRPOTrainer run with a vLLM server.
  • Rows whose paths exceed a sliding window, and models that do not apply prefix_seg_info (Gemma 3, MoE, hybrid GDN), keep the unroll.

…n fast backbones

TRL >= 1.17 packs AsyncGRPO rows as a prefix trie. Unsloth's fast backbones
ignored TRL's tree attention, so the rows were unrolled into one copy per
sample, forwarding every shared prefix once per sample while TRL budgets the
row by unique tokens.

The PrefixGrouper FlexAttention kernel now also takes a TreeSegInfo: in DFS
pre-order every segment's subtree is one contiguous token range, so kv token j
is visible to query q iff j <= q < reach_end[j]. Models whose decoder layers
apply prefix_seg_info run the trie once over its unique tokens; others, rows
with no fork, sliding-window paths and kernel compile failures keep the
unroll, which now reports its expansion once.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 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-20T10:52:47.602795Z ea09608 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: ea09608980

ℹ️ 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 6052964 into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the cg1-tree-attention branch November 20, 2026 13:06
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Nov 20, 2026
…, opt-in small tiles (unslothai#18645)

## Summary

On a T4 (sm75, 64 KB shared memory), the GRPO PrefixGrouper
FlexAttention kernel cannot compile. The 16-bit 128 / 64 tile needs
98304 B at head_dim 128, and the one-stage retry needs the same amount.
Today the compile check spends about 3 minutes failing, twice, at the
first training step. It then switches PrefixGrouper off.

This PR does two things, both inside the compile-options and
compile-check code in `unsloth/utils/prefix_grouper_kernel.py`:

1. **Skip the failing compile.** The skip applies on NVIDIA GPUs below
96 KB of shared memory, for fp16 / bf16 at head_dim >= 128 when the user
has not opted in. The check is skipped up front and PrefixGrouper
reports itself off with a clear reason. The result is the same as today
(the packed path), minus about 185 s of startup per run on T4.
2. **Opt-in small tiles.** `UNSLOTH_GRPO_PREFIX_GROUPER_SMALL_SMEM=1`
pins forward and backward tiles that fit 64 KB. The tiles are chosen
from the device's queried shared memory limit (Triton `max_shared_mem`,
falling back to the torch device properties), never from the GPU name.
The settings are forward 32 / 32 with 1 stage and 4 warps, and backward
32 / 32 / 32 / 32 with 1 stage and 8 warps. Every key is pass-prefixed
(`fwd_*`, `bwd_*`), so nothing leaks between passes. That gives one
compiled variant per call site, and the one-stage retry adds no second
one.

GPUs with 96 KB or more shared memory (sm80+, sm86 / sm89 / sm120, V100)
keep exactly the same `kernel_options` as before. ROCm keeps today's
behaviour; the opt-in tiles are available there for testing.

## Why the small tiles are not the default on T4

Triton 3.8 emits no tensor-core MMA on sm75. A plain `tl.dot` in fp16
compiles to 0 `mma.sync` and 256 `fma.rn.f32`, and the flex kernels
compile the same way. Attention therefore runs on CUDA cores:

- Isolated kernel test (Qwen3 attention shape, prompt 512 + 8 x 128):
flex forward + backward takes about 46 ms, against 9-11 ms for the
unshared SDPA rows.
- The shared forward wins on larger models, but the flex backward loses
that time again.

| T4, fp16, GRPO, 768-token prompt, 8 x 128 completions | PG off (A/A, 3
runs) | opt-in small tiles (3 runs) | delta |
|---|---|---|---|
| Qwen3-0.6B step time (s), run 1 | 4.939 / 4.964 / 4.968 | 6.908 /
6.935 / 7.025 | +39.7% (slower) |
| Qwen3-1.7B step time (s), run 1 | 10.214 / 10.279 / 10.290 | 9.982 /
9.992 / 10.022 | -2.8% |
| Qwen3-1.7B step time (s), run 2 (other VM) | 11.136 / 11.190 / 11.294
| 10.734 / 10.738 / 10.805 | -4.0% |

On 1.7B the logps phase drops from 1.30 to 0.87 s and the compute_loss
forward from 1.50 to 0.96 s, with peak memory going from 4.56 to 4.43
GB. Most of that is lost again in the backward.

Default path, Qwen3-0.6B, base vs head without the opt-in:
- **Steady state:** 5.56 / 5.67 s for base and 5.56 / 5.60 / 5.61 s for
head, against a PG-off A/A of 5.47 / 5.58 / 5.67 s. All of these are
inside the A/A spread.
- **Wall time per run:** 292 s for base and 107 s for head.

## Correctness on T4 (opt-in path)

The check uses real Qwen3 FastLanguageModel with LoRA. It compares the
PrefixGrouper stream against unshared per-row log-probs and LoRA grads,
and the flex kernel was called 56 times.

| | fp32 PG vs per-row | fp16 PG vs fp32 per-row | fp16 per-row vs fp32
per-row |
|---|---|---|---|
| 0.6B max abs dlogp | 3.2e-5 | 0.024 | 0.014 |
| 0.6B total rel grad | 6.4e-6 | 5.2e-3 | 5.1e-3 |
| 1.7B max abs dlogp | 2.5e-5 | 0.022 | 0.028 |
| 1.7B total rel grad | 7.1e-6 | 5.0e-3 | 4.5e-3 |

So the fp16 PrefixGrouper error is at the level of fp16 rounding of the
unshared path.

## Interaction with unslothai#18614 / unslothai#18616

The branch is rebased on current main, which includes both PRs. The
change touches only the tile selection, the small-smem skip and a shared
failure helper, so it merges without conflicts. The AsyncGRPO tree mask
(`TreeSegInfo`) and the Qwen3-MoE opt-in go through the same `_run_flex`
and `_checked_first_call`. On T4 they therefore get the same up-front
skip, and the same tiles under the opt-in.

## Tests

`tests/test_prefix_grouper_small_smem.py` covers the following:
- Options are unchanged for 96 KB and larger limits, with and without
the opt-in.
- The opt-in tiles are fully pass-prefixed and satisfy the template
static asserts.
- There is one variant only.
- The skip fires only for NVIDIA, 16-bit, head_dim >= 128, with no
opt-in.
- The limit is queried once per device, with the torch-properties
fallback.
- `_run_flex` passes the device options.
- On T4 the compile check runs no strict compile.

On main, 25 of the 27 tests fail. The two that pass assert the unchanged
default.
meefs pushed a commit to meefs/unsloth that referenced this pull request Nov 22, 2026
`pyproject.toml` capped TRL at `<=1.15.0`. That cap was never tied to a
known break: unslothai#13203 set it to the newest release the version matrix had
run, which was 1.15.0 at the time (TRL 1.15 shipped Oct 8). Since then
TRL shipped 1.16.0, 1.17.0, 1.17.1, 1.18.0, 1.18.1 and 1.18.2. AsyncGRPO
needs 1.17+, and tree packing for recurrent layers needs it too. Most of
the 1.16 to 1.18 support work already landed on main (unslothai#16220, unslothai#17714,
unslothai#18070, unslothai#18175, unslothai#18230, unslothai#18254, unslothai#18271, unslothai#18466, unslothai#18614 and others), and
the `HF=latest + TRL=latest` CI lane already runs TRL 1.18.2. Users
still could not install any of it because of the cap.

This PR raises the window to `trl>=0.18.2,!=0.19.0,<=1.18.2` and fixes
the four breaks I found going through 1.16 to 1.18.2 at transformers
5.18.0. Two of them are silent on 1.18: the patch anchor stops matching,
so the trainer still builds but does something different.

### Fixes

1. **AsyncGRPO on TRL 1.16.0 crashed on the first step** with `KeyError:
'tree_segment_parents'`. TRL 1.16 already packs AsyncGRPO rows as a
prefix trie, but it only sends `tree_kv_index` / `tree_cu_seqlens_q` /
`tree_cu_seqlens_k`. `tree_segment_parents` arrived in 1.17, and unslothai#18070
handled only the 1.17+ layout. The parents can be recovered from the K/V
paths: each segment's path is its parent's path plus its own tokens.
`_async_grpo_tree_segment_parents` does that, and on TRL >= 1.17 it
gives exactly the parents TRL sends (there is a test for this). The tree
tests now build TRL 1.16's forward kwargs when `unpad_tree` is missing,
instead of skipping.
2. **SFT with padding-free stopped truncating pre-tokenized datasets on
TRL 1.18.** The padding-free `max_length` block was only generated when
TRL's SFTTrainer had the "`max_length` is not enforced" refusal. TRL
1.18 removed that refusal because its own `_prepare_dataset` truncates.
Zoo's prep replaces that step, though, and leaves rows that already have
`input_ids` alone. So on 1.18 a pre-tokenized dataset trained at full
length: in the version-compat test, 1202-token rows went through against
a 128-token cap. The block is now generated on TRL >= 1.18 too. The 31
tests in `test_trl_padding_free_max_length.py` that skipped on 1.18 now
run there and pass.
3. **SFT `assistant_only_loss` lost its train_on_responses_only fallback
on TRL 1.18.** TRL 1.18 calls
`get_training_chat_template(processing_class,
require_prefix_preservation=False)`, and the anchor only matched the old
one-argument call. A chat template TRL cannot train, such as plain
ChatML without `{% generation %}` markers, went back to raising TRL's
`ValueError`. The anchor now accepts trailing arguments and keeps them.
4. **`UNSLOTH_ENABLE_FLEX_ATTENTION=1` stopped padding to the flex block
size on TRL >= 1.16.** TRL 1.16 changed the `pad_to_multiple_of` default
from `None` to `"auto"`, so `"auto"` now counts as unset too.

Two other changes looked like they might break things and are fine. TRL
1.18's `GKDTrainer` now generates inside `get_batch_samples`, which is
upstream's version of the fix the GKD patch applies to the older
`training_step`, so the patch has nothing to do there. TRL 1.18's new
`qwen3_6_v2` template renders like `qwen3_6` and shares its training
template. The tool-template test now accepts both instead of expecting a
single family.

### Cap sites moved together

- `pyproject.toml` (both trl lines),
`studio/backend/requirements/no-torch-runtime.txt`
- `notebooks-ci.yml` lane, and the `version-compat-ci.yml` ceiling lane
now pins `trl==1.18.2` with `transformers==5.18.0`
- `tests/test_trl_cap_sites.py`: `TESTED_CEILING = 1.18.2`,
`NEWLY_ADMITTED` adds 1.16.0 through 1.18.2, and
`ZOO_FLOOR_ADMITTING_TESTED_TRL_CEILING = None`

unsloth_zoo caps TRL at `<=1.15.0` too, and pip takes the lower of the
two caps. The matching zoo change is a one-line pyproject lift. Until a
zoo release ships with it, pip keeps users on 1.15.0, so the zoo floor
gate stays deferred.
`test_the_zoo_trl_deferral_expires_when_the_zoo_release_ships` fails as
soon as a published zoo admits 1.18.2, and that is the point to raise
the `unsloth_zoo` floor here.

### Testing

Everything below runs at transformers 5.18.0 (the pyproject ceiling).
The CPU suites use torch 2.10 CPU. The GPU jobs run on Colab, with main
and this PR on the same VM and the same deps, and only the unsloth tree
swapped.

**CPU, 307 TRL-touching test files:**

| tree | TRL | passed | failed | skipped |
|---|---|---|---|---|
| main | 1.15.0 | 5960 | 182 | 951 |
| main | 1.16.0 | 5969 | 178 | 946 |
| main | 1.17.1 | 5976 | 173 | 944 |
| main | 1.18.2 | 5941 | 180 | 972 |
| this PR | 1.15.0 | 5957 | 185 | 953 |
| this PR | 1.18.2 | 5982 | 167 | 946 |

163 test IDs fail in every one of these runs: CUDA-only kernels and gloo
cases on a CPU box, plus no torchao. Comparing by test ID, the only
tests that move with the TRL version are the four breaks above. The rest
of the delta is a few dozen gloo / timing / packing tests that flip
between xdist runs, and every one of those passes on both trees and both
TRL versions when rerun alone. The unsloth_zoo side (126 TRL-touching
test files) shows no failure specific to TRL 1.16.0 or 1.18.2.

**Flip tests** (this PR's tests run against main's code):

| test | TRL | main | this PR |
|---|---|---|---|
| AsyncGRPO trio (`test_async_grpo_trl_tree.py`, `_patch.py`,
`_fast_inference.py`) | 1.16.0 | 7 tree tests fail, 4 with `KeyError:
'tree_segment_parents'` | 68 passed |
| same | 1.15.0 / 1.17.1 / 1.18.2 | pass | 61 / 68 / 70 passed |
| `test_trl_padding_free_max_length.py` | 1.18.2 | 34 failed
(pre-tokenized rows not truncated, cap not consumed) | 155 passed |
| same | 1.15.0 / 1.17.1 | pass | 155 passed |
| `version_compat/test_sft_assistant_mask_fallback_trainer.py` (real
UnslothSFTTrainer, ChatML without markers, `assistant_only_loss=True`) |
1.18.2 | `ValueError: The chat template is not training-compatible` |
pass |
| same | 1.15.0 / 1.17.1 | pass | pass |
| `test_sft_assistant_mask_fallback.py::test_applies_to_installed_trl`
(real TRL source) | 1.18.2 | fail | pass |
|
`test_flex_pad_to_multiple_of_auto.py::test_trl_default_pads_to_the_flex_block`
| 1.17.1, 1.18.2 | fail (stays `None`) | pass (128) |
| same | 1.15.0 | pass | pass |
| `test_trl_cap_sites.py` + flex test | 1.15.0 / 1.17.1 / 1.18.2 | | 37
passed, 4 skipped (deferred zoo gate) |
| CI TRL discovery shim (taken from `consolidated-tests-ci.yml`) |
1.15.0 / 1.16.0 / 1.17.1 / 1.18.2 | | pass |

**GPU jobs** (`jobs/*.py --backend unsloth`, verdicts from
`jobs/compare.py`):

Final head, L4, one VM, TRL 1.15.0 / 1.16.0 / 1.18.2 x main / this PR:

| job | model | main vs PR at each TRL | PR, TRL 1.15.0 vs 1.16.0 /
1.18.2 |
|---|---|---|---|
| sft | Qwen3-0.6B | NO_REGRESSION x3 | NO_REGRESSION, same loss on
every step in all 6 runs |
| dpo | Qwen3-0.6B | NO_REGRESSION x3 | NO_REGRESSION, same loss on
every step in all 6 runs |
| vision_sft `--tiny` | tiny Qwen2.5-VL | NO_REGRESSION x3 |
NO_REGRESSION, same loss on every step in all 6 runs |
| grpo (notebook preset) | Qwen3-0.6B-Base | NO_REGRESSION x3 |
NO_REGRESSION (sampled rollouts, within the main-vs-main spread) |

Earlier runs used the first commit. The later commits change AsyncGRPO
tree rows and SFTTrainer init, and the table above covers SFTTrainer
init:

| job | where | main vs PR | PR, TRL 1.15.0 vs 1.18.2 |
|---|---|---|---|
| grpo `--fast-inference` (vLLM 0.32.0), Qwen3-0.6B-Base | G4 |
NO_REGRESSION at 1.15.0 and 1.18.2 | NO_REGRESSION |
| sft / grpo / dpo `--tiny` | A100 | NO_REGRESSION at 1.15.0 and 1.18.2
| same loss on every step |

**AsyncGRPO, `fast_inference=True`** (vLLM 0.32.0, Qwen3-0.6B, LoRA
r=16, 6 steps, RTX PRO 6000):

| TRL | main | this PR |
|---|---|---|
| 1.16.0 | crashes: `KeyError: 'tree_segment_parents'` | trains 6 steps,
mean reward 0.93 |
| 1.17.1 | trains 6 steps, mean reward 0.91 | trains 6 steps, mean
reward 0.91 |
| 1.18.2 | trains 6 steps, mean reward 0.92 | trains 6 steps, mean
reward 0.82 (one sampled 6-step run) |

### Not covered

- No published unsloth_zoo admits TRL > 1.15.0 yet, so users only get
1.16+ after the zoo lift ships and the floor here moves.
- `unslothai/notebooks` pins TRL on its own side (`PIN_TRL`), and so
does Studio's single-env install (`trl==0.23.1`). This PR does not touch
either.
- TRL 1.18 with transformers 5.23+ is covered only by the existing
`HF=latest` lane. pyproject still caps transformers at 5.18.0.
- No multi-GPU (FSDP2 / DDP) GRPO or AsyncGRPO run on 1.16 to 1.18. The
CPU gloo tests cover what they can.
- TRL 1.17.0, 1.18.0 and 1.18.1 were not run on their own. 1.17.1 and
1.18.2 are patch releases on top of them.
- Windows, macOS / MLX and AMD were not run.

Companion: unslothai/unsloth-zoo#2656 raises the zoo ceiling the same
way; merge it first.
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