Skip to content

feat: add FlashComm1 and MMRS fusion support for Qwen3.5 NPU.#1890

Open
Cooofish wants to merge 23 commits into
xLLM-AI:mainfrom
Cooofish:flashcomm1-pr-default-off
Open

feat: add FlashComm1 and MMRS fusion support for Qwen3.5 NPU.#1890
Cooofish wants to merge 23 commits into
xLLM-AI:mainfrom
Cooofish:flashcomm1-pr-default-off

Conversation

@Cooofish

@Cooofish Cooofish commented Jul 6, 2026

Copy link
Copy Markdown

Summary

This PR adds FlashComm1 (FC1) support for NPU tensor-parallel inference.

FC1 is a prefill-side communication optimization for long-context workloads. It shards hidden states along the sequence dimension across TP ranks, lets supported row-parallel linear layers consume the sharded layout, and uses Matmul + ReduceScatter fusion to reduce part of the communication and launch overhead in prefill.

The feature is disabled by default:

--enable_flashcomm1=false
--enable_mmrs_fusion=false

To enable the full FC1 path:

--enable_flashcomm1=true \
--enable_mmrs_fusion=true \

More details about design, usage, suitable workloads, and validation guidance are documented in:

Main Changes

  • Add FC1 runtime options, global flags, model context fields, and worker/master option propagation.
  • Add FlashComm1Context and helper functions for prefill sequence padding, sequence sharding, reduce, gather, and row-parallel layout handling.
  • Add NPU matmul_reduce_scatter kernel API backed by torch_npu npu_mm_reduce_scatter_base.
  • Integrate fused MMRS into supported row-parallel linear layers with fallback to the original matmul + reduce path when MMRS is not applicable.
  • Wire FC1 into Qwen3 and Qwen3-Next hybrid model paths.
  • Keep model output semantics unchanged by gathering back to normal hidden states before returning from the FC1 prefill path.
  • Gate FC1 to prefill-only long-context cases by default: dp=1, cp=1, tp>=8, and prefill_tokens>=8192.
  • Keep FC1 disabled in decode. TPOT/decode throughput are not expected to directly benefit from this feature.

MMRS Integration

The MMRS path intentionally uses the torch_npu fused operator instead of implementing a local fused kernel in xLLM:

  • xLLM wrapper validates inputs, resolves the HCCL process group, selects comm_mode, and calls npu_mm_reduce_scatter_base.
  • Supported mmrs_comm_mode values are aiv, ai_cpu, and none.
  • The default mode remains aiv.
  • If a specific shape hits an AIV AICore issue, the path can fall back to ai_cpu through the existing mode selection logic.
  • Unsupported MMRS cases return to the caller-side fallback path instead of hiding fallback behavior inside the wrapper.

Default Activation Policy

FC1 and MMRS are both opt-in. Even when enabled by flags, FC1 only becomes active when runtime conditions are suitable.

Default suitable case:

  • NPU backend.
  • Prefill phase.
  • Long input, currently prefill_tokens >= 8192.
  • tp >= 8.
  • dp = 1.
  • cp = 1.
  • BF16/FP16 non-quantized row-parallel paths.

Cases where FC1 is disabled or expected to have limited benefit:

  • Decode phase.
  • Short prompts such as 2K input.
  • Long-output workloads where decode dominates total latency.
  • tp < 8, dp > 1, or cp > 1.
  • Quantized row-parallel paths, which currently skip fused MMRS.

Validation

Build validation performed locally:

NPU_HOME_PATH=/usr/local/Ascend/cann-9.0.0 \
PYTHON_INCLUDE_PATH=/usr/local/python3.11.15/include/python3.11 \
PYTORCH_INSTALL_PATH=/usr/local/python3.11.15/lib/python3.11/site-packages/torch \
PYTORCH_NPU_INSTALL_PATH=/usr/local/libtorch_npu \
LIBTORCH_ROOT=/usr/local/python3.11.15/lib/python3.11/site-packages/torch \

Result: passed, producing build_flash_npu3/xllm/xllm.

Ascend A3 and ACL Graph compatibility

On Ascend A3 (Ascend910_93), some CANN 9.0-based xllm_ops/ATB
packages may incorrectly select the 910A CustomPagedAttention runner
when ACL Graph is enabled. This can cause CustomPagedAttention setup
to fail with status 27.

This issue is independent of FlashComm1/MMRS. Use an xllm_ops build
that correctly classifies Ascend910_93 as a 910B-family device and
deploy the matching libatb_customize.so and libcustomize_ops.so
together.

Correctness checks performed locally:

  • TP=4, 2K input / 2K output, FC1 off vs FC1 on token IDs matched.
  • Chunked prefill active validation passed for long and uneven prompt lengths.
  • MMRS consistency validation passed with token mismatch = 0 and sampled logprob max diff < 0.03.

Performance and profiling checks performed locally:

  • The FC1-off/on matrix was run with Qwen3.5-27B, graph=true, 1K output, 8K/16K/32K input, parallel=2/4/8/16, and two warmup requests.
  • The selected primary matrix contains 72 individual measurements, covering 36 complete FC1-off/on comparisons collected from repeated TP=8 measurements. The July 19 single-round rerun is reported separately below and is not used to replace the repeated 32K multi-concurrency conclusion. The prior AICore failures were resolved for the reported matrix after deploying compatible custom-operator builds.
  • TP=2 and TP=4 were retained as flag/no-op controls. The table below reports TP=8 because the default runtime policy requires tp >= 8 before FC1 becomes active.
  • Positive percentages consistently mean that FC1 on is better: lower TTFT/TPOT/latency or higher throughput. TTFT uses the stable post-warmup request average and remains sensitive to scheduler/batch composition.
Input Parallel TTFT gain TPOT gain Prompt throughput gain Decode throughput gain Request throughput gain Latency gain
8K 2 +3.95% -0.01% +0.19% +0.19% +0.19% +0.19%
8K 4 +5.35% -2.08% -1.58% -1.58% -1.58% -1.61%
8K 8 +5.57% -1.25% -0.68% -0.68% -0.68% -0.70%
8K 16 +4.06% -2.10% -1.34% -1.34% -1.34% -1.37%
16K 2 +3.26% +0.92% +1.12% +1.12% +1.12% +1.10%
16K 4 +1.54% +4.52% +6.07% +6.07% +6.07% +4.25%
16K 8 +1.27% +3.08% -0.49% -0.49% -0.49% +2.84%
16K 16 +1.38% +0.06% +0.29% +0.29% +0.29% +0.30%
32K 2 +6.10% -0.60% +0.40% +0.40% +0.40% +0.39%
32K 4 +3.95% -0.13% +2.10% +2.10% +2.10% +1.96%
32K 8 +3.63% +1.15% +2.65% +2.65% +2.65% +1.71%
32K 16 +1.94% +1.97% +2.60% +2.60% +2.60% +1.97%
  • Prefill-focused profiling confirmed that FC1+MMRS is active:
    • MatmulReduceScatterV2 appears when FC1/MMRS is enabled.
    • Part of the original row-parallel communication path is replaced by MMRS.
    • allReduce time/count decreases in FC1-on traces.

Performance Notes

FC1 is not a general-purpose speedup switch. In the selected multi-round TP=8 matrix, the most balanced results are 32K input at parallel=4/8/16: TTFT improves by 1.94%-3.95%, prompt/decode/request throughput improves by 2.10%-2.65%, and average latency improves by 1.71%-1.97%. The 32K, parallel=2 case also improves TTFT by 6.10%, with throughput and latency essentially unchanged to slightly better.

The 8K cases improve TTFT by 3.95%-5.57%, but throughput and average latency are flat to about 1.6% worse. At 16K, parallel=2 is balanced (+3.26% TTFT and about +1.1% throughput), while parallel=8/16 improves TTFT by about 2.6% but regresses end-to-end throughput substantially. The 16K, parallel=4 result was remeasured three times; the final repeat is effectively neutral (+0.40% TTFT, -0.33% throughput), showing why a single TTFT average must not be interpreted as a stable FC1 gain. These results reinforce that FC1 primarily targets prefill latency; TTFT improvement does not guarantee an end-to-end throughput improvement when decode and layout/communication overhead dominate.

Current profiling limitations:

  • Extra gather may be needed after reduceScatter to restore the expected full hidden-state layout.
  • MMRS has fixed overhead and is not beneficial for small decode-like shapes.
  • Layout transforms such as concat/transpose and pad/unpad reduce the net gain.
  • End-to-end TTFT is sensitive to scheduler batching variance.
  • Quantized row-parallel paths currently skip fused MMRS.

For this reason, FC1 remains disabled by default and should be enabled only for suitable long-prefill deployments.

Reviewer Focus

Please focus review on:

  • Default-off behavior for both FC1 and MMRS.
  • Runtime activation gating for long-prefill only.
  • MMRS shape checks, comm_mode selection, and fallback behavior.
  • Sequence sharding, padding, gather, and output-layout correctness.
  • Qwen3 and Qwen3-Next integration points.
  • Runtime/model-output semantics after FC1 gathers hidden states back.

Recent Updates

MMRS wrapper simplification

  • Simplified the FC1 MMRS C++ wrapper so it only validates inputs, resolves the HCCL group, selects torch_npu comm_mode, and calls npu_mm_reduce_scatter_base.
  • Removed duplicate local torch::matmul fallback from the wrapper. Unsupported MMRS cases now return an empty tensor and let the existing row-parallel fallback remain in the caller.
  • This keeps the integration closer to the upstream torch_npu operator and reduces review surface.

Gemini review fixes

  • Kept FlashComm1Context as a plain data struct and moved sequence-sharding helpers to free functions.
  • Removed duplicate row-padding helper from linear.cpp and reused the shared FC1 helper.
  • Added defensive defined() checks before inspecting MMRS input tensor metadata.
  • Verified that the previously flagged production paths already use ModelConfig::get_instance().backend(), EPLBConfig::get_instance().expert_parallel_degree(), preserve the ep_size == 1 single-reduce MoE optimization, and no longer contain the flagged Qwen3 ATB int64_t hostData vectors.

Diff-scope cleanup

  • Restored CMake helper files and third-party submodule pointers to match upstream main.
  • Restored top-level CMakeLists.txt to match upstream main.
  • Removed unused MMRS parameters and noisy success-path FC1 logs.
  • The PR now keeps CMake helpers, third-party pointers, and local build-environment inference out of the FlashComm1 change set.

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request introduces the Flash Communication 1 (FC1) sequence-parallel optimization for tensor parallel inference on NPU, integrating it into layers like RowParallelLinear and FusedMoE, and adding a fused matmul_reduce_scatter NPU kernel. The review feedback identifies several style guide violations, including the use of member functions in the FlashComm1Context struct and direct access to FLAGS_ global variables. It also highlights critical issues such as potential undefined behavior from missing tensor definition checks, duplicate helper functions, a performance regression in MoE reduction when ep_size == 1, and a type mismatch where int64_t is used instead of int32_t for CANN/ATB host data.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread xllm/core/common/flash_comm1_context.h
Comment thread xllm/core/layers/npu_torch/fused_moe.cpp Outdated
Comment thread xllm/core/framework/hf_model_loader.cpp Outdated
Comment thread xllm/core/kernels/npu/matmul_reduce_scatter.cpp Outdated
Comment thread xllm/core/layers/common/linear.cpp Outdated
Comment thread xllm/core/layers/npu_torch/fused_moe.cpp Outdated
Comment thread xllm/core/layers/npu/npu_qwen3_decoder_layer_impl.h Outdated
@Cooofish
Cooofish force-pushed the flashcomm1-pr-default-off branch 2 times, most recently from a2db15a to dd852e4 Compare July 6, 2026 09:35
@Cooofish Cooofish changed the title Add FlashComm1 and MMRS fusion support for Qwen3.5 NPU feat:Add FlashComm1 and MMRS fusion support for Qwen3.5 NPU Jul 6, 2026
@Cooofish Cooofish changed the title feat:Add FlashComm1 and MMRS fusion support for Qwen3.5 NPU feat: Add FlashComm1 and MMRS fusion support for Qwen3.5 NPU Jul 6, 2026
@Cooofish
Cooofish force-pushed the flashcomm1-pr-default-off branch 2 times, most recently from 9bb1d73 to 2c1850e Compare July 7, 2026 01:58
@Cooofish Cooofish changed the title feat: Add FlashComm1 and MMRS fusion support for Qwen3.5 NPU feat: Add FlashComm1 and MMRS fusion support for Qwen3.5 NPU. Jul 7, 2026
Comment thread xllm/xllm.cpp Outdated
Comment thread xllm/pybind/bind.cpp
Comment thread xllm/core/layers/npu_torch/qwen3_next_hybrid_decoder_layer_base.cpp Outdated
Comment thread xllm/core/kernels/npu/matmul_reduce_scatter.cpp Outdated
pjgao and others added 5 commits July 7, 2026 11:25
- Infer NPU Python, PyTorch, and torch_npu paths during CMake configure when the environment is unset.

- Propagate CARGO_HOME into Rust custom commands and align the workspace Cargo mirror name with the root Cargo config.

- Remove stale selected-gather and Device::type_str() remnants after the FC1 context refactor.

- Keep FC1 default-off and raise the activation threshold to long-prefill TP=8 cases.
- Keep the wrapper focused on validating inputs, resolving the HCCL group, selecting comm_mode, and invoking torch_npu npu_mm_reduce_scatter_base.

- Return an empty tensor on unsupported inputs so the existing row-parallel matmul plus reduce_scatter fallback remains owned by the caller.

- Remove the duplicate local torch::matmul fallback and reject-reason string builder to make the FC1 MMRS path easier to review and maintain.
Comment thread cmake/cargo_library.cmake
@yingxudeng yingxudeng changed the title feat: Add FlashComm1 and MMRS fusion support for Qwen3.5 NPU. feat: add FlashComm1 and MMRS fusion support for Qwen3.5 NPU. Jul 21, 2026
@Cooofish

Cooofish commented Jul 21, 2026

Copy link
Copy Markdown
Author

本地python setup.py build test已通过

100% tests passed, 0 tests failed out of 833

Total Test time (real) = 125.67 sec

The following tests did not run:
51 - AnthropicServerFeaturesTest.ToolChoiceAuto (Disabled)
52 - AnthropicServerFeaturesTest.ToolChoiceSpecific (Disabled)
53 - AnthropicServerFeaturesTest.StopReasonVariations (Disabled)
54 - AnthropicServerFeaturesTest.ToolChoiceAutoExplicit (Disabled)
55 - AnthropicServerFeaturesTest.ToolChoiceAny (Disabled)
56 - AnthropicServerFeaturesTest.ToolChoiceSpecificTool (Disabled)
57 - AnthropicServerFeaturesTest.ToolUseBlockStructure (Disabled)
58 - AnthropicServerFeaturesTest.StopReasonEndTurn (Disabled)
59 - AnthropicServerFeaturesTest.StopReasonMaxTokens (Disabled)
60 - AnthropicServerFeaturesTest.StopReasonStopSequence (Disabled)
61 - AnthropicServerFeaturesTest.Completion (Disabled)
62 - AnthropicServerFeaturesTest.CompletionStream (Disabled)
63 - AnthropicServerFeaturesTest.ChatCompletion (Disabled)
64 - AnthropicServerFeaturesTest.ChatCompletionStream (Disabled)
65 - AnthropicServerFeaturesTest.SystemPrompt (Disabled)
66 - AnthropicServerFeaturesTest.StopSequences (Disabled)
67 - AnthropicFunctionCallingTest.FunctionCallingFormat (Disabled)
68 - AnthropicFunctionCallingTest.FunctionCallingWithWeatherTool (Disabled)
69 - AnthropicFunctionCallingTest.FunctionCallingStreamingSimple (Disabled)
70 - AnthropicFunctionCallingTest.ToolChoiceRequired (Disabled)
71 - AnthropicFunctionCallingTest.ToolChoiceSpecific (Disabled)
72 - AnthropicFunctionCallingTest.FunctionCallingStrictMode (Disabled)
73 - AnthropicFunctionCallingTest.FunctionCallingNoToolCall (Disabled)
74 - AnthropicFunctionCallingTest.FunctionCallingParallelTools (Disabled)
142 - OpenAIServerFeaturesTest.SampleSingleMatch (Disabled)
143 - OpenAIServerFeaturesTest.SampleMultipleMatchesStayOrdered (Disabled)
144 - OpenAIServerFeaturesTest.SampleRejectsOutOfRangeLogprobs (Disabled)
145 - OpenAIServerFeaturesTest.CompletionsRegressionSmoke (Disabled)
146 - OpenAIServerFeaturesTest.ChatCompletionsRegressionSmoke (Disabled)
443 - RejectionSamplerTest.RandomFused (Skipped)
444 - RejectionSamplerTest.RandomFusedRecoveryDistribution (Skipped)
556 - ContinuousSchedulerFactoryTest.ModelPartitionCpDoesNotBuildMixedBatch (Skipped)
I20260721 17:52:23.669031 1718187 setup.py:786] ================================================================================
I20260721 17:52:23.669207 1718187 setup.py:787] Step 2: Running ReduceScatterMultiDeviceTest sequentially...
I20260721 17:52:23.669245 1718187 setup.py:788] ================================================================================
Test project /root/g00510989/xllm_th/xllm_pr1890_format_fix/build/cmake.linux-aarch64-cpython-311
No tests were found!!!
W20260721 17:52:23.720484 1718187 setup.py:757] No tests matched the pattern (this is OK for some backends).
I20260721 17:52:23.720615 1718187 setup.py:786] ================================================================================
I20260721 17:52:23.720650 1718187 setup.py:787] Step 3: Running BroadcastMultiDeviceTest sequentially...
I20260721 17:52:23.720679 1718187 setup.py:788] ================================================================================
Test project /root/g00510989/xllm_th/xllm_pr1890_format_fix/build/cmake.linux-aarch64-cpython-311
No tests were found!!!
W20260721 17:52:23.767794 1718187 setup.py:757] No tests matched the pattern (this is OK for some backends).
I20260721 17:52:23.767932 1718187 setup.py:786] ================================================================================
I20260721 17:52:23.767968 1718187 setup.py:787] Step 4: Running DeepEPMultiDeviceTest sequentially...
I20260721 17:52:23.767999 1718187 setup.py:788] ================================================================================
Test project /root/g00510989/xllm_th/xllm_pr1890_format_fix/build/cmake.linux-aarch64-cpython-311
No tests were found!!!
W20260721 17:52:23.815568 1718187 setup.py:757] No tests matched the pattern (this is OK for some backends).
I20260721 17:52:23.815700 1718187 setup.py:786] ================================================================================
I20260721 17:52:23.815736 1718187 setup.py:787] Step 5: Running AttentionMultiDeviceTest sequentially...
I20260721 17:52:23.815778 1718187 setup.py:788] ================================================================================
Test project /root/g00510989/xllm_th/xllm_pr1890_format_fix/build/cmake.linux-aarch64-cpython-311
No tests were found!!!
W20260721 17:52:23.861909 1718187 setup.py:757] No tests matched the pattern (this is OK for some backends).
I20260721 17:52:23.862036 1718187 setup.py:786] ================================================================================
I20260721 17:52:23.862072 1718187 setup.py:787] Step 6: Running FusedMoEAll2AllMultiDeviceTest sequentially...
I20260721 17:52:23.862099 1718187 setup.py:788] ================================================================================
Test project /root/g00510989/xllm_th/xllm_pr1890_format_fix/build/cmake.linux-aarch64-cpython-311
No tests were found!!!
W20260721 17:52:23.909828 1718187 setup.py:757] No tests matched the pattern (this is OK for some backends).
I20260721 17:52:23.909966 1718187 setup.py:797] ================================================================================
I20260721 17:52:23.910008 1718187 setup.py:798] All tests passed!
I20260721 17:52:23.910040 1718187 setup.py:799] ================================================================================

commit b56d8e5也测试通过

Triton NPU tests:
============ 210 passed, 2 skipped, 1 warning in 192.30s (0:03:12) =============

CTest:
I20260722 10:21:48.711465 setup.py:724] Test parallelism: 16 (set CTEST_PARALLEL to override)

I20260722 10:23:49.394614 setup.py:797] ================================================================================
I20260722 10:23:49.394642 setup.py:798] All tests passed!
I20260722 10:23:49.394665 setup.py:799] ================================================================================

Preserve the latest main quantization refactor while restoring the FC1/MMRS row-parallel overload, including its guarded MMRS fallback and tensor-defined checks.

Formatting was validated with the repository clang-format configuration.
#include "common/global_flags.h"
#include "framework/parallel_state/parallel_state.h"

DEFINE_bool(enable_flashcomm1,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

为啥放这里?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

确实不该放这里,我把这些配置定义移到了KernelConfig,改成通过 from_flags() 解析,并在create_options()中传递给FlashComm1Options

: std::nullopt;
CHECK(weight_scale.has_value() && weight_scale.value().defined())
<< "weight_scale is required for w8a8_dynamic quant matmul.";
#if defined(USE_DCU)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

为什么突然考虑 DCU?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

这里的 DCU 分支是复制原RowParallel forward量化逻辑时带入的,不该在FC1/MMRS用。已将该 overload 和调用路径限制到 USE_NPU。

Comment thread xllm/xllm.cpp Outdated
.rank_tablefile(eplb_config.rank_tablefile())
.expert_parallel_degree(eplb_config.expert_parallel_degree())
.enable_chunked_prefill(scheduler_config.enable_chunked_prefill())
.enable_flashcomm1(FLAGS_enable_flashcomm1)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

怎么突然用gflag

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

和第一处是同一问题,已经改为把这些配置定义移到KernelConfig,通过 from_flags() 解析,并在create_options()中传递给FlashComm1Options

Move FC1 and MMRS flags into KernelConfig, remove direct gflag access from the runtime context, and limit the reduce-mode FC1 path to NPU. Preserve the existing defaults and Options propagation.
Comment thread xllm/core/layers/common/linear.cpp Outdated
auto output_shape = mmrs_input.sizes().vec();
output_shape[0] = fc1_ctx->padded_local_num_tokens;
output_shape[1] = weight_.size(0);
torch::Tensor mmrs_output = torch::empty(output_shape, input.options());

@yingxudeng yingxudeng Jul 22, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

torch::empty 了,但是实际没有用?是不是不太合理?只需要shape吧

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

确实不合理。现已删除 torch::empty 以及整个封装链路中无效的 output 参数。

x = moe_mlp_(x, input_params);
} else {
x = mlp_(x);
x = mlp_->forward(x);

@yingxudeng yingxudeng Jul 22, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why are we calling both mlp_(x) and mlp_->forward(x) here?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

这里可能是对 diff 的误解。x = mlp_(x) 是被删除的代码,当前实现中只保留了 x = mlp_->forward(x),没有同时调用mlp_(x) 和 mlp_->forward(x)

@yingxudeng yingxudeng Jul 22, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

sorry. 为什么改成了 x = mlp_->forward(x);

input = xllm::parallel_state::scatter(input, process_group_);
}

xllm::kernel::ScaledQuantizeParams quantize_params;

@yingxudeng yingxudeng Jul 22, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Does torch::Tensor RowParallelLinearImpl::forward heavily duplicate the existing code?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

原本考虑避免本次改动影响其他后端原有的量化、scatter 和 reduction 行为,保留了原 forward 路径。
在commit f189579中已经改为:

保留原有 forward(input) 和 FC1 使用的 forward(input, reduce_mode) 两个入口,但两个入口现在统一调用同一个 forward_impl()。量化、scatter、matmul、MMRS、fallback 和结果通信逻辑只保留一份。
原接口会根据 enable_result_reduction_ 映射到 NONE 或 ALL_REDUCE,维持原有行为;只有显式传入 REDUCE_SCATTER 或 MATMUL_REDUCE_SCATTER 时才会启用 FC1 的 sequence-sharded 处理,避免影响其他 RowParallelLinear 调用路径。

已通过 clang-format 和 NPU 单文件编译检查。

return gathered;
}

torch::Tensor maybe_pad_for_reduce(const torch::Tensor& input,

@yingxudeng yingxudeng Jul 22, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Is maybe_pad_for_reduce unused?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

是的。已删除 maybe_pad_for_reduce 的声明和实现。

Cooofish and others added 4 commits July 22, 2026 15:39
Remove the unused preallocated MMRS output parameter because torch_npu returns the result tensor directly. Also delete the unreferenced maybe_pad_for_reduce helper.
Route the existing and FC1-aware RowParallelLinear forward overloads through one implementation. Preserve the default reduction behavior while applying sequence-sharded handling only to explicit FC1 reduce modes.
@Cooofish

Copy link
Copy Markdown
Author

最新commit 971dd79已本地build test通过
100% tests passed, 0 tests failed out of 845
Total Test time (real) = 106.23 sec
All tests passed!


// MLP forward
if (moe_mlp_) {
x = moe_mlp_(x, input_params);

@yingxudeng yingxudeng Jul 22, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

对应的 moe 不用改嘛?moe 版本精度是否有问题

mmrs_weight_t_.size(0) == weight_.size(1) &&
mmrs_weight_t_.size(1) == weight_.size(0);
if (!valid) {
mmrs_weight_t_ = weight_.transpose(0, 1).contiguous();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

这个操作不能在模型初始化或者 load_state_dict 末尾做吗?

const int64_t world_size = process_group->world_size();
const int64_t k = a.size(1);
if (world_size == 2) {
return k == 3072 || k == 8704;

@yingxudeng yingxudeng Jul 22, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

不要用魔法数字

if (residual.size(0) == ctx.original_num_tokens) {
return shard_sequence(residual, ctx);
}
CHECK_EQ(residual.size(0), ctx.padded_local_num_tokens)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

走到这里的时候,是否是必定失败的。下面的 return residual; 是不是死代码

const FlashComm1Context& ctx) {
auto gathered = gather_sequence(input, ctx);
if (ctx.pad_size > 0) {
return gathered.slice(0, 0, ctx.original_num_tokens);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

gather_sequence 里面也有 gathered.slice(0, 0, ctx.original_num_tokens); 和这里的操作区别目的是什么

const int64_t shard_start =
static_cast<int64_t>(ctx.tp_rank) * ctx.padded_local_num_tokens;
const int64_t shard_end = shard_start + ctx.padded_local_num_tokens;
return padded_input.slice(0, shard_start, shard_end).contiguous();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

padded_input = pad_rows_by_copy(input, ctx.padded_num_tokens); 和 padded_input.slice(0, shard_start, shard_end).contiguous(); 是不是多次copy了,能否优化?

}

torch::Tensor output;
#if !defined(USE_NPU)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

别用宏了,有判断可以用的。

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