Skip to content

[WS1][CUDA][Qwen3-Next] Strict GDN recurrence in one launch per layer - #744

Open
fusheng-ji wants to merge 24 commits into
RL-Align:test-qwennextfrom
fusheng-ji:perf/qwen3-next-gdn-fused-recurrence
Open

fusheng-ji wants to merge 24 commits into
RL-Align:test-qwennextfrom
fusheng-ji:perf/qwen3-next-gdn-fused-recurrence

Conversation

@fusheng-ji

@fusheng-ji fusheng-ji commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

RFC #428 Qwen3-Next, strict GDN recurrence in one launch per layer (base test-qwennext).

Evidence location:

  • summary: reports/experiments/qwen3_next/qwen3-next-gdn-one-launch-b200-h100.md;
  • raw results: a release ZIP (SHA-256 f7b410f4…330bdd), as the maintainers asked for Qwen3-Next evidence.

What

  1. One launch per GDN layer for the strict forward (rl_engine/integrations/engines/train/vllm/qwen3_next_gdn.py, 63d46013).
    • The problem. The strict path ran each GDN layer's recurrence as a Python loop, launching vLLM's decode kernel once per token position. It did this on purpose, so that prefill and decode share one kernel and give the same bits. It cost about 0.28 ms per token per layer on B200; over 36 layers that is about 10 of the ~11 ms per prompt token of strict prefill. The same loop ran in VIME replay and in the training forward.
    • The new forward:
      • A small Triton kernel computes the gating values g and beta with the decode kernel's own expressions: softplus threshold 20, -exp(A_log) * softplus(a + dt_bias), sigmoid(b).
      • vLLM 0.30.0's fused_recurrent_gated_delta_rule then runs the same per-token update with the same tiles (BK 128, BV 32, one warp, three stages), with the time loop inside the kernel.
      • Output, final state and untouched cache slots are bit-identical to the loop.
    • Backward differentiates the old loop, now called decode_loop_sequence, so gradients are unchanged.
  2. Provider name (qwen3_next_provider.py). GDNProviderConfig.recurrence becomes vllm-0.30.0-fused-recurrent-decode-gating, so a certificate made for the old code does not cover the new one.
  3. Tests (tests/models/qwen3_next/check_qwen3_next_gdn_sequence.py). Seven new checks compare the one-launch forward with the loop bit for bit, including a 362-slot state bank and mixed and zero lengths, and compare the gradients.
  4. Report (reports/experiments/qwen3_next/qwen3-next-gdn-one-launch-b200-h100.md, 76fbaadc).
Commit What
63d46013 perf: the strict GDN recurrence in one launch per layer
ae913959 merge of #740 (be9b0285)
76fbaadc docs: B200 / H100 report and evidence link
bb02a313 docs: the report cites the EP4 chain's public commits
a648241e refuse a non-in-place final state; gradients against an independent FP64 reference
0d5741f0 merge of #740 (7e4c504c)
7b5550b3 test: gradients against FP64 at mixed lengths too; the self-comparison named for what it checks
7af7dad3 an all-empty batch returns a new bank, not the caller's; the gradient tests require non-zero gradients
94704c3e, 69a74a5a, 4ee99ab7 merges of #740 (a20cb715, 41f79bbe, cfeadffd)
9c0e5595 docs: the GDN report cites the re-uploaded evidence ZIP
a3374d26 docs: the GDN report cites the ZIP repacked without account IDs

Prior art & reuse decision

Existing implementation Same bits as the strict decode kernel? Decision
vLLM 0.30.0 fused_recurrent_gated_delta_rule (time loop inside one launch) Yes, with gating computed by the decode kernel's formulas reused as the recurrence
the same kernel with g / beta computed in PyTorch No: up to 3e-5 off not used; gating is a Triton copy of the decode kernel's expressions
vLLM's chunked GDN prefill kernel No: chunked algebra (about 0.42 ms for 1024 tokens) not used in strict mode
vLLM fused_recurrent_gated_delta_rule_packed_decode, per token (the old path) Yes kept, as decode_loop_sequence, for backward

Decision: reuse vLLM 0.30.0's fused recurrent kernel with the decode kernel's own tiles, and write only the gating kernel, because PyTorch gating is up to 3e-5 off the decode kernel.

Before and after

Left: one GDN layer on 1 × H100, the per-token loop against the one launch, all four cases bit-identical. Right: strict rollout prefill (time to the first token) on 4 × B200 before and after. Both from the files in the ZIP.

Results (B200 / Blackwell)

  • Bits. One GDN layer: all four probe cases are bit-identical to the loop (output, final state, cache slots; output_max_abs 0.0). The one launch takes 1.14 / 3.19 / 4.49 / 2.15 ms for 64, 1024, 3365 and 16 × 512 tokens. The GDN, convolution and core checks: 43 passed.
  • Real-weight chain at 213a9bcd (the fix merged with the speed test's first commits, which do not touch the strict path):
    • TP4 preflight, layers, l2 and bi (full) passed; 97 / 97 cells; chain report passed=True, 16 cells; gate 17 passed.
    • EP4 preflight, layers and l2 passed.
  • Strict path time, before and after:
before (f5100979) after (213a9bcd)
rollout prefill, 64 / 256 / 1024-token prompt, batch 1 0.89 / 3.03 / 11.59 s 0.18 / 0.20 / 0.30 s
rollout prefill, 512-token prompts, batch 1 / 16 / 64 7.85 / 16.01 / 25.51 s 0.25 / 0.79 / 2.15 s
replay logprob, 64 / 256 / 1024 tokens, batch 1 0.98 / 2.80 / 9.65 s 0.19 / 0.20 / 0.29 s
replay logprob, 512 + 512 tokens, batch 1 / 4 / 16 9.78 / 9.77 / 10.89 s 0.31 / 0.44 / 1.15 s
decode, tokens/s, batch 1 5.55 5.69
one training step, 64-token prompts / 512 + 512 tokens, batch 4 80.5 / 596.6 s 73.8 / 568.1 s

Results (H100 / Hopper)

At 213a9bcd on 4 × H100:

Status

History

  • 2026-11-20: found while building the end-to-end speed test. Strict prefill took about 11 ms per prompt token, almost all of it in the per-token GDN loop. The fix was verified bitwise on random inputs, then with real weights on B200 and H100.
  • 2026-11-22, bot round: a648241e.
    • The forward checks that vLLM returned the cloned bank as the final state (true for 0.30.0), and refuses otherwise.
    • A new check compares the forward and every gradient with FP64 autograd of an independent PyTorch gated delta rule: relative errors 1.4e-4 to 2.3e-3; a 10 % wrong decay gives 2.4e-2 to 4.0e-2.
    • The bank clone and the zero-length backward are answered, not changed.
    • Each finding has a reply.
  • 2026-11-22: stacked on [WS1][CUDA][Qwen3-Next] Follow-up to the RFC #428 stack: CI skip guard, case outcomes, worker attributes, user-site guard, CUDA_DEVICE_MAX_CONNECTIONS #740; the local B200 bit check was rerun at this head.
  • 2026-11-23, bot round on 0d5741f0: 7b5550b3.
    • The FP64 reference check also runs lengths (16, 0, 9, 32), which so far only had the comparison with the decode loop. Relative errors are 1.3e-4 to 2.5e-3, against 8.8e-5 to 2.3e-3 at (5, 0, 3).
    • That comparison is renamed for what it checks, the backward's wiring: the backward differentiates the decode loop by design.
    • The 362-slot case and the docstring say the op leaves the caller's state bank unchanged.
    • The failure_kind signatures needed no change.
    • Each finding has a reply.
  • 2026-11-23, bot round on 7b5550b3: 7af7dad3.
    • When every sequence is empty, the forward returned the caller's bank itself, so the output aliased it. It now returns a clone; a new test fails on the old code.
    • Both gradient tests require every gradient to exist and be non-zero.
    • Kept, with the reason in the reply: the 2-D slot indices (vLLM 0.30.0's kernel reads one slot per token when it updates the bank in place) and the FP64 check's 1e-2 bound.
    • Each finding has a reply.
  • 2026-11-23, bot round on 7af7dad3: both findings are in [WS1][CUDA][Qwen3-Next] Follow-up to the RFC #428 stack: CI skip guard, case outcomes, worker attributes, user-site guard, CUDA_DEVICE_MAX_CONNECTIONS #740's files.
    • The worker test is strengthened there (a20cb715, merged in 94704c3e).
    • The user-site comparison needed no change.
    • Each finding has a reply.
  • 2026-11-24, bot round on 94704c3e: no change. The decode loop already returns early on an all-empty batch, and the new test runs its backward. The finding has a reply. [WS1][CUDA][Qwen3-Next] Follow-up to the RFC #428 stack: CI skip guard, case outcomes, worker attributes, user-site guard, CUDA_DEVICE_MAX_CONNECTIONS #740's test commit is merged in 69a74a5a.

Tests

Command Environment Result
pytest check_qwen3_next_gdn_sequence.py check_qwen3_next_gdn_bridge.py check_qwen3_next_shared_core.py check_qwen3_next_core_matrix.py check_qwen3_next_conv_bridge.py 1 × B200, _C in the checkout, head 0d5741f0 44 passed (43 at ae913959, plus the independent-reference check)
the same 1 × H100, 213a9bcd 43 passed
pytest check_qwen3_next_gdn_sequence.py 1 × B200, head 7b5550b3 18 passed (17 before, plus the mixed-length FP64 case)
pytest check_qwen3_next_gdn_sequence.py check_qwen3_next_gdn_bridge.py check_qwen3_next_shared_core.py check_qwen3_next_core_matrix.py check_qwen3_next_conv_bridge.py 1 × B200, head 7af7dad3 46 passed
one-layer probe (bits and time, in the ZIP) 1 × B200 at ae913959; 1 × H100 at 213a9bcd 4 / 4 bit-identical on both
pytest tests/models/qwen3_next/ training environment, at the speed-test PR's 0ce47260 (contains this PR) 561 passed, 104 skipped, 15 failed (1 × B200 visible). The 15 are the training environment's test_qwen3_next_training_checkpoint.py group: Invalid device id once the cuDNN path is set, as on the B200 and H100 nodes
mypy --ignore-missing-imports rl_engine/ as CI, without site-packages no errors in files this PR changes (the same 8 as test-qwennext, in two other files)
pre-commit run --from-ref be9b0285 --to-ref HEAD passed

Scope / Known limitations

  • Forward only. The backward still differentiates the per-token loop, so a strict training step is barely faster (568 s against 597 s for the long workload).
  • Decode is unchanged: it was already one step per launch.
  • Bits are claimed against vLLM 0.30.0's kernels with the pinned tile configuration; another vLLM version is a new provider, which is what the renamed recurrence enforces.
  • The end-to-end comparison with stock vLLM and stock VIME is the next PR, stacked on this one.

…pped

The step only asserted four visible GPUs. A missing vLLM, kernel or
dtype support makes these modules skip, and pytest exits 0 for an
all-skipped run, so the job reported a real-model pass that never ran.
Apply the provider step's guard: tee the log, fail on any skip and
require at least one pass.

Signed-off-by: Wenbo Ji <[email protected]>
The case recorder wrote "skipped" for every report with wasxfail, so a
non-strict xpass of a mandatory case showed up as a skip. Record xfail
and xpass as themselves. The verdict is unchanged: xfail counts as a
skip and xpass as a failure, and either fails the run.

Signed-off-by: Wenbo Ji <[email protected]>
…constructor

SharedQwenWorker assigned shared_l2_trace and the execution mode after
Worker.__init__. vLLM 0.30.0's constructor calls no model method, so
nothing read them early, but an override reached from a later vLLM's
constructor would raise AttributeError. Assign both first; the contract
test checks they exist when the native constructor runs.

Signed-off-by: Wenbo Ji <[email protected]>
…ckages

On an H100 host every rollout smoke aborted while FlashInfer loaded
(__ffi_repr__ already registered): apache-tvm-ffi 0.1.16 in the user
site-packages was imported ahead of the environment's own copy. The
user site comes first on sys.path, so a package there replaces the
environment's copy, and the environment identity listed both without
flagging it.

current_identity() now raises environment_mismatch when a distribution
in the user site also exists in another installation root, and names
the packages and PYTHONNOUSERSITE=1. Packages only in the user site are
still recorded as before. The chain usage doc says so.

Signed-off-by: Wenbo Ji <[email protected]>
On four H100s the l2 recompute failed in Megatron's validate_args, which
requires CUDA_DEVICE_MAX_CONNECTIONS=1 with tensor parallelism. The B200
runs did not hit the check. The dense launcher already sets it; the
Qwen3-Next stage environment did not.

Set it next to the thread limits, outside provider_config.runtime_env,
so the run manifest does not change. It limits the hardware work queues
and does not change any kernel's arithmetic. The B200 chain has not been
rerun with it.

Signed-off-by: Wenbo Ji <[email protected]>
packed_recurrent_sequence launched vLLM's packed decode kernel once per token
position from Python, so the GDN layers cost about 0.28 ms per token per layer
on a B200, independent of batch and cache size. With 36 GDN layers that was
about 10 ms per prompt token in strict vLLM prefill, VIME replay and the
training forward.

The forward now calls vLLM 0.30.0's fused_recurrent_gated_delta_rule, which
runs the same per-token update with the same tiles (BK=128, BV=32, one warp,
three stages) and the time loop inside one launch. It takes g and beta as
inputs; a small Triton kernel computes them with the decode kernel's own
loads, casts and expressions. Computing them in PyTorch instead changes low
bits, so the copy is required.

The backward differentiates the old per-token decode loop, now
decode_loop_sequence, so gradients come from the same computation as before.
GDNProviderConfig.recurrence is renamed, so an older certificate does not
cover this provider.

check_qwen3_next_gdn_sequence.py now also requires the one-launch forward to
equal the decode loop bit for bit (output, final state, untouched slots of a
362-slot bank, mixed and zero lengths), and the gradients of both to be equal.
On one B200 the layer takes 2.3 ms instead of 348 ms for 1024 tokens.

Signed-off-by: Wenbo Ji <[email protected]>
…perf/qwen3-next-gdn-fused-recurrence

Stacks the one-launch GDN recurrence on the follow-up PR, which itself merged test-qwennext 12d5041.

Signed-off-by: Wenbo Ji <[email protected]>
Bits against the per-token loop, the real-weight TP4 / EP4 chain and the strict path's time
before and after, with a link to the raw results (release ZIP) and how to reproduce them.

Signed-off-by: Wenbo Ji <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6a7423f0-fcbd-4b72-889b-9cb675c4417a

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

🔍 OpenCodeReview found 1 issue(s) in this PR.

  • ✅ Successfully posted inline: 0 comment(s)
  • 📋 Routed to summary by policy: 1 comment(s)

⚠️ 5 warning(s) occurred during review.


bug · low

📄 .github/workflows/qwen3-next-provider-gpu.yml (L184-L185)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category bug)

The fail-closed check only matches skip output, but the sibling change in pytest_case_manifest.py now explicitly treats xfail/xpass as not-completed cases. With -rs (no -rx), a non-strict @pytest.mark.xfail test that unexpectedly passes produces no SKIPPED line and pytest exits 0 with 1 xfailed/1 xpassed in the summary; [0-9]+ passed then still matches, so a mandatory real-model check that silently did not execute would be reported as success. Include xfail/xpass in the detection (or run with -rx).

💡 Suggested Change

Before:

          if grep -Eq '^SKIPPED|[0-9]+ skipped' "$log"; then
            echo "::error::a real-model check was skipped"

After:

          if grep -Eq '^SKIPPED|[0-9]+ (skipped|xfailed|xpassed)' "$log"; then
            echo "::error::a real-model check was skipped or xfailed"

⚠️ Warnings:

  • .github/workflows/qwen3-next-provider-gpu.yml,rl_engine/integrations/engines/rollout/vllm/qwen3_next_vllm_worker.py,rl_engine/integrations/engines/train/vllm/qwen3_next_provider.py,tests/models/qwen3_next/check_qwen3_next_vllm_model_contract.py (review_limit_reached): reached the aggregate token budget before finishing; the grace round did not complete the task
  • .github/workflows/qwen3-next-provider-gpu.yml (token_budget_reached): stopped group ".github/workflows/qwen3-next-provider-gpu.yml,rl_engine/integrations/engines/rollout/vllm/qwen3_next_vllm_worker.py,rl_engine/integrations/engines/train/vllm/qwen3_next_provider.py,tests/models/qwen3_next/check_qwen3_next_vllm_model_contract.py" mid-review: used 626038 tokens exceeds budget 500000
  • tests/models/qwen3_next/test_qwen3_next_environment_identity.py (token_budget_reached): stopped dispatch: used 626038 tokens + group estimate 103128 = projected 729166 exceeds budget 500000
  • rl_engine/validation/models/pytest_case_manifest.py,rl_engine/validation/models/qwen3_next/qwen3_next_cases.py,tests/models/qwen3_next/test_qwen3_next_case_manifest.py (review_limit_reached): reached the aggregate token budget before finishing; the grace round completed the task
  • rl_engine/integrations/engines/train/vllm/qwen3_next_gdn.py,tests/models/qwen3_next/check_qwen3_next_gdn_sequence.py (review_limit_reached): reached the aggregate token budget before finishing; the grace round did not complete the task

@github-actions

Copy link
Copy Markdown

@fusheng-ji The automated OCR review has completed.

Please review and address all automated review bot findings, then push your updates. Maintainers will begin manual review after the bot findings have been addressed.

probe_environment ran qwen3_next_runtime.py --json with check_output, so a refusal in the
child (environment_mismatch for a shadowing user site) reached the launcher as a bare
'returned non-zero exit status 1'. It now captures the child's stderr and raises a
ProcessFailure with its tail and failure_kind. New test with a refusing stand-in interpreter
(fails on the old code).

Signed-off-by: Wenbo Ji <[email protected]>
…s against a reference

The one-launch forward relied on vLLM 0.30.0 returning initial_state itself as the final
state when inplace_final_state is set, and discarded the returned tensor. It now checks that
the returned final state is the cloned bank and raises otherwise, so a provider that returned
a separate tensor could not leave the state stale.

The gradient check compared the one-launch backward with the decode loop, and both
differentiate the same loop. A new check compares the forward and every input gradient with
FP64 autograd of an independent PyTorch gated delta rule written from the kernel
(relative error 1.4e-4 to 2.3e-3; a 10% wrong decay gives 2.4e-2 to 4.0e-2, over the 1e-2
bound).

Signed-off-by: Wenbo Ji <[email protected]>
Any pip install --user leaves pip (and often wheel) in the user site next to the
environment's copies, and the guard refused every run on such a machine although no stage
imports them. They are now exempt. setuptools stays in the check: torch.utils.cpp_extension
imports it for the JIT builds the stages allow. New test.

Signed-off-by: Wenbo Ji <[email protected]>
@fusheng-ji

Copy link
Copy Markdown
Contributor Author

Replies to the four OpenCodeReview findings routed to the summary (run on bb02a313).

  1. qwen3_next_gdn.py L271, performance: the forward clones the whole FP32 state bank. Not changed.
    • The clone keeps the forward functional. The caller's bank is unchanged, which autograd needs because state is saved for the backward, and so do callers that keep the previous bank.
    • The per-token loop this replaces cloned the bank at every token; this clones it once per call.
    • Its cost is inside the timings in the report: one launch, clone included, is 1.06-6.40 ms on H100 for 64-3365 tokens with a 65-slot bank, and 2.89 ms for 16 × 512 tokens with 362 slots.
    • Copying only the touched slots would need a gather and a scatter around the kernel, and the clone is not where the time goes.
  2. L261-262: an all-zero-length pack forwards but fails in backward. Not a defect.
    • _decode_loop returns qkv.new_empty((0, heads, 128)) and the unchanged state when no sequence has tokens (if not outputs: before torch.cat), so the backward's torch.cat never sees an empty list.
    • check_qwen3_next_gdn_sequence.py runs packs with zero-length sequences in both forward and backward. The new reference test below includes one too.
  3. L275: the fused path relies on inplace_final_state and discards the returned state. Fixed in a648241e.
    • vLLM 0.30.0 returns initial_state itself in that mode (fused_recurrent.py: final_state = initial_state), so the result was correct for the pinned provider.
    • The forward now checks that the returned final state is the cloned bank and raises otherwise, so a provider that returned a separate tensor fails closed instead of leaving the state stale.
  4. check_qwen3_next_gdn_sequence.py L140-141: both gradients come from the same _decode_loop. Fixed in a648241e: test_gradients_match_an_independent_reference.
    • It compares the forward and every input gradient with FP64 autograd of a separate PyTorch gated delta rule, written from the kernel: L2-normalised q and k, h *= exp(g), v -= h k, v *= beta, h += v kᵀ, o = h q, with the gating from A_log, dt_bias, a and b.
    • The relative errors are 1.4e-4 to 2.3e-3 (BF16 inputs) against a 1e-2 bound. With the decay made 10 % stronger in the reference, they are 2.4e-2 to 4.0e-2, so the check catches such an error.

GDN checks at this PR's head: 44 passed, on a B200 with _C built in the checkout.

Comment on lines +256 to +259
raise ProcessFailure(
f"environment probe exited with {result.returncode}:\n{tail}",
failure_kind=failure_kind(text=tail),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · high
The new refusal path depends on two helper contracts that are not changed in this diff: ProcessFailure(...) must accept a failure_kind= keyword, and failure_kind must accept a text= keyword here while the new test in test_qwen3_next_environment_identity.py calls failure_kind(error) with the exception positionally. If failure_kind only accepts one of these forms (or ProcessFailure has no failure_kind attribute/kwarg), both probe_environment and test_probe_keeps_the_child_refusal_and_its_failure_kind raise TypeError instead of surfacing the child's environment_mismatch, i.e. the refusal this PR is adding is lost. Please confirm/align the signatures (e.g. def failure_kind(error=None, *, text=None) and a failure_kind parameter on ProcessFailure) so the child message and its kind are preserved.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not changed: both signatures are already the ones asked for, in tools/validation/models/qwen3_next/qwen3_next_runtime.py:

  • class ProcessFailure(RuntimeError) has __init__(self, message, *, failure_kind) and stores self.failure_kind;
  • def failure_kind(error=None, *, text="") returns error.failure_kind first when it is a known kind, and otherwise classifies the error or text.

So failure_kind(text=tail) in probe_environment and failure_kind(error) in the tests are both valid calls. test_probe_keeps_the_child_refusal_and_its_failure_kind runs that path with a child that refuses with environment_mismatch, and asserts the kind survives.

fusheng-ji added a commit to fusheng-ji/RL-Kernel that referenced this pull request Nov 23, 2026
…ownloads are served as attachments); RL-Align#744 plot script

Signed-off-by: Wenbo Ji <[email protected]>
…d lengths

The FP64 reference gradient test now also runs lengths (16, 0, 9, 32), the
mixed-length case that so far only had the self-comparison against the decode
loop. That test is renamed for what it checks: the backward differentiates the
decode loop by design, so it covers the wiring, not the gradient math.

The rollout-sized bank case says the op is functional (the caller's bank keeps
every byte, the slots it reads included), and the docstring says the input
state is not modified.

Signed-off-by: Wenbo Ji <[email protected]>
@fusheng-ji

Copy link
Copy Markdown
Contributor Author

Reply to the OpenCodeReview finding routed to the summary (run on 0d5741f0).

tests/models/qwen3_next/check_qwen3_next_gdn_sequence.py L131-132: the gradient test compares the decode loop with itself. Right. Fixed in 7b5550b3.

  • The independent FP64 reference test now runs lengths (16, 0, 9, 32) as well as (5, 0, 3), so the mixed-length case's gradient math is checked against a separate recurrence.
  • The self-comparison is renamed test_backward_wiring_equals_the_decode_loop_gradient, and its docstring says what it checks: the backward differentiates the decode loop by design, so it covers the wiring (saved inputs, which inputs need gradients, an empty sequence, the state bank's routing), not the math.
  • 18 passed on one B200 (check_qwen3_next_gdn_sequence.py).

def _fused_sequence(qkv, a, b, A_log, dt_bias, state, indices, boundaries, *, num_k_heads, scale):
lengths = [end - start for start, end in zip(boundaries, boundaries[1:])]
if not max(lengths, default=0):
return qkv.new_empty((0, state.shape[1], 128)), state

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · high
The zero-token branch of _fused_sequence returns the caller's state tensor object unchanged, whereas every other path (and _PackedDecode.forward) returns a fresh clone. Because _PackedSequence.forward is a torch.autograd.Function and state is a normal forward input (often a leaf that requires_grad), returning an input as-is as a Function output means autograd will try to install a grad_fn on that same leaf tensor, which is not supported and can raise / corrupt the graph. It also makes packed_recurrent_sequence's "caller's state is not modified" invariant inconsistent: the returned state aliases the input, so mutating it later mutates the caller's tensor. This is reachable via a batch where all sequences have zero length (e.g. cu_seqlens=[0, 0]). Return a fresh tensor instead of the input, e.g. state.clone().

Suggestion:

Suggested change
return qkv.new_empty((0, state.shape[1], 128)), state
return qkv.new_empty((0, state.shape[1], 128)), state.clone()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 7af7dad3: the all-empty path now returns state.contiguous().clone(), a new bank as on every other path.

New test test_all_empty_sequences_return_a_new_bank_and_backpropagate. It runs cu_seqlens = [0, 0] and checks three things: the returned bank does not share storage with the input, it is equal to it, and its gradient flows back to the input. On the old code it fails on the storage check (both data_ptr()s were equal). The GDN check set gives 46 passed on one B200.

…mpty

The all-empty path returned the caller's bank itself, so the output aliased
it, unlike every other path. It now returns a clone. New test, which fails
on the old code: a new bank, equal to the input, and its gradient flows back.

The gradient tests also assert that every gradient exists and is non-zero:
the wiring test for each input, and the FP64 check for each reference
gradient, so a zero reference cannot make the relative error vacuous.

Signed-off-by: Wenbo Ji <[email protected]>
@fusheng-ji

Copy link
Copy Markdown
Contributor Author

Replies to the three OpenCodeReview findings routed to the summary (run on 7b5550b3).

1. check_qwen3_next_gdn_sequence.py L144-145: the backward test is a self-comparison. Agreed, and it is presented as one.

  • 7b5550b3 renamed it test_backward_wiring_equals_the_decode_loop_gradient. Its docstring says it checks the wiring, not the math, which the FP64 reference test covers.
  • 7af7dad3 adds the concrete wiring property asked for: every input's gradient exists and is non-zero, before the bitwise comparison.

2. check_qwen3_next_gdn_sequence.py L209-211: the FP64 check's norm and tolerance.

  • Zero reference: fixed in 7af7dad3. Each reference gradient must now be non-zero, so the relative error cannot pass vacuously.
  • The norm is already per tensor: relative is computed for the output and for each input's gradient separately, not over all of them.
  • The 1e-2 bound is kept, because it separates the two cases with room on both sides:
    • the measured errors are 8.8e-5 to 2.3e-3 at lengths (5, 0, 3) and 1.3e-4 to 2.5e-3 at (16, 0, 9, 32);
    • a 10 % wrong decay gives 2.4e-2 to 4.0e-2 (a648241e).
  • A per-element bound would mostly measure FP32 rounding on near-zero elements.
  • The exact-arithmetic claim is a separate, bitwise test: the one-launch forward against the decode loop.

3. qwen3_next_gdn.py L274: slots is 2-D. Not changed: vLLM 0.30.0's kernel needs one slot per token on this path.

  • With inplace_final_state=True, fused_recurrent_gated_delta_rule_fwd_kernel reads the destination slot for each token: ssm_state_indices + i_n * stride_indices_seq + i_t (vllm/third_party/flash_linear_attention/ops/fused_recurrent.py, lines 154-156).
  • So the indices must be (sequences, tokens). A 1-D per-sequence tensor would read the next sequence's slot from the second token on.
  • slots repeats the sequence's slot for each of its tokens, so every per-token store goes to that slot, and the last one is the final state. The comment above slots says so.
  • The 1-D per-sequence form is the packed-decode kernel's ABI (_PackedDecode, one token per sequence), which _validate_state_indices checks.
  • Tests: the one-launch output and final bank are bitwise equal to one decode step per token at mixed lengths, a zero length included. So are a 1024-token prompt cut into chunks and reordered sequences. Wrong slots would break all three.

…e constructor

The existing check builds the worker without a config, so the mode it sees
is None. The new check passes a config with an identity and asserts that
the mode activated for it is already set when vLLM's Worker.__init__ runs;
it fails if the worker drops the mode.

Signed-off-by: Wenbo Ji <[email protected]>
@fusheng-ji

Copy link
Copy Markdown
Contributor Author

Replies to the two OpenCodeReview findings routed to the summary (run on 7af7dad3).

1. check_qwen3_next_vllm_model_contract.py L172-173: the worker test cannot see a real execution mode. Fixed in #740 (a20cb715), merged here in 94704c3e.

  • New test test_spawn_worker_sets_the_identity_execution_mode_before_native_initialization.
    • It builds the worker with a config that carries an identity, and makes activate_for_identity return a sentinel.
    • It asserts that the sentinel is already shared_provider_execution_mode inside vLLM's Worker.__init__.
    • It fails if the worker drops the mode (checked by setting it to None in the worker).
  • The existing test was not blind to the ordering itself. The attribute has no class default, so reading it in the native constructor before it is assigned raises AttributeError. What it could not see was the value.

2. qwen3_next_runtime.py L158-160: lexical Path equality for the user site. Not changed, as in the replies to the two earlier runs.

  • Both sides come from the same call. installation_roots() adds Path(site.getusersitepackages()), and current_identity() passes site.getusersitepackages(). Neither is resolved, so they are equal whenever the directory exists, whatever symlinks the home directory goes through.
  • They differ only when the user site does not exist (installation_roots() keeps existing directories), and then nothing can shadow.
  • Resolving one side would be what creates a mismatch. The reverse case, the user site counted among the other roots, cannot happen for the same reason.

Comment on lines +261 to +263
if not max(lengths, default=0):
# A new bank, as on every other path: the output must not alias the caller's state.
return qkv.new_empty((0, state.shape[1], 128)), state.contiguous().clone()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

bug · high
This forward special-cases an all-empty batch, but the backward path has no matching guard: _PackedSequence.backward calls _decode_loop, and decode_loop_sequence calls it directly, yet _decode_loop ends with an unconditional return torch.cat(outputs).index_select(0, order), state. With all sequences empty (max(lengths) == 0) the loop never runs, so outputs is empty and torch.cat([]) raises RuntimeError: expected a non-empty list of Tensors. The newly added test_all_empty_sequences_return_a_new_bank_and_backpropagate calls .backward() on exactly this case and will therefore fail, and decode_loop_sequence on an empty batch crashes too. Add an early return in _decode_loop (e.g. when max(lengths, default=0) == 0, return qkv.new_empty((0, state.shape[1], 128)), state preserving the grad link) so backward mirrors the forward's empty handling.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not changed: _decode_loop already handles the all-empty case, so the backward does not reach torch.cat([]).

  • After its loop, _decode_loop returns early when no token ran: if not outputs: return qkv.new_empty((0, state.shape[1], 128)), state (qwen3_next_gdn.py, lines 180-181). state keeps its gradient link, so the backward passes the bank's gradient through.
  • test_all_empty_sequences_return_a_new_bank_and_backpropagate runs the backward on this case, and it passes: 46 passed at 7af7dad3 (1 × B200), with state.grad == 2 * state.

@Flink-ddd Flink-ddd added platform: cuda Specific optimizations or bugs in NVIDIA graphics cards (such as FlashInfer, TMA optimizations) new-model qwen WS1 labels Nov 24, 2026
…s a failure

The worker execution-mode test also checks that the activator gets the
configured identity itself, so a dropped or different identity fails it.

A strict xpass gets its own case in the plugin test: pytest reports it as
"failed" without wasxfail, and the report counts it under failures.

Signed-off-by: Wenbo Ji <[email protected]>
fusheng-ji added a commit to fusheng-ji/RL-Kernel that referenced this pull request Nov 28, 2026
…ownloads are served as attachments); RL-Align#744 plot script

Signed-off-by: Wenbo Ji <[email protected]>
…_assets

The release ZIPs were re-uploaded with the B200 PCI bus IDs masked, and
pr_assets was rewritten to remove host and user identifiers. The merged
batch-invariance, chain and EP4 logprob reports cite the ZIPs' new SHA-256,
and the two RMSNorm docs link pr_assets c44f3f1 (was 692c408), which holds
the same files.

Signed-off-by: Wenbo Ji <[email protected]>
The release ZIP was re-uploaded with the B200 PCI bus IDs and a site home
path masked; the report cites its new SHA-256.

Signed-off-by: Wenbo Ji <[email protected]>
fusheng-ji added a commit to fusheng-ji/RL-Kernel that referenced this pull request Nov 29, 2026
…ownloads are served as attachments); RL-Align#744 plot script

Signed-off-by: Wenbo Ji <[email protected]>
The release asset qwen3-next-gdn-one-launch-b200-h100.zip was repacked
with the numeric user and group IDs masked in its environment records
and replaced. Update the SHA-256 the report cites.

Signed-off-by: Wenbo Ji <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

new-model platform: cuda Specific optimizations or bugs in NVIDIA graphics cards (such as FlashInfer, TMA optimizations) qwen WS1

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants