Skip to content

AsyncGRPO tree packing for Qwen3.5 / Qwen3.6 / Qwen3-Next (gated DeltaNet hybrids) - #18817

Merged
danielhanchen merged 10 commits into
mainfrom
grpo-tree-recurrent
Nov 22, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
grpo-tree-recurrent

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

#18809 (TRL cap lift) is merged, so this now targets main; AsyncGRPO tree packing needs TRL >= 1.17.

Stacked on #18809 (TRL cap lift), since tree packing for recurrent layers needs TRL >= 1.17.

TRL 1.17+ packs AsyncGRPO rows as a prefix trie and ships tree kernels for gated DeltaNet layers (trl.kernels.tree_gated_delta_rule): each segment starts from its parent's recurrent state, and the short conv reads the tokens on its own root path. TRL hooks them in with patch_tree_gdn(model), which rebinds causal_conv1d_fn and torch_chunk_gated_delta_rule in sys.modules[type(model).forward.__module__]. Through Unsloth that lookup misses in both cases:

  1. LoRA models are refused at init. A PEFT model's forward lives in peft.peft_model, which has neither function, so AsyncGRPOTrainer raises ValueError: PeftModelForCausalLM has ['linear_attention'] layers.... With fast_inference=True LoRA is the only mode, so AsyncGRPO could not run on Qwen3.5 at all.
  2. Full fine-tuning would leak across branches silently. Unsloth's compiled unsloth_compiled_module_qwen3_5.py defines its own Qwen3_5GatedDeltaNet_forward and imports transformers' __name__. TRL's lookup lands on transformers' module and patches that, while the layers read the compiled module, whose hub kernels drop the tree_* kwargs and scan the packed row as one sequence. On Qwen3.5-0.8B that shifts per-token log-probs by 0.99 on average (max 6.5).

Fix

  • patch_trl_async_grpo wraps TRL's patch_tree_gdn. It unwraps PEFT, runs TRL's own patch, then finds the functions that actually look up the two kernels (each layer class's forward, through its wrappers and the module-level forward it calls), and rebinds both names in their own globals with TRL's tree kernels. It counts engagement in _ASYNC_GRPO_TREE_GDN_COUNTS.
  • It still refuses what TRL refuses: if TRL's kernels do not import, or a mixer calls causal_conv1d_fn but scans with another kernel (Mamba2, KDA), it returns False and TRL raises.
  • The block-compile GDN adapters (_gdn_chunk_adapter, _causal_conv1d_adapter) step aside for tree calls.
  • Nothing changes on TRL <= 1.16 or for models without gated DeltaNet layers.

Testing

tests/test_async_grpo_tree_gdn.py (CPU, fp32) uses a tiny random Qwen3.5 wrapped in LoRA, with the GDN forward moved into a separate namespace the same way the compiled file does it. TRL's Triton scan is replaced by a per-segment reference, and TRL's tree conv runs as is. It checks that TRL's own patch misses the PEFT and compiled cases, that the packed tree row matches each sample run alone (log-probs and grads), that changing one branch leaves every other sample untouched, that rows without a tree are unchanged, and the refusal and adapter guards. On TRL 1.15.0 / 1.17.1 / 1.18.2 the AsyncGRPO CPU files give 98 passed / 113 passed / 115 passed with no failures.

GPU, Colab L4, TRL 1.18.2, transformers 5.18.0, Unsloth-loaded Qwen3.5 + LoRA r16, bf16. TRL's own parity protocol (two prompt groups, completions forking mid-way). "Alone" means each sample run on its own. "Flat" means the same tokens packed with nothing shared.

tiny Qwen3.5 Qwen3.5-0.8B
main (#18809) ValueError at init ValueError at init
tree GDN calls per forward 1 / 1 (1 GDN layer) 18 / 18 (18 GDN layers)
mean logp error vs fp32 CPU oracle (plain transformers + same adapter): tree / alone / flat 0.00031 / 0.00032 / 0.00032 0.0226 / 0.0212 / 0.0216
same row with the GDN layers not tree-routed (what full fine-tuning got) 0.989 mean, 6.50 max vs alone
other samples' logps after changing one branch bit-identical bit-identical
GRPO loss tree / alone / flat -0.02249 / -0.02267 / -0.02225 0.7146 / 0.7047 / 0.7708
grad rel error vs alone: tree / flat 0.0096 / 0.0094 0.065 / 0.228
grad of summed logps, rel error vs alone: tree / flat 0.0108 / 0.0100

The tree row is as close to the per-sample result as plain packing is, which is just bf16 noise. On 0.8B the GRPO loss amplifies that noise because old_log_probs = -12 puts tokens right at the IS clip edge, and the flat row moves the loss more than the tree row does.

Speed, compute_loss + backward of one micro-batch on the same L4, Qwen3.5-0.8B LoRA. 2 groups x (512-token prompt + 8 x 256-token completions) is 12288 raw tokens, and the tree row has 5134 unique tokens. 5 rounds, order swapped each round, two interleaved series per arm:

median s A/A spread raw tokens/s peak activation MiB
flat (no sharing) 2.43 0.5% 5050 1251
tree 1.13 0.04% 10885 563

End to end, AsyncGRPO with fast_inference=True (vLLM 0.32.0) on Qwen3.5-0.8B on an L4, 8 steps:

result
main (#18809) ValueError at AsyncGRPOTrainer(...)
this PR trains 8/8 steps, packing ratio 3.6x to 4.8x per step, mean reward 0.62, peak 5.6 GiB

Not covered here: Qwen3.6 (MoE), Qwen3-Next and OLMo-Hybrid take the same code path but got no GPU run. GPU runs were TRL 1.18.2 only, with no multi-GPU and no AMD.

TRL 1.16 changed the pad_to_multiple_of default from None to "auto", so
UNSLOTH_ENABLE_FLEX_ATTENTION no longer padded to the flex block size on
TRL >= 1.16. Treat "auto" as unset there.

Raise trl to <=1.18.2 in pyproject (both sites), the Studio runtime mirror,
the notebooks CI lane and the version-compat ceiling lane, and move
TESTED_CEILING with it. The zoo floor gate is deferred until an unsloth_zoo
release admits trl 1.18.2.
TRL 1.16 packs AsyncGRPO rows as a prefix trie but sends only
tree_kv_index / tree_cu_seqlens_*; tree_segment_parents arrived in 1.17.
On an Unsloth backbone every such row went through _forward_tree_unrolled,
which read tree_segment_parents and raised KeyError. Recover the parents
from the K/V paths (each path is the parent's path plus the segment's own
tokens), matching what TRL 1.17+ sends. The tree tests now build TRL 1.16's
forward kwargs when unpad_tree is absent instead of skipping.
… TRL 1.18

TRL 1.18 calls get_training_chat_template(processing_class,
require_prefix_preservation=False), so the anchor that wraps the call only
matched TRL <= 1.17. On 1.18 a chat template TRL cannot train (every
Unsloth-edited one without generation markers) raised TRL's ValueError
again instead of falling back to Zoo's response masks. Match the call with
any trailing arguments and keep them.

The tool template test now accepts TRL 1.18's qwen3_6_v2 family, which
renders like qwen3_6 and shares its training template.
The padding-free max_length block was generated only when TRL's SFTTrainer
carried the "max_length is not enforced" refusal. TRL 1.18 removed that
refusal, since its own _prepare_dataset truncates, but Zoo's prep replaces
that step and leaves rows that already have input_ids alone. On 1.18 a
pre-tokenized dataset therefore trained at full length: 1202-token rows
against a 128-token cap in the version-compat test. Generate the block on
TRL >= 1.18 as well, so every 1.x release gets the same cap.
…ent Triton

TRL <= 1.15 imports its fused LM head kernel only when Triton imports and
leaves trl.trainer.utils._ChunkedLogProbFunction = None otherwise, so on
Windows test_packed_row_guard_engages died inside TRL's own _fused_forward
('NoneType' object has no attribute 'apply'). Same failure on main; TRL
1.16+ imports the kernel unconditionally.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 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-22T01:26:36.651165Z adcf9e1 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. 🎉

Reviewed commit: f072d14e43

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

Base automatically changed from trl-cap-1-18 to main November 22, 2026 01:24
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: adcf9e1a53

ℹ️ 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 0d63a57 into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the grpo-tree-recurrent branch November 22, 2026 03:35
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…rom #18817 (#18830)

## Summary

`Source lint` (Lint CI) and the risky loader test in `workflow-trigger
lint` are red on `main` since #18817:

```
1 risky loader call site(s) not in the baseline:
  unsloth/models/rl.py:5527  [dynamic-import] import_module
```

#18817 (AsyncGRPO tree packing for gated DeltaNet hybrids) loads TRL's
tree gated DeltaNet kernels with `importlib.import_module` over two
candidates: the literal `trl.kernels.tree_gated_delta_rule` (TRL >=
1.18), and on TRL 1.17 the sibling of the module TRL's own packing
function lives in (`original.__module__`). Neither name comes from user
input, a config or a downloaded file, so the call is fine and the lint
just needs it recorded. Spelling the 1.17 path out literally would tie
it to one TRL layout and lose the fallback.

## Fix

`python scripts/lint_risky_loaders.py --update` (the `rl.py`
dynamic-import entry goes from one call site to two), with that entry's
reason rewritten to cover both loads.

## Testing

- `python scripts/lint_risky_loaders.py`: all 123 call sites recorded;
with `main`'s baseline it still exits 1 on this site.
- `tests/security/test_lint_risky_loaders.py`: 46 passed.
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