Skip to content

[MoE] change torch.bmm back to scatter add - #2775

Merged
acisseJZhong merged 5 commits into
mainfrom
scatter_add
Apr 6, 2026
Merged

acisseJZhong merged 5 commits into
mainfrom
scatter_add

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Change

scatter_add was replaced by torch.bmm in #1974 due to its non determinism. However, bmm backward kernel was reported to be slow in #2225. Although @drisspg has pytorch/pytorch#176552 which greatly optimized the bmm backward time under compile, eager mode backward is still slow.

Therefore we try to switch back to scatter_add with torch.use_deterministic_algorithms(True), see more in https://docs.pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms. We tested out the determinism part using this test script. , updated test

Test with topk=2

llama4 debug model(topk=2), qwen3 debug model(topk=8)

NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
image

Loss compare

NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama4' --baseline-config='llama4_debugmodel' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint

Testing with llama4 debug model, scatter_add with torch deterministic mode on seems still slightly faster than torch.bmm.

cc @garrett361 @chelsea0x3b @rakkit @drisspg

@acisseJZhong
acisseJZhong marked this pull request as draft April 1, 2026 06:20
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Apr 1, 2026
@acisseJZhong
acisseJZhong force-pushed the scatter_add branch 2 times, most recently from 6eac1c1 to 6002fcd Compare April 1, 2026 06:45
@acisseJZhong
acisseJZhong marked this pull request as ready for review April 1, 2026 06:45
Comment thread torchtitan/models/common/moe/moe.py Outdated
Comment on lines +514 to +518
out = out.scatter_add(
dim=0,
index=token_indices_experts_sorted.reshape(-1, 1).expand(-1, dim),
src=routed_output,
)

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.

Can we localize the torch.use_deterministic_algorithms(True) usage to just around this scatter_add, instead of relying on --debug.deterministic for the entire run?

e.g. https://www.internalfb.com/metamate/M4AK5M not sure if context manager works with compile

Comment thread torchtitan/models/common/moe/moe.py Outdated
token_indices_experts_sorted,
num_tokens_per_expert,
) = self.reorderer(top_scores, selected_experts_indices)
token_indices_experts_sorted = token_indices_experts_sorted // self.router.top_k

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.

In general the code looks a bit different from what's before #1974

Please make sure numerics are not changed. In particular, we had to modify ReordererSequenceParallel to make tp2ep correct.

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.

@acisseJZhong acisseJZhong Apr 1, 2026 •

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.

I think previously we also changed ReordererSequenceParallel because we did token_indices_experts_sorted = token_indices_experts_sorted // self.router.top_k inside the reorderer. Now I move this line right after the reorderer. @garrett361 maybe could you also help confirm we don't need other changes here?

For numerics, I ran the loss compare script with dp2tp2ep4etp1(should have tp2ep), loss is matching exactly.

NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama4' --baseline-config='llama4_debugmodel' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint

@garrett361

Copy link
Copy Markdown
Contributor

Do you have performance numbers comparing before/after @acisseJZhong?

@chelsea0x3b

Copy link
Copy Markdown
Contributor

I've been doing some testing and found another way to disappear the slow bmm dispatch with just extracting the bmm into a separate function with torch.compile annotation. Boosts qwen3 30b-a30b from 22.9% mfu to 24.7%. Would ya'll be interested in a PR? its a pretty simple one without any triton kernels.

@tianyu-l

tianyu-l commented Apr 1, 2026

Copy link
Copy Markdown
Contributor

just extracting the bmm into a separate function with torch.compile annotation.

@chelsea0x3b how's that compared with just enable compile in general? For compile, our goal is to enable it for entire transformer block, instead of on individual functions.

@garrett361

Copy link
Copy Markdown
Contributor

@chelsea0x3b

chelsea0x3b commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

the MoE.forward is not compiled currently, only its submodules are:

if isinstance(submod, moe_module.MoE):
    # avoid graph breaking on the GroupedExperts' FSDP hooks
    # by wrapping each submod's forward instead of their __call__
    moe = submod
    for attr_name, submod in moe.named_children():
        if attr_name == "experts":
            # NOTE: We don't compile token dispatch and token combine due to an issue on B200:
            # https://github.com/pytorch/torchtitan/issues/1940
            continue
        submod.compile(backend=compile_config.backend, fullgraph=True)

I think you could probably add

    moe.compile(..., fullgraph=False)

to the end and it would be equivalent? You'd need the fullgraph=False because the experts are skipped

I will test it out as well

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

Do you have performance numbers comparing before/after
@garrett361 yes see the screenshot in description section. Using scatter_add(with torch deterministic wrapping around) has higher throughput and mfu than using bmm, but slower than no deterministic scatter_add.

@garrett361

Copy link
Copy Markdown
Contributor

Oh, missed the image somehow, sorry. And weird, I found in #1974 (comment) that bmm was faster, fwd + bwd. Maybe inequivalent tests.

@acisseJZhong
acisseJZhong force-pushed the scatter_add branch 2 times, most recently from 2d2df06 to 2c904d0 Compare April 1, 2026 22:19
@acisseJZhong

acisseJZhong commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor Author

And weird, I found in #1974 (comment) that bmm was faster, fwd + bwd. Maybe inequivalent tests.

maybe worth re-running your script @garrett361

I also just tested qwen3 debug model, in addition to the llama4 debug model. For qwen3 debug, I think the throughput and MFU of scatter add with deterministic was slightly better than bmm / almost the same.

see #2775 (comment)

@tianyu-l tianyu-l 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.

Is the perf you tested with this local determinism?

Please address comments before landing.

Comment thread torchtitan/models/common/moe/utils.py Outdated
return _round_up(num_tokens, MXFP8_GROUP_ALIGNMENT_SIZE)


def scatter_add_with_local_determinism(

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.

maybe just

Suggested change
def scatter_add_with_local_determinism(
def _deterministic_scatter_add(

inside moe.py

Please don't put in this file because I'm deleting it in #2774

@acisseJZhong

acisseJZhong commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Is the perf you tested with this local determinism?

yup I just doubled check and found out I forgot to delete --deterministic flag in the command. I deleted this flag, and retested llama4 and qwen3 debug model, with topk=2, and topk=8.
image

For qwen3 debug moe both scatter add with local determinism and bmm have similar MFU and wps. However, for llama4 debug moe bmm initially has slightly higher but later almost same MFU and wps.

@tianyu-l

tianyu-l commented Apr 1, 2026

Copy link
Copy Markdown
Contributor

hmm, how about if we compile scatter_add? I think if we compile bmm it will be quite faster.

@acisseJZhong

acisseJZhong commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor Author

@tianyu-l compile scatter add and compile bmm seems to be on par
image
image

@acisseJZhong
acisseJZhong force-pushed the scatter_add branch 2 times, most recently from 49ba16e to 718f2da Compare April 2, 2026 06:25

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.

model/common so far mainly holds shared modules used by various models. For ops, which can be potentially used by other components than model, maybe it's worth its own folder, such as torchtitan/ops/. Wdyt?

@@ -0,0 +1,48 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.

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.

custom op scatter add seems to have slightly lower mfu initially, but later on par. @xmfan please help review if this file looks good to you.

Image

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.

custom op introduces more cpu overhead

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.

let's not call it ops/custom_ops.py which sounds redundant. I'd suggest

  • either put it in init.py for now since there's only one op
  • put it in scatter_add.py

out = (
self.shared_experts(x)
if self.shared_experts is not None
else torch.zeros_like(x)

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.

?

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.

see #1974

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.

I don't see how that PR means we need to have a torch.zeros_like(x) that ends up being unused

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.

pytorchmergebot pushed a commit to pytorch/pytorch that referenced this pull request Apr 6, 2026
# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert.

Deemed a decent enough use case to try out our new APIS;
Some learnings ->
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈

### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />

### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides

SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}

def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")

passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

Pull Request resolved: #179082
Approved by: https://github.com/slayton58, https://github.com/malfet, https://github.com/albanD
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

locally ran the failed test, it's passing

NCCL_NVLS_ENABLE=0 NGPU=8 LOG_RANK=0,1,2,3,4,5,6,7 ./run_train.sh --module graph_trainer.llama3 --config graph_trainer_llama3_debugmodel_flex_attn --compile.mode aot --parallelism.data_parallel_shard_degree 4 --parallelism.tensor_parallel_degree 2 --compile.passes auto_bucketing,regional_inductor
[rank5]:[titan] 2026-04-06 13:33:04,407 - root - INFO - Training completed
[rank0]:[titan] 2026-04-06 13:33:04,408 - root - INFO - step: 10  loss:  4.08641  grad_norm:  1.7635  memory:  0.54GiB(0.56%)  tps: 116,880  tflops: 8.37  mfu: 0.85%
[rank0]:[titan] 2026-04-06 13:33:04,408 - root - INFO - Sleeping 2 seconds for other ranks to complete
[rank7]:[titan] 2026-04-06 13:33:04,406 - root - INFO - step: 10  loss:  4.08641  grad_norm:  1.7635  memory:  0.54GiB(0.56%)  tps: 118,494  tflops: 8.48  mfu: 0.86%

@acisseJZhong
acisseJZhong merged commit 8bc267d into main Apr 6, 2026
29 of 31 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in TorchTitan Development Apr 6, 2026
@tianyu-l
tianyu-l deleted the scatter_add branch April 6, 2026 20:55
weifengpy pushed a commit to pytorch/pytorch that referenced this pull request Apr 7, 2026
# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert.

Deemed a decent enough use case to try out our new APIS;
Some learnings ->
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈

### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />

### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides

SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}

def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")

passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

Pull Request resolved: #179082
Approved by: https://github.com/slayton58, https://github.com/malfet
nklshy-aws pushed a commit to nklshy-aws/pytorch that referenced this pull request Apr 7, 2026
# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert.

Deemed a decent enough use case to try out our new APIS;
Some learnings ->
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈

### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />

### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides

SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}

def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")

passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

Pull Request resolved: pytorch#179082
Approved by: https://github.com/slayton58, https://github.com/malfet
nklshy-aws pushed a commit to nklshy-aws/pytorch that referenced this pull request Apr 7, 2026
# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert.

Deemed a decent enough use case to try out our new APIS;
Some learnings ->
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈

### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />

### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides

SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}

def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")

passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

Pull Request resolved: pytorch#179082
Approved by: https://github.com/slayton58, https://github.com/malfet, https://github.com/albanD
drisspg added a commit to pytorch/pytorch that referenced this pull request Apr 9, 2026
…outer product"


# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert. 

Deemed a decent enough use case to try out our new APIS;
Some learnings -> 
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈


### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />




### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides


SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}


def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")


passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx ipiszy kadeng muchulee8 amjames chauhang aakhundov coconutruben jataylo slayton58

[ghstack-poisoned]
drisspg added a commit to pytorch/pytorch that referenced this pull request Apr 9, 2026
# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert. 

Deemed a decent enough use case to try out our new APIS;
Some learnings -> 
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈


### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />




### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides


SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}


def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")


passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx ipiszy kadeng muchulee8 amjames chauhang aakhundov coconutruben jataylo slayton58

[ghstack-poisoned]
pytorch-bot Bot pushed a commit to pytorch/pytorch that referenced this pull request Apr 10, 2026
# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert.

Deemed a decent enough use case to try out our new APIS;
Some learnings ->
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈

### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />

### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides

SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}

def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")

passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

Pull Request resolved: #179082
Approved by: https://github.com/slayton58, https://github.com/malfet
pytorchmergebot pushed a commit to pytorch/pytorch that referenced this pull request Apr 13, 2026
# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert.

Deemed a decent enough use case to try out our new APIS;
Some learnings ->
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈

### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />

### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides

SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}

def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")

passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

Pull Request resolved: #179082
Approved by: https://github.com/slayton58, https://github.com/malfet, https://github.com/albanD
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
### Change
scatter_add was replaced by torch.bmm in
pytorch#1974 due to its non
determinism. However, bmm backward kernel was reported to be slow in
pytorch#2225. Although @drisspg has
pytorch/pytorch#176552 which greatly optimized
the bmm backward time under compile, eager mode backward is still slow.

Therefore we try to switch back to scatter_add with
`torch.use_deterministic_algorithms(True)`, see more in
https://docs.pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms.
We tested out the determinism part using [this test script.
](https://gist.github.com/acisseJZhong/c56dbc331d3248e488edb24894dc4565),
updated
[test](https://gist.github.com/acisseJZhong/562b635e6ef96d4f2ca68769dbdbad82)

### Test with topk=2
llama4 debug model(topk=2), qwen3 debug model(topk=8)
```
NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
```
<img width="1075" height="288" alt="image"
src="https://github.com/user-attachments/assets/81e7523b-e833-4351-ad57-f5e1276807f3"
/>

### Loss compare

```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama4' --baseline-config='llama4_debugmodel' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```
Testing with llama4 debug model, scatter_add with torch deterministic
mode on seems still slightly faster than torch.bmm.

cc @garrett361 @chelsea0x3b @rakkit @drisspg
jemitche1 pushed a commit to jemitche1/torchtitan that referenced this pull request Apr 14, 2026
### Change
scatter_add was replaced by torch.bmm in
pytorch#1974 due to its non
determinism. However, bmm backward kernel was reported to be slow in
pytorch#2225. Although @drisspg has
pytorch/pytorch#176552 which greatly optimized
the bmm backward time under compile, eager mode backward is still slow.

Therefore we try to switch back to scatter_add with
`torch.use_deterministic_algorithms(True)`, see more in
https://docs.pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms.
We tested out the determinism part using [this test script.
](https://gist.github.com/acisseJZhong/c56dbc331d3248e488edb24894dc4565),
updated
[test](https://gist.github.com/acisseJZhong/562b635e6ef96d4f2ca68769dbdbad82)

### Test with topk=2
llama4 debug model(topk=2), qwen3 debug model(topk=8)
```
NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
```
<img width="1075" height="288" alt="image"
src="https://github.com/user-attachments/assets/81e7523b-e833-4351-ad57-f5e1276807f3"
/>

### Loss compare

```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama4' --baseline-config='llama4_debugmodel' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```
Testing with llama4 debug model, scatter_add with torch deterministic
mode on seems still slightly faster than torch.bmm.

cc @garrett361 @chelsea0x3b @rakkit @drisspg
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
### Change
scatter_add was replaced by torch.bmm in
pytorch#1974 due to its non
determinism. However, bmm backward kernel was reported to be slow in
pytorch#2225. Although @drisspg has
pytorch/pytorch#176552 which greatly optimized
the bmm backward time under compile, eager mode backward is still slow.

Therefore we try to switch back to scatter_add with
`torch.use_deterministic_algorithms(True)`, see more in
https://docs.pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms.
We tested out the determinism part using [this test script.
](https://gist.github.com/acisseJZhong/c56dbc331d3248e488edb24894dc4565),
updated
[test](https://gist.github.com/acisseJZhong/562b635e6ef96d4f2ca68769dbdbad82)

### Test with topk=2
llama4 debug model(topk=2), qwen3 debug model(topk=8)
```
NCCL_NVLS_ENABLE=0 NGPU=8 ./run_train.sh     --module llama4     --config llama4_debugmodel     --parallelism.pipeline_parallel_degree 1     --parallelism.data_parallel_shard_degree 4     --parallelism.tensor_parallel_degree 2     --parallelism.expert_parallel_degree 2     --parallelism.expert_tensor_parallel_degree 2      --metrics.enable_wandb --training.steps 100
```
<img width="1075" height="288" alt="image"
src="https://github.com/user-attachments/assets/81e7523b-e833-4351-ad57-f5e1276807f3"
/>

### Loss compare

```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama4' --baseline-config='llama4_debugmodel' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4 --parallelism.expert_tensor_parallel_degree 1" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 4 --parallelism.expert_tensor_parallel_degree 1" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```
Testing with llama4 debug model, scatter_add with torch deterministic
mode on seems still slightly faster than torch.bmm.

cc @garrett361 @chelsea0x3b @rakkit @drisspg
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert.

Deemed a decent enough use case to try out our new APIS;
Some learnings ->
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈

### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />

### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides

SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}

def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")

passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

Pull Request resolved: pytorch#179082
Approved by: https://github.com/slayton58, https://github.com/malfet
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert.

Deemed a decent enough use case to try out our new APIS;
Some learnings ->
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈

### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />

### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides

SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}

def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")

passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

Pull Request resolved: pytorch#179082
Approved by: https://github.com/slayton58, https://github.com/malfet, https://github.com/albanD
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert.

Deemed a decent enough use case to try out our new APIS;
Some learnings ->
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈

### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />

### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides

SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}

def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")

passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

Pull Request resolved: pytorch#179082
Approved by: https://github.com/slayton58, https://github.com/malfet, https://github.com/albanD
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert.

Deemed a decent enough use case to try out our new APIS;
Some learnings ->
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈

### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />

### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides

SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}

def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")

passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

Pull Request resolved: pytorch#179082
Approved by: https://github.com/slayton58, https://github.com/malfet
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert.

Deemed a decent enough use case to try out our new APIS;
Some learnings ->
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈

### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />

### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides

SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}

def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")

passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

Pull Request resolved: pytorch#179082
Approved by: https://github.com/slayton58, https://github.com/malfet, https://github.com/albanD
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
# Summary
PT does not do a great job with this special case which showed up in how titan implemented the post expert router weighting. W/ scores after expert.

Deemed a decent enough use case to try out our new APIS;
Some learnings ->
copy on write will fail for pretty much every triton overload. Why? because calling `data_ptr` always redirects to mutable_data_ptr. As a follow up we should expose const_data_ptr to python. But even then its pretty annoying to jam this into triton or other dsls.

Autouning is really nice, we should figure out what are reasonable bounds for first run overhead.

Im sure after this lands more learnings will come 🙈

### Perf
```csv
dtype,layout,shape,cublas_ms,cublas_TB/s,triton_ms,triton_TB/s
float16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,contiguous,64x256x1 @ 64x1x256,0.007,1.22,0.003,2.45
float16,contiguous,512x256x1 @ 512x1x4096,0.558,1.93,0.152,7.11
float16,contiguous,65536x8x1 @ 65536x1x2048,4.031,0.60,0.713,3.39
float16,contiguous,12345x7x1 @ 12345x1x1999,0.758,0.52,0.170,2.33
float16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
float16,lhs_permuted,64x256x1 @ 64x1x256,0.007,1.22,0.004,2.36
float16,lhs_permuted,512x256x1 @ 512x1x4096,0.560,1.93,0.152,7.09
float16,lhs_permuted,65536x8x1 @ 65536x1x2048,4.039,0.60,0.716,3.38
float16,lhs_permuted,12345x7x1 @ 12345x1x1999,0.759,0.52,0.184,2.14
float16,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.04
float16,rhs_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.37
float16,rhs_permuted,512x256x1 @ 512x1x4096,0.542,1.99,0.148,7.30
float16,rhs_permuted,65536x8x1 @ 65536x1x2048,15.139,0.16,0.884,2.74
float16,rhs_permuted,12345x7x1 @ 12345x1x1999,2.798,0.14,0.176,2.24
float16,both_permuted,4x128x1 @ 4x1x64,0.004,0.02,0.002,0.03
float16,both_permuted,64x256x1 @ 64x1x256,0.007,1.24,0.004,2.30
float16,both_permuted,512x256x1 @ 512x1x4096,0.540,2.00,0.148,7.29
float16,both_permuted,65536x8x1 @ 65536x1x2048,15.112,0.16,0.892,2.71
float16,both_permuted,12345x7x1 @ 12345x1x1999,2.876,0.14,0.188,2.10
bfloat16,contiguous,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,contiguous,64x256x1 @ 64x1x256,0.008,1.01,0.003,2.44
bfloat16,contiguous,512x256x1 @ 512x1x4096,0.756,1.43,0.152,7.11
bfloat16,contiguous,65536x8x1 @ 65536x1x2048,10.272,0.24,0.713,3.39
bfloat16,contiguous,12345x7x1 @ 12345x1x1999,1.800,0.22,0.170,2.33
bfloat16,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,lhs_permuted,64x256x1 @ 64x1x256,0.008,1.00,0.004,2.37
bfloat16,lhs_permuted,512x256x1 @ 512x1x4096,0.761,1.42,0.152,7.09
bfloat16,lhs_permuted,65536x8x1 @ 65536x1x2048,10.272,0.24,0.716,3.38
bfloat16,lhs_permuted,12345x7x1 @ 12345x1x1999,1.800,0.22,0.184,2.14
bfloat16,rhs_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.04
bfloat16,rhs_permuted,64x256x1 @ 64x1x256,0.008,1.02,0.004,2.37
bfloat16,rhs_permuted,512x256x1 @ 512x1x4096,0.543,1.99,0.148,7.30
bfloat16,rhs_permuted,65536x8x1 @ 65536x1x2048,10.416,0.23,0.884,2.73
bfloat16,rhs_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.176,2.24
bfloat16,both_permuted,4x128x1 @ 4x1x64,0.003,0.02,0.002,0.03
bfloat16,both_permuted,64x256x1 @ 64x1x256,0.008,1.05,0.004,2.29
bfloat16,both_permuted,512x256x1 @ 512x1x4096,0.541,1.99,0.148,7.29
bfloat16,both_permuted,65536x8x1 @ 65536x1x2048,10.415,0.23,0.892,2.71
bfloat16,both_permuted,12345x7x1 @ 12345x1x1999,1.769,0.22,0.188,2.10
float32,contiguous,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,contiguous,64x256x1 @ 64x1x256,0.008,2.03,0.005,3.64
float32,contiguous,512x256x1 @ 512x1x4096,0.551,3.91,0.317,6.80
float32,contiguous,65536x8x1 @ 65536x1x2048,3.718,1.30,0.824,5.86
float32,contiguous,12345x7x1 @ 12345x1x1999,0.696,1.14,0.170,4.65
float32,lhs_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,lhs_permuted,64x256x1 @ 64x1x256,0.008,2.01,0.005,3.49
float32,lhs_permuted,512x256x1 @ 512x1x4096,0.560,3.85,0.317,6.81
float32,lhs_permuted,65536x8x1 @ 65536x1x2048,3.719,1.30,0.873,5.54
float32,lhs_permuted,12345x7x1 @ 12345x1x1999,0.696,1.13,0.185,4.27
float32,rhs_permuted,4x128x1 @ 4x1x64,0.004,0.04,0.002,0.07
float32,rhs_permuted,64x256x1 @ 64x1x256,0.011,1.50,0.005,3.53
float32,rhs_permuted,512x256x1 @ 512x1x4096,0.738,2.92,0.305,7.08
float32,rhs_permuted,65536x8x1 @ 65536x1x2048,7.400,0.65,1.178,4.10
float32,rhs_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.207,3.83
float32,both_permuted,4x128x1 @ 4x1x64,0.003,0.04,0.002,0.07
float32,both_permuted,64x256x1 @ 64x1x256,0.011,1.48,0.005,3.43
float32,both_permuted,512x256x1 @ 512x1x4096,0.751,2.87,0.304,7.09
float32,both_permuted,65536x8x1 @ 65536x1x2048,7.397,0.65,1.188,4.07
float32,both_permuted,12345x7x1 @ 12345x1x1999,1.420,0.56,0.208,3.79
```

<img width="1866" height="186" alt="image" src="https://github.com/user-attachments/assets/7646d6b2-def7-4a0a-bd97-ad4e249ad39f" />

### Correctness testing:
```Py
"""Test bmm outer product against cublas for all layout/dtype/shape permutations."""

import torch
from torch._native.registry import deregister_op_overrides, reenable_op_overrides

SHAPES = [
    (1, 1, 1),
    (1, 64, 128),
    (4, 8, 16),
    (8, 1, 1),
    (32, 8, 256),
    (64, 256, 512),
    (256, 8, 2048),
    (12345, 7, 1999),
]

DTYPES = [torch.float32, torch.float16, torch.bfloat16]

LAYOUTS = {
    "contiguous": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "lhs_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(B, 1, N, device="cuda", dtype=dt),
    ),
    "rhs_permuted": lambda B, M, N, dt: (
        torch.randn(B, M, 1, device="cuda", dtype=dt),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
    "both_permuted": lambda B, M, N, dt: (
        torch.randn(M, B, 1, device="cuda", dtype=dt).permute(1, 0, 2),
        torch.randn(N, B, 1, device="cuda", dtype=dt).permute(1, 2, 0),
    ),
}

def cublas_bmm(a, b):
    deregister_op_overrides(disable_op_symbols="bmm")
    try:
        return torch.bmm(a, b)
    finally:
        reenable_op_overrides(enable_op_symbols="bmm")

passed = 0
failed = 0

for dtype in DTYPES:
    for layout_name, make_inputs in LAYOUTS.items():
        for B, M, N in SHAPES:
            a, b = make_inputs(B, M, N, dtype)
            assert a.shape == (B, M, 1) and b.shape == (B, 1, N)

            triton_result = torch.bmm(a, b)
            cublas_result = cublas_bmm(a, b)

            assert triton_result.stride() == cublas_result.stride()
            if torch.equal(triton_result, cublas_result):
                passed += 1
            else:
                max_diff = (triton_result - cublas_result).abs().max().item()
                print(f"MISMATCH {dtype} {layout_name} ({B},{M},{N}) max_diff={max_diff:.2e}")
                failed += 1

print(f"\n{passed} passed, {failed} failed out of {passed + failed}")

```

See: pytorch/torchtitan#2775

Pull Request resolved: pytorch#179082
Approved by: https://github.com/slayton58, https://github.com/malfet, https://github.com/albanD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

6 participants