Skip to content

[dtensor] fix conv1d output placement and group scaling - #186129

Closed
shuhuayu wants to merge 1 commit into
pytorch:mainfrom
shuhuayu:opt
Closed

shuhuayu wants to merge 1 commit into
pytorch:mainfrom
shuhuayu:opt

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Fixes DTensor dispatch for depthwise convolution (groups == in_channels == out_channels) when channels are sharded across the mesh — e.g. under FSDP or TP where the weight is Shard(0) and the input is Shard(1) on the channel dim. This is the layout used by GatedDeltaNet-style depthwise Conv1d in hybrid-attention models (Qwen3.5).

Depthwise conv treats each channel as an independent group, so channel-sharding requires no cross-rank communication — each rank computes its own channels locally. DTensor previously couldn't express or execute this, failing in both forward and backward.

The bugs

  1. Wrong forward output placement. convolution_single_dim_strategy only enumerated batch-dim sharding with a replicated weight. Channel-sharded input + out-channel-sharded weight matched no rule, so the propagator fell back to all-Replicate. The handler then ran on the still-sharded local tensors but labeled the result Replicate — so a 64-channel local output was tagged as the full 128-channel tensor. Downstream ops (e.g. full_tensor()) trusted the label and silently returned wrong data.

  2. Crash on groups (forward and backward). groups is a plain int that isn't sharded. With a channel-sharded weight (128 → 64 local channels per rank), the local conv was still called with groups=128:

    RuntimeError: Given groups=128, expected weight to be at least 128 at dimension 0, but got weight of size [64, 1, 4]
    

    The backward path had the identical defect and crashed the same way; it had gone unnoticed because earlier validation only exercised the forward/inference path.

The fix

Split across the two layers that own each concern, symmetric for forward and backward:

  • _ops/_conv_ops.py (sharding strategies) — add a depthwise channel-sharding rule to both strategies, gated on groups == in_channels == out_channels:

    • forward: [output=Shard(1), input=Shard(1), weight=Shard(0), (bias=Shard(0))]
    • backward: [grad_input=Shard(1), grad_weight=Shard(0), grad_bias=Shard(0), grad_output=Shard(1), input=Shard(1), weight=Shard(0)]

    grad_weight / grad_bias are Shard(0) (per out-channel, no cross-rank sum), not Partial, because the groups are independent. The propagator now returns the correct Shard(1) / Shard(0) placements with no redistribution.

  • _tp_conv.py (local arg adjustment) — strategies decide placements only; the local op still needs groups rescaled to the local weight shard (groups * local_out_channels // global_out_channels). This is factored into a shared _scaled_local_conv_groups helper, with a divisibility assertion guarding the even-sharding invariant, and is called from both convolution_handler and convolution_backward_handler.

Only depthwise conv is handled; regular (groups=1) and general grouped conv are untouched and fall through unchanged.

Test

test/distributed/tensor/test_convolution_ops.py::test_conv1d_channel_shard — depthwise Conv1d, input Shard(1) + weight Shard(0), asserts for both forward and backward:

  • zero communication (CommDebugMode),
  • correct Shard(1) output / gradient placement,
  • full_tensor() bit-identical (max_diff 0.0) to a single-device reference.

Regression tests (test_conv1d, test_conv1d_batch_shard, test_depthwise_convolution) still pass. Validated across FSDP, TP, and FSDP+EP configs, and end-to-end on a hybrid-attention model (Qwen3.5) whose GatedDeltaNet layers use depthwise Conv1d.

@pytorch-bot

pytorch-bot Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/186129

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

❌ 1 New Failure, 2 Unrelated Failures

As of commit 61acc31 with merge base a8eeede (image):

NEW FAILURE - The following job has failed:

  • pull / linux-jammy-aarch64-py3.10 / build-osdc (gh)
    Executing the custom container implementation failed. Please contact your self hosted runner administrator.

    AI verdict:

    The failure is a GitHub Actions self-hosted runner infrastructure error ("Executing the custom container implementation failed"), completely unrelated to the code changes in this commit which only modify distributed tensor convolution logic.

    Full reasoning on HUD →

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@anshul-si

Copy link
Copy Markdown
Contributor

@claude review this pr

@claude

claude Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Claude finished @anshul-si's task in 2m 31s —— View job


PR Review: [dtensor] fix conv1d output placement and group scaling

  • Read the PR diff and changed files
  • Analyze the conv ops strategy changes
  • Analyze the tp_conv handler changes
  • Post review feedback

Summary

This PR fixes two real bugs in DTensor dispatch for depthwise convolution (groups == in_channels == out_channels) when channels are sharded. The fix is split cleanly across two layers — strategy enumeration and local arg adjustment — which matches DTensor's existing separation of concerns.

Feedback

1. Correctness of the strategy rule (_conv_ops.py:196-209)

The depthwise gating condition is correct:

groups > 1 and groups == input_meta.shape[1] and groups == weight_meta.shape[0]

For depthwise conv, weight.shape[0] == out_channels == groups and input.shape[1] == in_channels == groups. Each group is truly independent so channel-sharding requires no communication. The placement assignments (Shard(1) for input/output channels, Shard(0) for weight out-channels, Shard(0) for bias) are all consistent and correct.

2. Group scaling in the handler (_tp_conv.py:273-277)

The formula groups * local_out_channels // global_out_channels is correct for even sharding. For depthwise conv on 2 ranks: 128 * 64 // 128 = 64, which is exactly right.

However, two concerns:

  • Integer division rounding: If groups * local_out_channels is not evenly divisible by global_out_channels (e.g., odd groups on an even mesh), this silently produces a wrong value. In practice, DTensor's shardability check should prevent uneven sharding from reaching here, but a defensive assertion would make the invariant explicit:

    scaled = groups * local_out_channels
    assert scaled % global_out_channels == 0, "groups must divide evenly across shards"
    local_args[8] = scaled // global_out_channels

    Fix this →

  • Overly broad trigger: The condition isinstance(groups, int) and groups > 1 and isinstance(args[1], dtensor.DTensor) fires for any grouped conv (not just depthwise) where the weight happens to be a DTensor. For a non-depthwise grouped conv (e.g., groups=4 with 64 channels) with a replicated weight, local_out_channels == global_out_channels so the inner if is false and no harm is done. But if someone later adds a channel-sharding strategy for general grouped conv, this handler code would silently kick in without validation. Consider tightening the gate to mirror the strategy condition (check groups == global_out_channels), or at minimum add a comment noting the reliance on the local != global guard for non-depthwise cases.

3. Missing backward path

The convolution_backward_handler (line 290) does not have a corresponding groups-scaling adjustment. If the backward pass is triggered with the same channel-sharded placements, it will call the local backward op with the full (global) groups value against a sharded weight, causing the same crash that the forward fix addresses. The existing convolution_backward_single_dim_strategy also doesn't include a depthwise channel-sharding rule — it only has the batch-dim rule. This means backward will likely redistribute to Replicate before computing gradients (avoiding the crash but adding communication). If that's intentional for now, a TODO comment would be helpful.

4. No new tests

The PR description has a test plan with a manual torchrun script, but there's no automated test added to test/distributed/tensor/test_convolution_ops.py. The existing test_depthwise_convolution test uses Shard(3) (spatial dim) with replicated weights, so it doesn't exercise the new channel-sharding path. A test with Shard(1) input + Shard(0) weight for a depthwise Conv1d would be valuable for CI coverage and regression protection. Fix this →

Minor nits

  • _conv_ops.py:174: The comment # Tensor inputs are TensorMetas in single-dim strategies is helpful but slightly redundant with the register_single_dim_strategy docstring (line 706 of single_dim_strategy.py). Not a blocker, the local reminder has value for code readers.

Verdict

The core logic is sound and addresses real production bugs. The main actionable items are:

  1. [Medium] Add a divisibility assertion in the handler to catch invariant violations early.
  2. [Medium] Add an automated test for the new channel-sharding path.
  3. [Low] Consider whether backward also needs the groups scaling (or document that it's intentionally deferred).

@shuhuayu

Copy link
Copy Markdown
Contributor Author

@anshul-si can i get another round of review, thanks

@anshul-si

Copy link
Copy Markdown
Contributor

@claude please review the following issues and validate them. Provide an example the author can use as a test case for each case.

  1. The PR adds a strategy where input/output are Shard(1), meaning split by channel. But _requires_data_exchange() still treats any non-batch sharding with padding > 0 as if it were spatial sharding. It then exchanges/concats boundary data along the length dimension, but the other rank owns different channels, not neighboring length positions.

  2. The new helper rescales groups whenever weight is a DTensor, groups > 1, and local output channels are smaller than global output channels. That condition also matches ordinary grouped convs. For Conv1d(8, 8, groups=4) with weight sharded on dim 0, the helper rewrites groups=4 to groups=2, so local convolution expects 4 input channels but receives 8.

@claude

claude Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Claude finished @anshul-si's task in 12m 6s —— View job


Review: validating the two reported issues

I read _tp_conv.py, _ops/_conv_ops.py, and the new test. Both issues are real. Details and a concrete repro test for each below.


Issue 1 — _requires_data_exchange misfires for channel sharding + padding ✅ VALID

_requires_data_exchange (_tp_conv.py:14-19):

def _requires_data_exchange(padding, dim_map) -> bool:
    if all(x == -1 for x in dim_map[1:]):   # only excludes pure batch-dim sharding
        return False
    return padding[-1] != 0

For the new depthwise channel rule the output is Shard(1), so for a Conv1d output [N, C, L] the dim_map is [-1, 0, -1]. dim_map[1:] == [0, -1] is not all -1, so the first guard passes and the function returns padding[-1] != 0. With any padding > 0 it returns True and dispatch enters the spatial halo-exchange path (_ring_send_recv_construct), which sends/concatenates boundary slices along the length dim between neighbor ranks. But under channel sharding the neighbor rank owns different channels, not adjacent length positions — so it stitches channel-disjoint data as if spatially adjacent, silently corrupting the result (and also reporting non-zero comm).

The PR's test_conv1d_channel_shard only uses padding=0, so this path is never exercised. The check should gate on the spatial (last) dim being sharded, not "anything other than batch."

Repro test case (currently fails — non-zero comm + wrong numerics):

@with_tf32_off
@with_comms
@skip_if_lt_x_gpu(2)
def test_conv1d_channel_shard_padding(self):
    device_mesh = self.build_device_mesh()
    channels = 8
    model = nn.Conv1d(
        channels, channels, kernel_size=3, padding=1, groups=channels
    ).to(self.device_type)
    model_ref = copy.deepcopy(model).to(self.device_type)
    model = distribute_module(model, device_mesh, _depthwise_channel_conv_fn)

    x = torch.randn(2, channels, 16, device=self.device_type)
    x_dt = distribute_tensor(x, device_mesh, [Shard(1)])

    comm_mode = CommDebugMode()
    with comm_mode:
        out_dt = model(x_dt)
    # Channel sharding is group-independent: must NOT trigger spatial halo exchange.
    self.assertEqual(comm_mode.get_total_counts(), 0)
    self.assertTrue(out_dt.placements[0].is_shard(1))

    out_ref = model_ref(x)
    self.assertEqual(out_dt.full_tensor(), out_ref)

Fix this →


Issue 2 — _scaled_local_conv_groups rescales ordinary grouped convs ✅ VALID

The helper (_tp_conv.py:264-282) gates only on groups > 1, weight is a DTensor, and local_out_channels < global_out_channels:

if not (isinstance(groups, int) and groups > 1 and isinstance(weight, dtensor.DTensor)):
    return groups
global_out_channels = weight.shape[0]
local_out_channels = local_weight.shape[0]
if local_out_channels == global_out_channels:
    return groups
...
return scaled_groups // global_out_channels

This never checks the depthwise invariant (groups == in_channels == out_channels) that the strategy in _conv_ops.py:196-201 uses to decide it's safe. The handler runs on the user-provided local shards directly (it does not redistribute inputs), so the local weight stays whatever the user sharded. For Conv1d(8, 8, groups=4) (so weight global shape (8, 2, k)) with the weight distributed Shard(0) on 2 ranks:

  • local_weight.shape == (4, 2, k) → global=8, local=4
  • scaled = 4 * 4 = 16; 16 % 8 == 0 → returns 16 // 8 = 2

So groups is rewritten 4 → 2. The local conv then expects in = local_groups * weight.shape[1] = 2 * 2 = 4 input channels but receives the full 8:

RuntimeError: Given groups=2, weight of size [4, 2, k], expected input ... to have 4 channels, but got 8 channels instead

Note this is a new crash introduced by the PR — before the scaling, groups stayed 4 and the local op did not raise. The fix is to mirror the strategy's gate: only rescale when the conv is genuinely depthwise (e.g. groups == global_out_channels and weight.shape[1] == 1), otherwise return groups unchanged.

Repro test case (currently crashes in the forward):

@with_tf32_off
@with_comms
@skip_if_lt_x_gpu(2)
def test_conv1d_grouped_weight_shard(self):
    # Non-depthwise grouped conv: groups=4 != channels=8. Weight Shard(0) must
    # NOT have its local groups rescaled.
    device_mesh = self.build_device_mesh()
    model = nn.Conv1d(8, 8, kernel_size=3, padding=0, groups=4).to(self.device_type)
    model_ref = copy.deepcopy(model).to(self.device_type)
    # _depthwise_channel_conv_fn distributes params as Shard(0).
    model = distribute_module(model, device_mesh, _depthwise_channel_conv_fn)

    x = torch.randn(2, 8, 16, device=self.device_type)
    x_dt = distribute_tensor(x, device_mesh, [Replicate()])
    out_dt = model(x_dt)
    out_ref = model_ref(x)
    self.assertEqual(out_dt.full_tensor(), out_ref)

Fix this →


Summary

# Issue Verdict Root cause
1 Halo exchange on channel + padding Valid _requires_data_exchange only excludes batch-dim sharding; channel sharding with padding>0 wrongly enters the spatial exchange path
2 Groups rescaled for ordinary grouped conv Valid _scaled_local_conv_groups gate omits the depthwise invariant, so any Shard(0) weight on a groups>1 conv gets rescaled

Both are gaps in the gating conditions rather than the core logic — the depthwise channel-sharding path itself is sound. Recommend (a) gating data exchange on the spatial dim and (b) gating the groups rescale on the depthwise invariant, plus the two regression tests above.
• branch opt

@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

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

Labels

ciflow/dtensor Run DTensor specific tests ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (dtensor) release notes category Stale

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants