Skip to content

[rl] Qwen3.5 support in the RL experiment - #3757

Closed
yichuan-w wants to merge 6 commits into
pytorch:mainfrom
yichuan-w:yichuan/qwen3_5-rl-support
Closed

yichuan-w wants to merge 6 commits into
pytorch:mainfrom
yichuan-w:yichuan/qwen3_5-rl-support

Conversation

@yichuan-w

Copy link
Copy Markdown
Member

Wires the upstream Qwen3.5 model (torchtitan/models/qwen3_5/, #3371) into
the RL experiment. Addresses #3756.

Qwen3.5 is a hybrid model: most layers are GatedDeltaNet (gated
linear-attention/SSM) with a full-attention layer every full_attention_interval.
That breaks several RL-stack assumptions, fixed here:

Changes

  • Recipe: alphabet_sort rl_grpo_qwen3_5_4b_varlen + _qwen3_5_rl_model_registry
    (lm_head fp32 cast, like the qwen3 wrapper).
  • Trainer / generator attention validation (actors/trainer.py,
    actors/generator.py): use model.first_attention instead of assuming
    layers[0] carries an attention config (layer 0 of Qwen3.5 is GatedDeltaNet).
  • vLLM wrapper / registry (models/vllm_wrapper.py, models/vllm_registry.py):
    derive head dims from the first full-attention layer; skip linear
    (GatedDeltaNet) layers when swapping inner_attention for the vLLM
    paged-attention backend.
  • parallelize_qwen3_5: add skip_dp (FSDP forward hooks are incompatible
    with vLLM's inference_mode), matching parallelize_qwen3.
  • qwen3_5 model: let forward run text-only (special_tokens=None) by
    reading the image/video token ids only when pixel values are present (it raised
    TypeError otherwise — the model could not run text-only at all).
  • renderer: map qwen3_5 -> "auto" (resolve the chat template from the
    tokenizer).

Status / known limitation (why this is a draft)

Config build is verified (spec qwen3_5, 32 layers, first_attention resolves to
the full-attention layer). The open risk is the generator: GatedDeltaNet has no
recurrent-state cache in the vLLM TorchTitanCausalLM wrapper
, so generation
recomputes the linear-attention layers over the full sequence each decode step.
This needs end-to-end validation (logprob drift via the bit_wise/* metrics)
before on-policy training can be trusted. vLLM has native Qwen3.5 support, so an
alternative is to special-case the generator to vLLM-native for these layers.

Requires flash-linear-attention (already a qwen3_5 dep via
.ci/docker/requirements-vlm.txt).

Wire the upstream Qwen3.5 model (torchtitan/models/qwen3_5) into the RL
experiment. Qwen3.5 is hybrid: GatedDeltaNet (linear-attention) layers with a
full-attention layer every full_attention_interval.

- alphabet_sort: add rl_grpo_qwen3_5_4b_varlen + _qwen3_5_rl_model_registry.
- Trainer/generator attention validation uses model.first_attention (hybrid-safe)
  instead of assuming layers[0] carries an attention config.
- vLLM wrapper/registry: derive head dims from the first full-attention layer and
  skip linear (GatedDeltaNet) layers when swapping inner_attention for the vLLM
  paged-attention backend.
- parallelize_qwen3_5: add skip_dp (FSDP is incompatible with vLLM
  inference_mode), matching parallelize_qwen3.
- qwen3_5 model: let forward run text-only (special_tokens=None) by reading the
  image/video token ids only when pixel values are present (it crashed before).
- renderer: map qwen3_5 -> "auto" (resolve the chat template from the tokenizer).

Config builds verified. KNOWN LIMITATION: GatedDeltaNet has no recurrent-state
cache in the vLLM TorchTitanCausalLM wrapper, so generation recomputes the
linear-attention layers full-sequence each decode step; logprob drift
(bit_wise/*) must be validated before trusting on-policy training.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 24, 2026
@Jeremalloch

Copy link
Copy Markdown
Contributor

This is awesome! I have a PR for adding varlen attention to Qwen 3.5 that I plan on opening today, which should help close another one of the gaps between Qwen 3.5 and Qwen 3 (the latter of which uses varlen iirc to handle a skewed rollout length distribution)

Switch the Qwen3.5 RL generator to vLLM's native model and make the loop run
end to end. The shared TorchTitanCausalLM wrapper has no recurrent-state cache
for GatedDeltaNet decode, so on-policy generation was wrong; vLLM's native
Qwen3.5 model brings the GDN mamba state cache + hybrid KV allocator.

Generator (torchtitan/experiments/rl/actors/generator.py):
- Add a backend knob: "torchtitan_wrapper" (default, unchanged) vs "vllm_native".
  On the native path we skip register_to_vllm / config_format / attention_config
  and let vLLM resolve its own model class from the checkpoint's architectures.
- Add vllm_additional_config passthrough (e.g. gdn_prefill_backend=triton).
- Weight sync on the native path: pull the trainer's torchtitan state dict from
  TorchStore, convert to HF via the model's state_dict_adapter, and call the
  vLLM model's load_weights.
- Fix an undefined `inner_attn` NameError in the EngineArgs attention_config.

Fixes:
- vllm_wrapper.py: the _node_ref monkeypatch took 1 arg but vLLM's _node_ref now
  takes (arg, consts, const_index); forward *args/**kwargs so it is signature-
  compatible (this also unblocks the native compile path).
- renderer.py: map qwen3_5 -> the dedicated "qwen3.5" renderer ("auto" only
  matches a known HF repo id and raises for this VLM family on a local path).
- qwen3_5/__init__.py: set enable_weight_tying=True for the tied configs
  (0.8B/2B/4B; HF tie_word_embeddings=true) and use skip_param_init for their
  tok_embeddings (the shared weight is initialized once via lm_head, matching
  the llama3 convention). Without tying, the HF DCP load fails on a missing
  lm_head.weight.
- qwen3_5/model.py: narrow Qwen35Model.Config.norm to OffsetRMSNorm.Config so
  tyro can parse the RL config; assert special_tokens is present before reading
  image/video ids (and fix the video-branch assert message).

Config:
- rl_grpo_qwen3_5_4b_varlen uses the vLLM-native backend and the validated
  working settings (generator TP=1, cudagraph off, compile off) with TODOs for
  the follow-ups (generator TP>1 custom all-reduce under Monarch; trainer
  torch.compile + fla GatedDeltaNet under activation checkpointing).

Tests (CPU): generator backend default + recipe wiring, the qwen3_5 to_hf
weight-tying skip, and the qwen3_5 -> qwen3.5 renderer mapping.

Validated end to end (3 GPUs): pre-training validation + 3 GRPO steps +
checkpoint save, with non-trivial rewards. Known limitation: the native
generator's GatedDeltaNet decode (recurrent) and the trainer (chunk) use
different kernels, so logprobs are not bitwise aligned; GRPO's importance ratio
corrects for the drift (bit_wise/* measures it).
@yichuan-w

Copy link
Copy Markdown
Member Author

Pushed 834fe8e1: switch the Qwen3.5 RL generator to vLLM's native model and get the loop running end to end.

Why: the shared TorchTitanCausalLM wrapper has no recurrent-state cache for GatedDeltaNet decode, so on-policy generation was wrong. vLLM's native Qwen3.5 model brings the GDN mamba state cache + the hybrid KV/mamba allocator.

What:

  • generator: add a backend knob (torchtitan_wrapper default / vllm_native) + a vllm_additional_config passthrough (e.g. gdn_prefill_backend=triton). On the native path we skip register_to_vllm/config_format/attention_config and let vLLM resolve its own model class; weight sync pulls the trainer's torchtitan state dict, converts it to HF via the model's state_dict_adapter, and calls the vLLM model's load_weights. Also fixes an undefined inner_attn NameError.
  • vllm_wrapper: the _node_ref monkeypatch took 1 arg but vLLM's _node_ref now takes 3; forward *args/**kwargs (also unblocks the native compile path).
  • renderer: map qwen3_5 -> the dedicated qwen3.5 renderer (auto only matches a known HF repo id and raises for this VLM family on a local path).
  • qwen3_5: enable_weight_tying=True for the tied configs (0.8B/2B/4B; HF tie_word_embeddings=true) + skip_param_init for their tok_embeddings; otherwise the HF DCP load fails on a missing lm_head.weight. Narrow Qwen35Model.Config.norm to OffsetRMSNorm.Config so tyro can parse the RL config.
  • CPU tests: generator backend default + recipe wiring, the qwen3_5 to_hf weight-tying skip, and the qwen3_5 -> qwen3.5 renderer mapping.

Validated end to end on 3 GPUs: pre-training validation + 3 GRPO steps + checkpoint save, non-trivial rewards.

Known limitation: the native generator's GatedDeltaNet decode (recurrent) and the trainer (chunk) use different kernels, so logprobs are not bitwise aligned; GRPO's importance ratio corrects for the drift (bit_wise/* measures it). This is fundamental to linear attention (unlike full attention, whose prefill and decode share one kernel), so it can't be made bitwise the way the attention wrapper path is.

Follow-ups (default-off in the recipe): generator TP>1 trips vLLM's custom all-reduce under Monarch external_launcher; trainer torch.compile can't trace the fla GatedDeltaNet op under activation checkpointing; characterize the logprob drift (mean vs outliers).

@hanabenko

hanabenko commented Jun 26, 2026 •

Copy link
Copy Markdown

I pulled this PR locally and tested the Qwen3.5 RL changes.

Local checks that passed:

  • pre-commit run --show-diff-on-failure --files <changed files>
  • python3.10 -m py_compile on the PR-touched Python files
  • CPU unit tests:
    • pytest -q tests/unit_tests/observability/test_structured_logging.py -> 77 passed
    • pytest -q tests/unit_tests/test_override.py -> 26 passed
    • pytest -q tests/unit_tests/test_configurable.py -> 11 passed

I also found a few remaining stale Qwen3.5 hybrid-attention assumptions and pushed a small follow-up patch here:
https://github.com/hanabenko/torchtitan/tree/fix/qwen35-rl-pr-checks

The local patch covers:

  • RL generation now respects generator.backend == "vllm_native" instead of always routing through the
    TorchTitan vLLM wrapper.
  • Batch-invariance attention conversion now skips Qwen3.5 DeltaNet layers where attention is None.
  • RL config/test code now uses first_attention instead of assuming layers[0].attention exists.
  • Added regression coverage that Qwen3.5 layer 0 is DeltaNet (attention is None) and that first_attention
    finds a real full-attention layer.

Local limitations:

  • I could not run the broader Qwen3.5/RL pytest selection locally because my macOS arm64 environment cannot
    install triton, and test collection reaches Triton-dependent imports.
  • I did not run GPU/vLLM integration locally.

Based on the local checks and the fixes above, I think this PR is in a healthier state and ready for a GPU/vLLM training smoke test, especially to validate the vLLM-native generator path and TorchTitan -> HF/vLLM weight sync.

…ce under Monarch

vLLM's custom (CUDA-IPC) all-reduce throws "invalid argument" when the
generator runs tensor-parallel under Monarch's external_launcher: the TP
workers are spawned by Monarch's proc mesh, so the cross-process CUDA IPC
peer-handle exchange (at communicator construction) never sets up. This
blocked any generator TP>1.

Fix: at tensor_parallel_degree>1, set disable_custom_all_reduce=True so vLLM
falls back to the pynccl all-reduce (correctness-neutral; reuses the NCCL
group Monarch already established). No-op at TP=1, where no all-reduce is
built. Not model-specific -- applies to any model whose vLLM generator runs
TP>1 in this RL loop. The trainer's own TP all-reduce uses torchtitan/NCCL
and is unaffected.

Validated: Qwen3.5-4B, trainer TP=2 + generator TP=2, 3 GRPO steps, exit 0
(vLLM dispatch drops CUSTOM, uses [SYMM_MEM, PYNCCL]). The 4B recipe still
defaults generator TP=1 (fits one GPU); this only affects opt-in TP>1.

Fallback cost (isolated all-reduce, TP=2, hidden=2560): custom ~20us vs
pynccl ~100-130us for decode-size messages; end-to-end impact is far smaller
(all-reduce interleaves with compute) and only applies when generator TP>1 is
actually needed (model does not fit one GPU).
…ude)

verify_logprob_identity reported only a signed mean (positive/negative drift
cancels) and a single-token max, neither of which shows the typical per-token
generator-vs-trainer logprob drift. Add logprob_diff/abs_mean = mean(|diff|)
over loss-mask tokens, pre-normalized by the global token count so the existing
SUM-reduce over the loss-mesh reconstructs the global value (same pattern as
logprob_diff/mean). Surface it on the train console line.

Why it matters for the GDN path: the vLLM-native GatedDeltaNet generator
(chunk prefill + recurrent decode) and the fla trainer (chunk over the full
sequence) use different kernels, so logprobs are not bitwise aligned. abs_mean
makes the drift visible; GRPO's importance ratio corrects it.

Measured (alphabet_sort, 6 GRPO steps, generator TP=1):
- GDN Qwen3.5-4B (vllm_native): abs_mean 0.03-0.23, max 6-13 -- a heavy tail.
  The typical token is fine (sampled median ~1e-3); a few outlier tokens
  (saturated GDN gates) dominate the mean.
- Dense Qwen3-1.7B (torchtitan_wrapper, same code as the trainer + a shared
  full-attention kernel): abs_mean ~0.002, max <2.3, median 0 (near bitwise).
So the large drift is inherent to the GDN/vLLM-native path, not the RL loop.
Bitwise (zero-logp) on GDN would need batch-invariant + deterministic
recurrent kernels shared by both sides.
Trim verbose and cross-site-duplicated comments/docstrings added by the
Qwen3.5 RL work down to the load-bearing 'why' (mechanism/root-cause detail
belongs in the PR/commit, not the source). Biggest cuts: the 4B recipe
docstring, the disable_custom_all_reduce note, and the backend field docs.

Replace the two hand-rolled 'first full-attention layer' scans in
vllm_registry.py and vllm_wrapper.py with Decoder.Config.first_attention --
the same property this PR already adopts in trainer.py/generator.py, so all
four sites now share one source of truth. Runtime-equivalent for every
RL-registered model (each layer config has an .attention attribute) and
lint-safe (experiments/ is excluded from pyrefly).

No behavior change. pre-commit clean (pyrefly 0 errors); CPU tests pass.
Reconcile the Qwen3.5 RL additions with upstream's RL rewrite (RLTrainer ->
Controller/AsyncLoopConfig, drift metrics moved into the loss, new generator
weight-sync path). Semantic resolutions:

- config_registry: port rl_grpo_qwen3_5_4b_varlen + _qwen3_5_rl_model_registry
  onto Controller.Config/AsyncLoopConfig/ValidationConfig, InterGeneratorRouter,
  and ChunkedLossWrapper(loss_fn=GRPOLoss) (matching sibling recipes).
- trainer.py: take upstream's removal of verify_logprob_identity/PartialLogprobDrift
  (drift now computed in the loss) and the generic loss_metrics reduce; KEEP the
  hybrid-safe first_attention (qwen3_5 layer 0 is GatedDeltaNet, .attention=None).
- dapo.py: re-home the bit_wise/logprob_diff/abs_mean metric (was in trainer's
  verify_logprob_identity) next to the other bit_wise metrics.
- generator.py: keep vllm_native backend + native weight sync; adopt upstream's
  spmd_types state-dict branch, fused-module load_state_dict reload,
  register_to_vllm(override=), VLLM_USE_BREAKABLE_CUDAGRAPH, and
  max_num_batched_tokens; gate the custom cudagraph config on the wrapper path.
- vllm_wrapper.py: drop the _node_ref monkeypatch (upstream removed the infra);
  keep the linear-attention passthrough + first_attention reuse.
- processor.py: take upstream's trimmed console list (metric still logged to
  W&B/TB via the loss).
@yichuan-w
yichuan-w marked this pull request as ready for review July 1, 2026 03:11
checkpoint_config=config.checkpoint,
override=config.override,
)
if native:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, this looks interesting.

While it's not using the unified modeling approach, so might need to think about whether we want to merge, but does it just work?

cc @wwwjn @felipemello1

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, if unifed model, that will be a long story...
it just works for now, which I think is ok, and we can simply patch all linear attn kernel in the future
Now it is FLA chunked for training , vLLM kernel for generation: recurrent for decode, chunked for prefill

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if unifed model, that will be a long story...

Why? We have Qwen3.5 in torchtitan and did you meet some issue trying to enable Qwen3.5 in RL?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wwwjn You need "kv cache" handling for linear attention. Remember that we plugged in vllm attention inside our model, but we are not doing that for linear attention.

Comment on lines +311 to +312
data_parallel_degree=1,
tensor_parallel_degree=1,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be good to test different parallelisms and perf.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure

@tianyu-l
tianyu-l requested a review from felipemello1 July 1, 2026 03:23
checkpoint_config=config.checkpoint,
override=config.override,
)
if native:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if unifed model, that will be a long story...

Why? We have Qwen3.5 in torchtitan and did you meet some issue trying to enable Qwen3.5 in RL?

model_config=model_spec.model,
hf_assets_path=model_path,
)
else:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this path should be working but super slow because of lacking GDN mamba state cache + the hybrid KV/mamba allocator? Maybe a n00b q, van we let our model use vllm's mamba state cache management , like how we plug our attention kernel with kv cache managed by vllm

Comment on lines +811 to +815
if (
config.cudagraph.enable
and config.cudagraph.mode == "FULL_AND_PIECEWISE"
):
os.environ["VLLM_USE_BREAKABLE_CUDAGRAPH"] = "1"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This par should already covered by main, please rebase

# Enables RequestOutput.metrics, so generator metrics can be returned
disable_log_stats=False,
)
# vLLM's custom CUDA-IPC all-reduce fails under Monarch's

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this happens for all the model in RL? If so, the vllm custom all reduce is not bringing any gain. Can you help check this?

@hanabenko

Copy link
Copy Markdown

Hi! Is there an update on the remaining blockers for this PR? I’m hoping to resume the Qwen3.5 RL experiments once it’s ready, and I’d be happy to help with any additional testing if useful. 🙏

@hanabenko

Copy link
Copy Markdown

Hi! Is there an update on the remaining blockers for this PR? I’m hoping to resume the Qwen3.5 RL experiments once it’s ready, and I’d be happy to help with any additional testing if useful. 🙏

It looks like #3957 may provide the unified Qwen3.5 RL path discussed in the reviews here. Is #3957 expected to supersede this PR, or are there still changes from #3757 that will need to land separately?

@wwwjn

wwwjn commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Hi! Is there an update on the remaining blockers for this PR? I’m hoping to resume the Qwen3.5 RL experiments once it’s ready, and I’d be happy to help with any additional testing if useful. 🙏

It looks like #3957 may provide the unified Qwen3.5 RL path discussed in the reviews here. Is #3957 expected to supersede this PR, or are there still changes from #3757 that will need to land separately?

Hi @hanabenko the #3957 PR is based on this PR and we will aim for iterating on #3975 instead

@hanabenko

Copy link
Copy Markdown

Hi! Is there an update on the remaining blockers for this PR? I’m hoping to resume the Qwen3.5 RL experiments once it’s ready, and I’d be happy to help with any additional testing if useful. 🙏

It looks like #3957 may provide the unified Qwen3.5 RL path discussed in the reviews here. Is #3957 expected to supersede this PR, or are there still changes from #3757 that will need to land separately?

Hi @hanabenko the #3957 PR is based on this PR and we will aim for iterating on #3975 instead

Thanks for the update and for continuing to iterate on this!

tianyu-l pushed a commit that referenced this pull request Jul 27, 2026
## Summary

Adds varlen attention support to the Qwen3.5 GatedDeltaNet
(linear-attention) path. Packed multi-document batches now run the FLA
variable-length kernels with per-document `cu_seqlens`, so each document
is processed independently within a packed sequence instead of padding
out to full attention.


I've added this for in house work at my job, where we have quite varied
sequence lengths on training data (in a way that packing is
insufficient). I think this would also benefit [efforts to add Qwen3.5
to TorchTitan RL](#3757)
(where I believe Qwen3 uses varlen by default).

### How to Review
The branch is organized as two commits for review:

1. Add variable-length attention support to Qwen3.5 GatedDeltaNet
2. Adopt Shazeer style shape-suffix tensor names in Qwen3.5
a. No-op rename of the Qwen3.5 model tensors to the shape-suffix
convention (`x -> x_BLD`,
   `q/k/v -> xq_BLNK/xk_BLNK/xv_BLNV`, ...)
b. I have seen PR's landing in torchtitan the last couple weeks making
this change. If this is unwanted, I'm happy to remove this from the PR.

## Details

- `VarlenMetadata` carries host-side `cu_seq_q` offsets (opt-in via
`include_host_offsets`); `GatedDeltaNet` builds a CPU `cu_seqlens`
tensor once
per forward, so the FLA chunked / fused-recurrent kernels and the causal
conv
  avoid per-call device-to-host syncs.
- `GatedDeltaNet` / `GatedDeltaKernel` / the causal conv thread
`cu_seqlens`,
`cu_seqlens_host`, and `cu_seqlens_cpu`, flattening the batch to a
single
  packed sequence for the kernels.


## Testing

### Integration
I ran the following tests on an H100 node for 10 steps each:

- 2-GPU: `qwen3_5_tp+varlen_attn+per_op_sac`
- 4-GPU: `qwen3_5_fsdp+varlen_attn+per_op_sac`
- 8-GPU combined smoke: Qwen3.5 varlen + SelectiveAC, `dp_shard=4`,
`tp=2` (note this had a long first-step Triton compile)

### New Unit Tests
I added new unit tests to `tests/unit_tests/test_qwen3_5_deltanet.py`
that assert that the varlen
forward is asserted equal to running each document independently and
stitching
the outputs back. Covered on the `torch_native` reference (CPU, exact,
atol 1e-6) and on both production
FLA kernels (`fla_chunked`, `fla_fused_recurrent`) on GPU:

## Notes / follow-ups
- A `torch_native` varlen reference path was added for numerical
testing.
- The qwen3_5 requirements was updated to use `-r` so the shared VLM
requirements (flash-linear-attention) are actually installed.
- All varlen behavior is gated behind `cu_seqlens is not None`; the
non-varlen
path is a no-op refactor (the extracted `_local_map_conv` reproduces the
previous inline `local_map`, same placements/grad placements), so
existing
non-varlen Qwen3.5 behavior is unchanged. **Note:** Left to CI to
confirm.
- The Qwen3.5 feature tests run on the default SPMD backend, not
`full_dtensor`,
  because `qwen3_5/parallelize.py` raises `NotImplementedError` under
  `full_dtensor` (TODO to lift the exclusion once supported).
- The integration harness asserts process completion (exit code); the
unit
equivalence tests are what assert numerical correctness of the varlen
path.

---------

Co-authored-by: Shuhua Yu <[email protected]>
@tianyu-l tianyu-l closed this Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants