Repository navigation
Conversation
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.
|
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).
|
Pushed Why: the shared What:
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 ( Follow-ups (default-off in the recipe): generator TP>1 trips vLLM's custom all-reduce under Monarch |
|
I pulled this PR locally and tested the Qwen3.5 RL changes. Local checks that passed:
I also found a few remaining stale Qwen3.5 hybrid-attention assumptions and pushed a small follow-up patch here: The local patch covers:
Local limitations:
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).
| checkpoint_config=config.checkpoint, | ||
| override=config.override, | ||
| ) | ||
| if native: |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
@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.
| data_parallel_degree=1, | ||
| tensor_parallel_degree=1, |
There was a problem hiding this comment.
Would be good to test different parallelisms and perf.
| checkpoint_config=config.checkpoint, | ||
| override=config.override, | ||
| ) | ||
| if native: |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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
| if ( | ||
| config.cudagraph.enable | ||
| and config.cudagraph.mode == "FULL_AND_PIECEWISE" | ||
| ): | ||
| os.environ["VLLM_USE_BREAKABLE_CUDAGRAPH"] = "1" |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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?
|
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! |
## 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]>
Wires the upstream Qwen3.5 model (
torchtitan/models/qwen3_5/, #3371) intothe RL experiment. Addresses #3756.
Qwen3.5 is a hybrid model: most layers are
GatedDeltaNet(gatedlinear-attention/SSM) with a full-attention layer every
full_attention_interval.That breaks several RL-stack assumptions, fixed here:
Changes
alphabet_sortrl_grpo_qwen3_5_4b_varlen+_qwen3_5_rl_model_registry(lm_head fp32 cast, like the qwen3 wrapper).
actors/trainer.py,actors/generator.py): usemodel.first_attentioninstead of assuminglayers[0]carries an attention config (layer 0 of Qwen3.5 is GatedDeltaNet).models/vllm_wrapper.py,models/vllm_registry.py):derive head dims from the first full-attention layer; skip linear
(GatedDeltaNet) layers when swapping
inner_attentionfor the vLLMpaged-attention backend.
parallelize_qwen3_5: addskip_dp(FSDP forward hooks are incompatiblewith vLLM's
inference_mode), matchingparallelize_qwen3.forwardrun text-only (special_tokens=None) byreading the image/video token ids only when pixel values are present (it raised
TypeErrorotherwise — the model could not run text-only at all).qwen3_5->"auto"(resolve the chat template from thetokenizer).
Status / known limitation (why this is a draft)
Config build is verified (spec
qwen3_5, 32 layers,first_attentionresolves tothe full-attention layer). The open risk is the generator: GatedDeltaNet has no
recurrent-state cache in the vLLM
TorchTitanCausalLMwrapper, so generationrecomputes 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).