Skip to content

[WS2][GEMM][Forward]: implement PR3 TP with FFN and batch-invariance tests - #293

Open
Flink-ddd wants to merge 4 commits into
RL-Align:testfrom
Flink-ddd:feat/pr3-tp-ffn
Open

[WS2][GEMM][Forward]: implement PR3 TP with FFN and batch-invariance tests#293
Flink-ddd wants to merge 4 commits into
RL-Align:testfrom
Flink-ddd:feat/pr3-tp-ffn

Conversation

@Flink-ddd

@Flink-ddd Flink-ddd commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator

resolved #239 (PR3 Forward track)

Overview

This PR implements PR3: Tensor Parallel (TP) with FFN for the Qwen3-8B architecture, establishing the foundational orchestration, weight slicing, autograd communication mapping, and batch-invariance verification framework.

Key Changes

  1. tensor_parallel.py:
    Introduced FFNContext and implemented TP weight slicing for gate_weight, up_weight, and down_weight.
    Implemented TensorParallelFFN orchestration module with customized autograd communication mapping.

  2. test_tensor_parallel_ffn.py: Added TP=2 Gloo multi-process correctness, backward communication placement, and batch/padding invariance tests.

all_reduce Placement & Logic:

  1. Down (RowParallel): Each rank computes a local partial output [..., H]. Forward performs a TP all_reduce(SUM) to yield the replicated residual stream output. The backward path acts as an identity (dOutput is used directly as local dHidden_i without an extra TP all_reduce on [..., I/TP]).
  2. Gate/Up (ColumnParallel): Forward and SwiGLU maintain local intermediate shards. In the backward path, local dX tensors are first accumulated via autograd, followed by a single TP all_reduce(SUM) on the combined [..., H] tensor.

Constraints & Guardrails:

  1. Excluded CP weight gradient reduction and SP AG/RS for this PR scope.
  2. Enforced deterministic GEMM by rejecting default torch.matmul to strictly preserve the batch-invariance contract.

Verification & Test Results

  1. Local Validation
    tests/test_tensor_parallel_ffn.py: 5 passed
    tests/test_swiglu.py: 22 passed (81 skipped)
    ruff linting: Passed

  2. GPU Hardware Validation (Pending)
    Reserved section for multi-GPU hardware test metrics and execution logs:

Summary by CodeRabbit

  • New Features

    • Added tensor-parallel support for Qwen-style feed-forward neural networks.
    • Added automatic weight sharding and distributed output reduction.
    • Added support for constructing modules from full model weights.
    • Added validation for parallel execution contexts and deterministic computation.
  • Tests

    • Added coverage for forward and backward equivalence, sharding, batch handling, validation, and deterministic computation.

@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown

Review Change Stack

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

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d0c123cd-841c-42ac-bf99-dcb2c438bd3a

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 6e16552e-cc0c-4ebd-802c-92db060b7b6f

📥 Commits

Reviewing files that changed from the base of the PR and between 9490f25 and c117d32.

📒 Files selected for processing (1)
  • rl_engine/kernels/ops/pytorch/ffn/tensor_parallel.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • rl_engine/kernels/ops/pytorch/ffn/tensor_parallel.py

📝 Walkthrough

Walkthrough

Adds a Qwen3-style tensor-parallel SwiGLU FFN with explicit TP context validation, deterministic local GEMM injection, rank-local weight sharding, autograd-aware collectives, and spawned two-rank Gloo tests.

Changes

Qwen3 tensor-parallel FFN

Layer / File(s) Summary
FFN contracts and rank-local construction
rl_engine/kernels/ops/pytorch/ffn/__init__.py, rl_engine/kernels/ops/pytorch/ffn/tensor_parallel.py
Defines public FFN exports, validates TP context and deterministic GEMM configuration, shards Qwen3 weights, and constructs rank-local parameters.
Local execution and TP reductions
rl_engine/kernels/ops/pytorch/ffn/tensor_parallel.py
Implements Gate and Up projections, SwiGLU activation, local Down computation, autograd-aware collectives, and final TP output reduction.
Distributed correctness validation
tests/test_tensor_parallel_ffn.py
Adds two-rank Gloo tests for forward and backward equivalence, collective shapes, batch invariance, context validation, weight shards, and GEMM rejection.

Estimated code review effort: 4 (Complex) | ~45 minutes

Suggested reviewers: kjldefeated, inaniloquentee

Sequence Diagram(s)

sequenceDiagram
  participant TensorParallelFFN
  participant DeterministicGEMM
  participant TPGroup
  TensorParallelFFN->>TPGroup: copy replicated input for autograd
  TensorParallelFFN->>DeterministicGEMM: compute local Gate and Up projections
  DeterministicGEMM-->>TensorParallelFFN: return local projections
  TensorParallelFFN->>DeterministicGEMM: compute local Down partial
  TensorParallelFFN->>TPGroup: all-reduce Down partial
  TPGroup-->>TensorParallelFFN: return summed output
Loading

</details>

<!-- walkthrough_end -->
<!-- pre_merge_checks_walkthrough_start -->

<details>
<summary>🚥 Pre-merge checks | ✅ 2 | ❌ 3</summary>

### ❌ Failed checks (3 warnings)

|         Check name         | Status     | Explanation                                                                                                                                                                 | Resolution                                                                                                                                                 |
| :------------------------: | :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- |
|     Linked Issues check    | ⚠️ Warning | The PR omits required CP weight-gradient reductions and SM90/BF16/NCCL validation, and it does not demonstrate reuse of the specified deterministic GEMM primitives [`#239`]. | Implement CP reductions and the required deterministic SM90/BF16/NCCL paths, or narrow the PR and link it to an issue that matches the CPU Gloo FFN scope. |
| Out of Scope Changes check | ⚠️ Warning | TensorParallelFFN orchestration and autograd-aware collectives exceed `#239`'s GEMM/operator-only scope, which excludes complete MLP behavior and autograd.                   | Move FFN orchestration and autograd behavior to a separate issue or PR, or update `#239` to explicitly include those requirements.                           |
|     Docstring Coverage     | ⚠️ Warning | Docstring coverage is 36.67% which is insufficient. The required threshold is 80.00%.                                                                                       | Write docstrings for the functions missing them to satisfy the coverage threshold.                                                                         |

<details>
<summary>✅ Passed checks (2 passed)</summary>

|     Check name    | Status   | Explanation                                                                                                                                  |
| :---------------: | :------- | :------------------------------------------------------------------------------------------------------------------------------------------- |
| Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled.                                                                                  |
|    Title check    | ✅ Passed | The title clearly summarizes the PR's main change: implementing tensor parallelism for the FFN with forward GEMM and batch-invariance tests. |

</details>

</details>

<!-- pre_merge_checks_walkthrough_end -->
<!-- finishing_touch_checkbox_start -->

<details>
<summary>✨ Finishing Touches</summary>

<details>
<summary>🧪 Generate unit tests (beta)</summary>

- [ ] <!-- {"checkboxId": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "radioGroupId": "utg-output-choice-group-unknown_comment_id"} -->   Create PR with unit tests

</details>

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---

Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=RL-Align/RL-Kernel&utm_content=293)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>


<sub>Comment `@coderabbitai help` to get the list of available commands.</sub>

<!-- tips_end -->

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@rl_engine/kernels/ops/pytorch/ffn/tensor_parallel.py`:
- Around line 72-85: Add an explicit supported-configuration policy to
FFNContext initialization and the FFN execution boundary: validate the
process-group backend, rank mapping, topology, tensor device, and dtype before
any collective or GEMM. Reject unsupported combinations fail-closed with
diagnostics containing backend, group size/rank, TP size/rank, device, and dtype
metadata. Preserve CPU Gloo as an explicitly supported test configuration, and
ensure validation occurs before execution.
- Around line 249-269: Add validation in TensorParallelFFN construction before
registering gate_weight, up_weight, and down_weight to require all three weights
use the same device and dtype. Reject mismatches consistently for direct
construction, while preserving the existing _make_parameter registration and
shape handling.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 3b19d32b-fb5b-46bc-b35c-d9872323f45d

📥 Commits

Reviewing files that changed from the base of the PR and between 505512d and 9490f25.

📒 Files selected for processing (3)
  • rl_engine/kernels/ops/pytorch/ffn/__init__.py
  • rl_engine/kernels/ops/pytorch/ffn/tensor_parallel.py
  • tests/test_tensor_parallel_ffn.py

Comment on lines +72 to +85
if not dist.is_available() or not dist.is_initialized():
raise RuntimeError(
"FFNContext(tp_group=...) requires torch.distributed to be initialized."
)
group_size = dist.get_world_size(group=self.tp_group)
group_rank = dist.get_rank(group=self.tp_group)
size = group_size if self.tp_size is None else int(self.tp_size)
rank = group_rank if self.tp_rank is None else int(self.tp_rank)
if size != group_size:
raise ValueError(
f"ctx.tp_size={size} does not match tp_group world size={group_size}."
)
if rank != group_rank:
raise ValueError(f"ctx.tp_rank={rank} does not match tp_group rank={group_rank}.")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Validate supported TP execution configurations before execution.

FFNContext accepts every initialized process group. It does not validate or report the backend, rank mapping, topology, or supported device and dtype combination. A production BF16 execution can therefore enter an unsupported configuration and fail later in GEMM or all_reduce without the required fail-closed diagnostic.

Add an explicit supported-configuration policy. Validate the process-group backend in FFNContext. Validate tensor device and dtype at the FFN execution boundary. Report the required configuration metadata. Keep CPU Gloo support explicit for the test path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rl_engine/kernels/ops/pytorch/ffn/tensor_parallel.py` around lines 72 - 85,
Add an explicit supported-configuration policy to FFNContext initialization and
the FFN execution boundary: validate the process-group backend, rank mapping,
topology, tensor device, and dtype before any collective or GEMM. Reject
unsupported combinations fail-closed with diagnostics containing backend, group
size/rank, TP size/rank, device, and dtype metadata. Preserve CPU Gloo as an
explicitly supported test configuration, and ensure validation occurs before
execution.

Comment on lines +249 to +269
self.gate_weight = self._make_parameter(
gate_weight,
(self.local_intermediate_size, hidden_size),
"gate_weight",
device=device,
dtype=dtype,
)
self.up_weight = self._make_parameter(
up_weight,
(self.local_intermediate_size, hidden_size),
"up_weight",
device=device,
dtype=dtype,
)
self.down_weight = self._make_parameter(
down_weight,
(hidden_size, self.local_intermediate_size),
"down_weight",
device=device,
dtype=dtype,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reject mixed projection weight devices and dtypes.

shard_qwen3_ffn_weights rejects inconsistent full weights, but direct TensorParallelFFN(...) construction bypasses that validation. Mixed Gate, Up, and Down weights create a module that fails later in the injected GEMM, NativeSwiGLUOp, or Down projection.

Validate that all three registered parameters share one device and one dtype.

Proposed fix
         self.down_weight = self._make_parameter(
             down_weight,
             (hidden_size, self.local_intermediate_size),
             "down_weight",
             device=device,
             dtype=dtype,
         )
+        if not (
+            self.gate_weight.device == self.up_weight.device == self.down_weight.device
+        ):
+            raise ValueError("gate_weight, up_weight, and down_weight must share one device.")
+        if not (
+            self.gate_weight.dtype == self.up_weight.dtype == self.down_weight.dtype
+        ):
+            raise ValueError("gate_weight, up_weight, and down_weight must share one dtype.")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
self.gate_weight = self._make_parameter(
gate_weight,
(self.local_intermediate_size, hidden_size),
"gate_weight",
device=device,
dtype=dtype,
)
self.up_weight = self._make_parameter(
up_weight,
(self.local_intermediate_size, hidden_size),
"up_weight",
device=device,
dtype=dtype,
)
self.down_weight = self._make_parameter(
down_weight,
(hidden_size, self.local_intermediate_size),
"down_weight",
device=device,
dtype=dtype,
)
self.gate_weight = self._make_parameter(
gate_weight,
(self.local_intermediate_size, hidden_size),
"gate_weight",
device=device,
dtype=dtype,
)
self.up_weight = self._make_parameter(
up_weight,
(self.local_intermediate_size, hidden_size),
"up_weight",
device=device,
dtype=dtype,
)
self.down_weight = self._make_parameter(
down_weight,
(hidden_size, self.local_intermediate_size),
"down_weight",
device=device,
dtype=dtype,
)
if not (
self.gate_weight.device == self.up_weight.device == self.down_weight.device
):
raise ValueError("gate_weight, up_weight, and down_weight must share one device.")
if not (
self.gate_weight.dtype == self.up_weight.dtype == self.down_weight.dtype
):
raise ValueError("gate_weight, up_weight, and down_weight must share one dtype.")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rl_engine/kernels/ops/pytorch/ffn/tensor_parallel.py` around lines 249 - 269,
Add validation in TensorParallelFFN construction before registering gate_weight,
up_weight, and down_weight to require all three weights use the same device and
dtype. Reject mismatches consistently for direct construction, while preserving
the existing _make_parameter registration and shape handling.

@Flink-ddd
Flink-ddd changed the base branch from main to test August 13, 2026 02:39
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.

[WS2][GEMM] Qwen3-8B TP=2 CP=2 deterministic GEMM forward/backward + TP/CP reductions (2 nodes x 2 GPUs, BF16 SM90)

1 participant