Skip to content

[AMD] Qwen4-Exp: sequence-parallel hyper-connection residual for TP prefill - #80

Merged
apinge merged 8 commits into
apinge:qwen38-flash-next-amd-current-fix-installfrom
yicyang:qwen4-seq-parallel
Nov 4, 2026
Merged

apinge merged 8 commits into
apinge:qwen38-flash-next-amd-current-fix-installfrom
yicyang:qwen4-seq-parallel

Conversation

@yicyang

@yicyang yicyang commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

Between the TP-sharded blocks, Qwen4-Exp runs three per-token ops on its 4-lane hyper-connection residual:
hc_combine, hc_norm and mix. After the all-reduce every TP rank holds all T rows, so every rank repeats these
ops on all T tokens.

What this PR does

With SGLANG_QWEN4_SEQ_PARALLEL=1, prefill keeps the residual sharded by token rows. Each all-reduce is split into
a reduce-scatter and an all-gather, with the per-token ops in between running on T/TP rows only:

              before                                        this PR
residual [T, 4x2560] (all rows)               residual [T/TP, 4x2560] (own rows)
  | hc_norm + mix   x T rows                    | hc_norm + mix   x T/TP rows
  v                                             | all-gather -> [T, 2560]
attention / GDN / MoE (all T rows)            attention / GDN / MoE (all T rows, unchanged)
  | all-reduce -> [T, 2560]                     | reduce-scatter -> [T/TP, 2560]
  v                                             v
hc_combine      x T rows                      hc_combine      x T/TP rows
  • RS + AG move the same bytes as the all-reduce, and AG(RS(x)) is bit-identical to AR(x). All three HC ops read
    only their own token's row, so sharding them is exact.
  • The residual is sharded after the last PLE layer; PLE's short conv needs neighbouring tokens.
  • At the end, only the final mixer output [T, 2560] is gathered. The residual is gathered instead only when hidden
    states are captured (MTP, return_hidden_states).
  • The path applies to eager EXTEND / MIXED / TARGET_VERIFY forwards with at least
    SGLANG_QWEN4_SEQ_PARALLEL_MIN_TOKENS tokens. Captured graphs, decode, draft-model forwards, DP attention and EP
    all-to-all keep the all-reduce.

Changes

  • layers/hc_seq_parallel.py (new): SeqParallelPlan (scatter / reduce-scatter / all-gather).
  • models/qwen4_exp.py: SP plumbing in the decoder layers and the model forward. The MoE runs under
    mlp_reduce_scatter=True.
  • environ.py: SGLANG_QWEN4_SEQ_PARALLEL (default 0) and SGLANG_QWEN4_SEQ_PARALLEL_MIN_TOKENS (default 2048).
  • benchmark/qwen4_seq_parallel/: README and bench_rs_ag.py.

New environment variables

Variable Default Meaning
SGLANG_QWEN4_SEQ_PARALLEL 0 1 enables the sequence-parallel residual. It only applies with TP > 1, without DP attention or EP all-to-all.
SGLANG_QWEN4_SEQ_PARALLEL_MIN_TOKENS 2048 Forwards with fewer tokens keep the all-reduce. The value is arbitrary, not tuned.

Results

8x MI308X, Qwen3.8-Flash-Next-PTPC-FP8, 12000 in / 350 out (scripts/run_pure_text_bench.sh). Measured at
e687814e2; the last commit (ad34d5364) was checked for correctness only.

Prefill step (12000 tokens, mean of 4 steps):

TP2 base TP2 SP TP4 base TP4 SP
step 748.7 ms 691.8 ms (-7.6%) 542.0 ms 434.9 ms (-19.8%)
hc_combine + hc_norm + mix 164.0 ms 97.4 ms 165.9 ms 53.2 ms
all-reduce, or RS + AG AR 129.4 ms RS 64.9 + AG 65.3 ms (+ AR 8.4) AR 84.8 ms RS 43.7 + AG 40.5 ms (+ AR 5.6)

Per-step kernel time on TP-0. The remaining all-reduce belongs to the layers up to the PLE layer.

QPS (req/s, two interleaved rounds):

conc TP2 base TP2 SP gain TP4 base TP4 SP gain
1 0.302 / 0.302 0.310 / 0.309 +2.4% 0.342 / 0.339 0.349 / 0.353 +3.0%
4 0.594 / 0.597 0.619 / 0.616 +3.7% 0.776 / 0.769 0.821 / 0.836 +7.3%
8 0.798 / 0.792 0.834 / 0.826 +4.4% 1.003 / 1.012 1.087 / 1.122 +9.6%
16 0.930 / 0.931 0.991 / 0.993 +6.6% 1.211 / 1.205 1.359 / 1.373 +13.1%
32 1.008 / 1.006 1.079 / 1.081 +7.2% 1.353 / 1.347 1.541 / 1.553 +14.6%

Accuracy

  • Greedy outputs of a 12-prompt long-context probe are bit-identical to the baseline at TP2, at TP4, and with MTP.

  • Long-context check: 48/48.

  • gsm8k:

    base SP
    TP2 0.9817 0.9779
    TP4 0.9802 0.9779

    Both are within the 0.976-0.983 run-to-run range.

Traces

Before (SP off, TP2)
image

After (SP on, TP2)
image

Limitations

  • The layers up to the PLE layer keep the all-reduce.
  • Bit-identity is observed, not guaranteed. A kernel may pick a different tiling for the smaller M.

Reproduce

SGLANG_QWEN4_SEQ_PARALLEL=1 TP_SIZE=4 bash scripts/launch_qwen38_flash_next_fp8_mi308x_pure_tp_4_or_8_or_2.sh
bash scripts/run_pure_text_bench.sh

…refill (opt-in)

Between the TP-sharded blocks, Qwen4-Exp runs three per-token ops on its
4-lane hyper-connection residual: hc_combine, hc_norm and the low-rank mix.
With a replicated residual every TP rank repeats them on all tokens, ~165 ms
of a 12k-token prefill step per rank (31% at TP4, 22% at TP2).

With SGLANG_QWEN4_SEQ_PARALLEL=1, prefill keeps the residual sharded by token
rows after the last PLE layer (layers/hc_seq_parallel.py): each block's
partial output is reduce-scattered instead of all-reduced, combined and mixed
on this rank's rows, and the mixed input is all-gathered for the next block.
The MoE runs under mlp_reduce_scatter=True so it returns its partial sum.
RS + AG (aiter custom kernels) move the same bytes as the all-reduce, and
AG(RS(x)) is bit-identical to AR(x).

Decode, graph capture, speculative modes, DP attention, EP all-to-all and
batches below SGLANG_QWEN4_SEQ_PARALLEL_MIN_TOKENS (2048) are unchanged.

12k-token prefill step: TP4 534 -> 436 ms, TP2 760 -> 685 ms. Serving
(12000 in / 350 out): TP4 +3% (c1) to +16% (c32) req/s, TP2 +2.5% to +7.5%,
greedy outputs bit-identical, gsm8k and a long-context probe unchanged.
…DME note)

- Narrow the aiter reduce-scatter path with isinstance on aiter's
  CustomAllreduce instead of a private GroupCoordinator helper.
- Skip the sequence-parallel path when this rank does not start at layer 0
  (the residual is sharded at an absolute layer index).
- README: note the discarded TP4 c32 baseline round.
…batches

- At the end of a sequence-parallel forward, run the final mixer on the local
  rows and all-gather its [T, hidden] output. The [T, hc_count * hidden]
  residual (HC state) is gathered only when the forward captures hidden
  states (speculative drafting, return_hidden_states), which is 1/hc_count
  of the gather bytes otherwise.
- Gate on EXTEND / MIXED / TARGET_VERIFY instead of
  is_extend_without_speculative: eager target-verify batches above the
  threshold are sharded too (captured ones never are), and split prefill is
  no longer let through.
@yicyang
yicyang marked this pull request as ready for review November 2, 2026 02:59
@yicyang
yicyang requested a balanced review from Copilot November 2, 2026 03:33

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Sequence parallelism can crash on ROCm without Aiter and is incorrectly enabled during graph warmup and capture and for MTP draft prefills.

3 open issues
What changed in this PR

This PR adds opt-in sequence parallelism to Qwen4-Exp’s hyper-connection residual path, reducing repeated per-token work across tensor-parallel ranks during prefill.

Changes:

  • Adds token-row scatter, reduce-scatter, and all-gather helpers.
  • Integrates residual sharding into decoder layers and final mixing, with hidden-state capture handling.
  • Adds configuration knobs, an AMD collective benchmark, and performance documentation.
File Description
python/​sglang/​srt/​models/​qwen4_exp.py Integrates sequence-parallel planning and residual processing.
python/​sglang/​srt/​layers/​hc_seq_parallel.py Implements row sharding and collective operations.
python/​sglang/​srt/​environ.py Defines the opt-in flag and minimum token threshold.
benchmark/​qwen4_seq_parallel/​README.md Documents the approach, configuration, and measured results.
benchmark/​qwen4_seq_parallel/​bench_rs_ag.py Compares Aiter collective timings and output equality.

Review effort: Balanced

Comment thread python/sglang/srt/models/qwen4_exp.py Resolved
Comment thread python/sglang/srt/models/qwen4_exp.py Resolved
Handle ImportError for CustomAllreduce import.

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
@yicyang
yicyang requested a review from apinge November 2, 2026 08:06
@apinge

apinge commented Nov 2, 2026

Copy link
Copy Markdown
Owner

Could you please add SGLANG_QWEN4_SEQ_PARALLEL=1 and other related env in sglang/scripts/launch_qwen38_flash_next_fp8_mi308x_pure_tp_4_or_8_or_2.sh

@yicyang

yicyang commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

Could you please add SGLANG_QWEN4_SEQ_PARALLEL=1 and other related env in sglang/scripts/launch_qwen38_flash_next_fp8_mi308x_pure_tp_4_or_8_or_2.sh

done

SGLANG_QWEN4_SEQ_PARALLEL now defaults to on (0 restores the all-reduce), and the
MI308X launch script exports both SP switches with overridable defaults.
…efill

get_is_capture_mode() only covers decode capture and breakable graphs; also skip
the sequence-parallel plan inside tc_piecewise CUDA graphs and whenever the current
stream is capturing, since the row split depends on the batch's token count.
@apinge
apinge merged commit 15055ff into apinge:qwen38-flash-next-amd-current-fix-install Nov 4, 2026
1 check failed
sammysun0711 added a commit that referenced this pull request Nov 11, 2026
* [AMD] Qwen4-Exp: sequence-parallel hyper-connection residual for TP prefill (#80)

* [AMD] Qwen4-Exp: sequence-parallel hyper-connection residual for TP prefill (opt-in)

Between the TP-sharded blocks, Qwen4-Exp runs three per-token ops on its
4-lane hyper-connection residual: hc_combine, hc_norm and the low-rank mix.
With a replicated residual every TP rank repeats them on all tokens, ~165 ms
of a 12k-token prefill step per rank (31% at TP4, 22% at TP2).

With SGLANG_QWEN4_SEQ_PARALLEL=1, prefill keeps the residual sharded by token
rows after the last PLE layer (layers/hc_seq_parallel.py): each block's
partial output is reduce-scattered instead of all-reduced, combined and mixed
on this rank's rows, and the mixed input is all-gathered for the next block.
The MoE runs under mlp_reduce_scatter=True so it returns its partial sum.
RS + AG (aiter custom kernels) move the same bytes as the all-reduce, and
AG(RS(x)) is bit-identical to AR(x).

Decode, graph capture, speculative modes, DP attention, EP all-to-all and
batches below SGLANG_QWEN4_SEQ_PARALLEL_MIN_TOKENS (2048) are unchanged.

12k-token prefill step: TP4 534 -> 436 ms, TP2 760 -> 685 ms. Serving
(12000 in / 350 out): TP4 +3% (c1) to +16% (c32) req/s, TP2 +2.5% to +7.5%,
greedy outputs bit-identical, gsm8k and a long-context probe unchanged.

* Qwen4-Exp SP: review fixes (aiter reduce-scatter check, PP guard, README note)

- Narrow the aiter reduce-scatter path with isinstance on aiter's
  CustomAllreduce instead of a private GroupCoordinator helper.
- Skip the sequence-parallel path when this rank does not start at layer 0
  (the residual is sharded at an absolute layer index).
- README: note the discarded TP4 c32 baseline round.

* Qwen4-Exp SP: refresh README results from the re-measurement

* Qwen4-Exp SP: gather the mixer output, and shard eager target-verify batches

- At the end of a sequence-parallel forward, run the final mixer on the local
  rows and all-gather its [T, hidden] output. The [T, hc_count * hidden]
  residual (HC state) is gathered only when the forward captures hidden
  states (speculative drafting, return_hidden_states), which is 1/hc_count
  of the gather bytes otherwise.
- Gate on EXTEND / MIXED / TARGET_VERIFY instead of
  is_extend_without_speculative: eager target-verify batches above the
  threshold are sharded too (captured ones never are), and split prefill is
  no longer let through.

* Add error handling for CustomAllreduce import

Handle ImportError for CustomAllreduce import.

Co-authored-by: Copilot Autofix powered by AI <[email protected]>

* Qwen4-Exp SP: list the sequence-parallel switches in the MI308X launch script (commented out)

* Qwen4-Exp SP: enable the sequence-parallel residual by default

SGLANG_QWEN4_SEQ_PARALLEL now defaults to on (0 restores the all-reduce), and the
MI308X launch script exports both SP switches with overridable defaults.

* Qwen4-Exp SP: keep the all-reduce in tc_piecewise and any captured prefill

get_is_capture_mode() only covers decode capture and breakable graphs; also skip
the sequence-parallel plan inside tc_piecewise CUDA graphs and whenever the current
stream is capturing, since the row split depends on the batch's token count.

---------

Co-authored-by: yicyang <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
(cherry picked from commit 15055ff)

* [AMD] Qwen4-Exp SP: overlap the reduce-scatter and both all-gathers with compute over SDMA (mori) (#89)

* Qwen4-Exp SP: overlap the reduce-scatter and both all-gathers with compute over SDMA

On top of the sequence-parallel residual, each communication runs on the SDMA
copy engines under compute:
- reduce-scatter: o_proj / GDN out_proj run in row chunks, peers' blocks first,
  and each chunk is pushed to its owner as soon as it is computed; the owner
  waits per chunk right before combining it (the MoE output is pushed the same way);
- attention / GDN input all-gather: the input projection runs on the local rows
  while peers' rows land, then on each peer block as it arrives;
- MoE input all-gather: hc_combine / hc_norm / mix run in row ranges and each
  range is pushed as soon as it is mixed.

The default mori backend posts the copies with one-wave kernels on the compute
stream (mori CCO SDMA put with an engine-side completion signal), so no side
streams or cross-stream events are needed; the hip backend (hipMemcpyAsync on
per-peer copy streams) is used when mori cannot run in the process.

Switches (on by default, only with SGLANG_QWEN4_SEQ_PARALLEL):
SGLANG_QWEN4_SP_SDMA_RS / _AG / _AG_MOE, SGLANG_QWEN4_SP_SDMA_BACKEND (mori|hip),
SGLANG_QWEN4_SP_SDMA_RS_TRANSPORT (bf16|fp8), SGLANG_QWEN4_SP_SDMA_RS_CHUNKS and
SGLANG_QWEN4_SP_SDMA_AG_MOE_CHUNKS (auto by TP size). The MI308X launch script
exports them and preloads ROCm's libdrm for mori.

* Qwen4-Exp SP SDMA: mori only, pin the mori dependency

Drop the hip copy-stream backend: every SDMA push and wait goes through mori.
Without a usable mori (not importable, MORI_ENABLE_SDMA unset, or the libdrm
preload missing) the layers log one warning and keep the aiter reduce-scatter /
all-gather of plain sequence parallelism. SGLANG_QWEN4_SP_SDMA_BACKEND is gone.

mori is pinned like PyHIP in python/pyproject_other.toml (ROCm/mori 752efd3);
benchmark/qwen4_seq_parallel/mori/ adds the MI308X engine-spread patch and
install_mori.sh, which builds that commit with the patch and BUILD_CCO_SDMA=ON.
The README lists the tested versions (ROCm 7.14, torch 2.12, FlyDSL 0.3.2).

* Move the mori install script and MI308X patch to 3rdparty/amd/mori

They install a runtime dependency rather than run a benchmark; 3rdparty/amd
already holds the same clone + patch + build pattern for rocmProfileData.

* 3rdparty/amd/mori: engine-spread patch as proposed upstream

Keep the per-engine counts in an AnvilLib member sized for the full 32-bit
engine mask (the old 8-entry static array could be indexed past its end on
parts with more engines), and only re-pick an engine for a peer link that
gets its first channels.

* 3rdparty/amd/mori: engine-spread patch without an env var

Track the upstream proposal: on MI308X a new peer link is only moved when its
engine collision involves a folded (fused-off) recommendation, and only onto
an xGMI engine the GPU does not use yet. Drop MORI_SDMA_SPREAD_MI308X from the
launch script and README.

* Pin mori to apinge/mori qwen3.8-flash-sdma, drop the engine-spread patch

The branch carries the MI308X SDMA engine spread (apinge/mori#1), so the
local patch is no longer needed. install_mori.sh now only builds the pinned
branch (MORI_REF also takes a commit or pull ref).

* Drop 3rdparty/amd/mori/install_mori.sh

With the patch gone, the amd_mori pin in pyproject_other.toml builds the same
thing (BUILD_CCO_SDMA is on by default); the README shows pip --target for
installs outside the environment.

* SdmaReduceScatter: drop the chunk-count upper bound

_MAX_CHUNKS sized the hip backend's per-chunk flags; with mori the chunk
waits use the engine's signal counter, so nothing bounds chunks above.

* hyperconnection: revert formatting-only changes

* launch script: list the SP SDMA chunk knobs as optional settings

All SP SDMA variables now appear in the MI308X launch script; the two chunk
counts stay commented out so unset keeps the measured per-TP defaults.

* launch script: export the SP SDMA chunk counts with their per-TP defaults

* Qwen4-Exp SP SDMA: address the Copilot review

- Fall back to aiter when the attention TP group spans nodes (HIP IPC maps
  only within one node) or when mori set up no SDMA queue (puts would move
  no bytes and the waits would never return); checked once per process.
- Keep the SDMA reduce-scatter to bf16, the dtype its reduce kernel sums.
- Read max_prefill_tokens through runtime_context.get_schedule() instead of
  the legacy get_global_server_args().
- Drop each consumed projection chunk / all-gather input from the in-flight
  handles, which the model keeps on its carrier tensors.

* README: libibverbs-dev is a build-time requirement missing from the base image

* Install libibverbs-dev before the hip extras in the ROCm image and AMD CI

amd_mori, pinned in the hip extras, builds from source and its setup.py stops
without the ibverbs headers, which the base image does not ship.

* Document the libibverbs-dev install in the README instead of the image / CI

Revert the Dockerfile and AMD CI changes; the README now lists the install
steps for mori (ibverbs headers, then the pinned amd_mori).

* README: mark image vs installed dependencies, fix the mori import check

Only mori and libibverbs-dev are added on top of the ROCm 7.14 image; FlyDSL
and torch stay the image's. Drop --no-deps (mori declares no runtime deps)
and run the import check with the libdrm preload, without which importing
mori next to FlyDSL can crash.

---------

Co-authored-by: yicyang <[email protected]>
(cherry picked from commit d4edb47)

* Qwen4 CI: install mori for the SP SDMA prefill path; port fixups for v0.5.21

The two cherry-picked PRs (#80, #89) were resolved onto qwen4_v0.5.21 as follows:
- keep the branch's PP-aware hyper_connection_mixer, PP proxy tensors and
  AuxHiddenStateList; sequence parallelism is also off when pp_size > 1, since a
  non-last stage hands its residual on in proxy tensors;
- the launch-script changes go to evaluation/launch_qwen38_..._pure_tp_4_or_8_or_2.sh,
  which now enables SP + SDMA by default, so the Qwen3.8 TP2 CI cases run with them;
- get_attn_tp_group comes from parallel_state (dp_attention no longer re-exports it);
- isort / ruff-format on the touched files.

evaluation/Dockerfile.ci installs libibverbs-dev and amd_mori (apinge/mori
qwen3.8-flash-sdma) before the candidate install: the srt_hip extras pin mori by
URL, which the CI requirement check cannot install. The guide documents both.

---------

Co-authored-by: yicyang <[email protected]>
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Co-authored-by: Xiake Sun <[email protected]>
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.

3 participants