Repository navigation
Avoid D2D copy for addmm with distinct C and D - #191706
anijain2305 wants to merge 13 commits into
Conversation
Add a guarded cuBLASLt addmm path that passes distinct C and D pointers directly to cuBLASLt for D = alpha * mat1 @ mat2 + beta * C. Today, when beta != 0 and the addmm output is not the same tensor as C, the CUDA addmm path first copies C into D before launching GEMM. That D2D copy can be acceptable when C is local, but it is expensive for matmul_reduce_scatter-style schedules where C may be a remote HBM allocation accessed through symmetric memory. In that case the pre-copy forces an extra remote read/copy before the GEMM and adds significant exposed latency. Keep the optimization narrow: only exact dense 2D C/D cases with matching dtype/layout and no overlap use this path. All broadcast, aliasing, activation, unsupported dtype/layout, or cuBLASLt failure cases fall back to the existing copy-then-GEMM behavior. This will be used to improve matmul_reduce_scatter performance in later PRs. ghstack-source-id: da8dea9 Pull-Request: #191706
5efe8b6 to
1d22c5b
Compare
681d380 to
1d22c5b
Compare
|
@claude review this PR |
|
Claude finished @anijain2305's task in 15m 37s —— View job Reviewed the new cuBLASLt distinct-C/D addmm path: the GEMM geometry looks correct, but the change ships with no tests, silently bypasses TunableOp, and drops several ROCm gates that the existing Lt guard deliberately applies. Full reviewPR Review: #191706SummaryAdds TestingNo test changes in a 402-line PR that introduces a brand-new numeric kernel path. This is the blocking issue. At minimum:
Without (1) the numerics of the new path are unverified anywhere, and without (2) the fallback edges are unverified. Fix this → InfrastructureTunableOp is silently bypassed. ROCm arch gate is dropped. ROCm 2D-bias exclusion is inverted, and the ROCm 6.4 workaround is not replicated. Code Quality~200 lines duplicated from Concretely, the copy already carries a pre-existing bug forward: on ROCm, when The
Unrelated diff noise. Redundant guard conditions. At Performance / Fragility
RecommendationRequest Changes New numeric kernel path with zero tests is blocking on its own. Beyond that, the TunableOp regression and the dropped ROCm device gate are behavior changes for shapes that work today, and the 200-line duplication of |
| } | ||
|
|
||
| template <typename Dtype, typename C_Dtype> | ||
| bool gemm_with_distinct_c_and_d( |
There was a problem hiding this comment.
check if you can reuse existing template, I'm pretty sure there's a lot of code repetition that we can avoid
| if (self.sizes()[0] != result.sizes()[0] || self.sizes()[1] != result.sizes()[1]) { | ||
| return false; | ||
| } | ||
| if (!self.is_contiguous() || !result.is_contiguous()) { |
There was a problem hiding this comment.
is this a necessary condition? I think cublasLt should be able to handle some leading dimensions that are larger than sizes (to be confirmed with tests)
|
@claude review this PR |
|
Claude finished @anijain2305's task in 40m 57s —— View job The refactor addressed both of @ngimel's comments well ( Full reviewPR Review: #191706 (v2)What changed since the last roundBoth reviewer comments are addressed:
I verified the GEMM geometry independently. With TestingThe tests never confirm the new path runs. Every assertion in all three new tests would pass identically if
for out in (torch.empty((m, n), ...),
torch.empty((m, 2 * n), ...)[:, :n]):
wide_out = out._base if out._base is not None else out
filler = wide_out.clone() if out._base is not None else None
wide_out = make_tensor((m, 2 * n), dtype=dtype, device=device, low=-1, high=1)
filler = wide_out.clone()
out = wide_out[:, :n]The Minor: CorrectnessThe early TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
args.result->is_same(result) && args.result_ld == result.stride(0));
uint32_t d_alignment = detail::getAlignment(reinterpret_cast<uintptr_t>(
c_ptr ? static_cast<const void*>(result_ptr) : static_cast<const void*>(bias)));
PerformanceOne extra std::optional<CuBlasLtMatrixLayout> Ddesc;
if (c_ptr) Ddesc.emplace(cType, m, n, result_ld);
const auto Ddesc_raw = c_ptr ? Ddesc->descriptor() : Cdesc.descriptor();Separately, passing two distinct-but-identical layout objects as C and D (instead of the same object twice, as before) is a nonzero behavioral surface change on the hottest GEMM path — the heuristic could in principle pick differently. The PR's benchmark only covers the new path; a quick sanity run on a plain Code qualityDead clause in return t.dim() == 2 && t.stride(1) == 1 && t.stride(0) >= t.sizes()[1] &&
(t.sizes()[0] <= 1 || t.stride(0) >= 1);The trailing clause can never fail given the preceding one.
Naming.
Minor precision note. With RecommendationApprove with comments on the C++ (the geometry, the guard, and the TunableOp/ROCm exclusions all check out), request changes on the tests. The three test issues to resolve before landing: prove the fast path is taken, stop comparing uninitialized memory in the padded test, and add the aliasing assertion behind the early return. The |
|
@claude review this PR |
|
Claude finished @anijain2305's task in 21m 31s —— View job The refactor is in good shape and the geometry checks out, but the new Full reviewPR Review: #191706 (v3)SummaryExtends I re-verified the GEMM geometry independently. With Testing
The kernel count is more brittle than it needs to be. The "input aliasing out" fallback case never reaches the aliasing guard. base = make_tensor((2 * m, n), dtype=dtype, device=device, low=-1, high=1)
check(base[:m], out=base[m:])That is the only path that can produce silently wrong numerics if the guard is ever loosened, and it is currently untested. Fix this → Two guard clauses have no fallback coverage. Infrastructure
This is a defensible fix — base was feeding the wrong pointer into Duplicated eligibility logic. Code Quality
RecommendationRequest Changes The ROCm skip is a CI-red and must land before merge. The aliasing test not reaching the aliasing guard means the one case that can produce silently wrong numerics is uncovered, and the kernel-count filter should move to |
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
|
@pytorchbot merge |
Merge failedReason: New commits were pushed while merging. Please rerun the merge command. Details for Dev Infra teamRaised by workflow job |
|
The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
Merge failedReason: 2 jobs have failed, first few of them are: B200 Smoke Tests / linux-jammy-cuda13.0-py3.12-gcc11-sm100 / test (smoke_b200, 1, 1, linux.dgx.b200), B200 Smoke Tests / linux-jammy-cuda13.2-py3.12-gcc11-sm100 / test (smoke_b200, 1, 1, linux.dgx.b200) Details for Dev Infra teamRaised by workflow job |
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 2 checks: B200 Smoke Tests / linux-jammy-cuda13.0-py3.12-gcc11-sm100 / test (smoke_b200, 1, 1, linux.dgx.b200), B200 Smoke Tests / linux-jammy-cuda13.2-py3.12-gcc11-sm100 / test (smoke_b200, 1, 1, linux.dgx.b200) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
mergedog handoffNote This PR is being shepherded by mergedog, an automation tool run by a maintainer. It watches CI and may push fixes; the PR author does not need to act unless a maintainer asks. All CI is green (or skipped). Ready for human review and Current PR head: CI notes at handoffmergedog is treating these still-failing checks as unrelated/spurious. Please verify before merging:
Warning: mergedog's suppressed check list differs from the latest Dr. CI summary. Suppressed by mergedog but not marked unrelated by Dr. CI:
Latest Dr. CI summary## :link: Helpful Links
### :test_tube: See artifacts and rendered test results at [hud.pytorch.org/pr/191706](https://hud.pytorch.org/pr/191706)
* :page_facing_up: Preview [Python docs built from this PR](https://docs-preview.pytorch.org/pytorch/pytorch/191706/index.html)
* :page_facing_up: Preview [C++ docs built from this PR](https://docs-preview.pytorch.org/pytorch/pytorch/191706/cppdocs/index.html)
* :question: Need help or want to give feedback on the CI? Visit the [bot commands wiki](https://github.com/pytorch/pytorch/wiki/Bot-commands)
Note: Links to docs will display an error until the docs builds have been completed.
## :x: 2 New Failures, 1 Pending, 6 Unrelated Failures
As of commit e415b6e00ad0cc0a5b5790f9e662b2fe86c469b5 with merge base 2942118cd9809a2a925c970df1bf6b91497a6a2f (<sub><sub><img alt="image" width=70 src="https://img.shields.io/date/1786288961?label=&color=FFFFFF&style=flat-square"></sub></sub>):
<details open><summary><b>NEW FAILURES</b> - The following jobs have failed:</summary><p>
* [B200 Smoke Tests / linux-jammy-cuda13.0-py3.12-gcc11-sm100 / test (smoke_b200, 1, 1, linux.dgx.b200)](https://hud.pytorch.org/pr/pytorch/pytorch/191706#93288753460) ([gh](https://github.com/pytorch/pytorch/actions/runs/31329815334/job/93288753460))
`test/inductor/test_flex_gemm.py::TestFlexGemmEpilogueHOP::test_addmm_compiled_matches_reference`
<details><summary>AI verdict: <a href="https://hud.pytorch.org/pr/pytorch/pytorch/191706#93288753460"><img alt="AI verdict: not related" src="https://hud.pytorch.org/api/drci/advisorBadge?owner=pytorch&repo=pytorch&sha=e415b6e00ad0cc0a5b5790f9e662b2fe86c469b5&job=B200+Smoke+Tests+%2F+linux-jammy-cuda13.0-py3.12-gcc11-sm100+%2F+test+%28smoke_b200%2C+1%2C+1%2C+linux.dgx.b200%29"></a></summary><blockquote>
The suspect commit only modifies comments in Blas.cpp and test tolerances in test_linalg.py. The failing test is in test_flex_gemm.py which is untouched. The B200 smoke test job was already failing on trunk with different flex_gemm tests.
<a href="https://hud.pytorch.org/pr/pytorch/pytorch/191706#93288753460">Full reasoning on HUD →</a>
</blockquote></details>
* [B200 Smoke Tests / linux-jammy-cuda13.2-py3.12-gcc11-sm100 / test (smoke_b200, 1, 1, linux.dgx.b200)](https://hud.pytorch.org/pr/pytorch/pytorch/191706#93288889769) ([gh](https://github.com/pytorch/pytorch/actions/runs/31329815334/job/93288889769))
`test/inductor/test_flex_gemm.py::TestFlexGemmEpilogueHOP::test_addmm_compiled_matches_reference`
<details><summary>AI verdict: <a href="https://hud.pytorch.org/pr/pytorch/pytorch/191706#93288889769"><img alt="AI verdict: related" src="https://hud.pytorch.org/api/drci/advisorBadge?owner=pytorch&repo=pytorch&sha=e415b6e00ad0cc0a5b5790f9e662b2fe86c469b5&job=B200+Smoke+Tests+%2F+linux-jammy-cuda13.2-py3.12-gcc11-sm100+%2F+test+%28smoke_b200%2C+1%2C+1%2C+linux.dgx.b200%29"></a></summary><blockquote>
The suspect commit changes the numerical behavior of eager torch.addmm for bf16 by enabling a distinct C/D pointer path in cuBLASLt. The failing test compares compiled flex_gemm output against eager addmm as a reference, so the shifted eager results cause a mismatch.
<a href="https://hud.pytorch.org/pr/pytorch/pytorch/191706#93288889769">Full reasoning on HUD →</a>
</blockquote></details>
</p></details>
<details ><summary><b>CRCR (non-blocking)</b> - The following CRCR downstream CI jobs failed but are non-blocking:</summary><p>
* [crcr/pytorch/crcr-test/CRCR L3 CI - Checking if PR check run is successfully created/test-L3-xcancel-checkrun-creation](https://hud.pytorch.org/pr/pytorch/pytorch/191706#92309020095) ([gh](https://github.com/pytorch/crcr-test/actions/runs/31006923652))
* [crcr/pytorch/crcr-test/CRCR L3 CI - Checking if PR check run is successfully created/test-L3-xcancel-checkrun-creation](https://hud.pytorch.org/pr/pytorch/pytorch/191706#92514173833) ([gh](https://github.com/pytorch/crcr-test/actions/runs/31069470478))
* [crcr/pytorch/crcr-test/CRCR L3 CI - Checking if PR check run is successfully created/test-L3-xfail-checkrun-creation](https://hud.pytorch.org/pr/pytorch/pytorch/191706#92309020171) ([gh](https://github.com/pytorch/crcr-test/actions/runs/31006923652))
* [crcr/pytorch/crcr-test/CRCR L3 CI - Checking if PR check run is successfully created/test-L3-xfail-checkrun-creation](https://hud.pytorch.org/pr/pytorch/pytorch/191706#92514173916) ([gh](https://github.com/pytorch/crcr-test/actions/runs/31069470478))
* [crcr/pytorch/crcr-test/CRCR L3 CI - Checking if PR check run is successfully created/test-L3-xtimeout-checkrun-creation](https://hud.pytorch.org/pr/pytorch/pytorch/191706#92309020199) ([gh](https://github.com/pytorch/crcr-test/actions/runs/31006923652))
* [crcr/pytorch/crcr-test/CRCR L3 CI - Checking if PR check run is successfully created/test-L3-xtimeout-checkrun-creation](https://hud.pytorch.org/pr/pytorch/pytorch/191706#92514173905) ([gh](https://github.com/pytorch/crcr-test/actions/runs/31069470478))
</p></details>
This comment was automatically generated by Dr. CI and updates every 15 minutes.No LLM was invoked during this run. |
A regression introduced in pytorch#191706 was caught internally on GB200 via `TestLinalgCUDA.test_addmm_out_distinct_c_and_d`, but that test was not included in the `ciflow/b200` smoke job. Add a targeted `test_linalg` run filtered to `-k "mm or addmv"`, which covers `test_mm*`, `test_addmm*`, and `test_addmv*` in test_linalg (~1000 small-tensor parametrized cases) without meaningfully extending the ~1.5-hour smoke job runtime. `test_matmul_cuda` and `test_scaled_matmul_cuda` are already included in the smoke suite and cover mm and scaled mm independently. Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
A regression introduced in #191706 was caught internally on GB200 via `TestLinalgCUDA.test_addmm_out_distinct_c_and_d`, but that test was not included in the `ciflow/b200` smoke job. This adds a targeted `test_linalg -k "mm or addmv"` run to `test_python_smoke_b200()`, covering `test_mm*`, `test_addmm*`, and `test_addmv*` in test_linalg (~1000 small-tensor parametrized cases) without meaningfully extending the ~1.5-hour smoke job runtime. Note that `test_matmul_cuda` and `test_scaled_matmul_cuda` are already included in the smoke suite and cover mm and scaled mm independently. [Human note: to verify the increase of test time] Human update: This PR's smoke test (with keep-going) took 1hr 35 minutes. https://github.com/pytorch/pytorch/actions/runs/31434627639/job/93657733055?pr=192836#logs Trunk job https://github.com/pytorch/pytorch/actions/runs/31437490081/job/93620093271 took 1hr 30 minutes. **So 5 minute in crease in test time.** > [!NOTE] > This PR was authored with the assistance of an AI assistant. Pull Request resolved: #192836 Approved by: https://github.com/ngimel, https://github.com/Skylion007 Co-authored-by: Claude Sonnet 4.6 (1M context) <[email protected]>
Let CUDA addmm hand cuBLASLt distinct C and D pointers for
D = alpha * mat1 @ mat2 + beta * C, instead of copying C into D first.
Today, when beta != 0 and the addmm output is not the same tensor as C, the
CUDA path materializes C into the output via
`copy_(result, *expand_size(self, result.sizes(), "addmm"))` in
`aten/src/ATen/native/cuda/Blas.cpp` and then runs the GEMM in place. That copy
is tolerable when C is local, but it is expensive for matmul_reduce_scatter
style schedules where C is a peer allocation reached through symmetric memory:
the pre-copy turns into an exposed remote read before the GEMM. See the numbers below.
Rather than add a second cuBLASLt entry point, this extends `gemm_and_bias`
with optional `c_ptr` / `c_ld` / `beta` arguments that default to the existing
behavior, so the descriptor, reduction-scheme, SM-carveout, alignment and
heuristic handling stay in one place. When `c_ptr` is null the C and D layouts
are identical and the call is unchanged.
The guard is intentionally narrow. It requires a 2D, row-major C and D of
matching shape and dtype, no activation, beta != 0, and no shared storage
between C and D; everything else keeps the existing copy-then-GEMM path. Two
notes on what it deliberately excludes:
- It is off on ROCm. `isInputCompliesAddmmCudaLt()` already keeps 2D `self`
away from hipBLASLt, so enabling exactly that shape here would open an
untested path.
- It is off when TunableOp is enabled, since these shapes are tuned today
through the non-Lt gemm and silently bypassing that would be a regression.
Row-major operands with padding between rows are accepted, since the leading
dimension expresses them and cuBLASLt handles them; only genuinely strided or
column-major operands fall back. Note that `at::get_overlap_status()` cannot be
used for the aliasing check here because it reports TooHard for those padded
layouts, so the check is on shared storage instead.
While rewriting the alignment preferences, this also fixes a pre-existing bug
next door: `d_alignment` was derived from the bias pointer, and
`detail::getAlignment(nullptr)` returns 256, so cuBLASLt was told D is
256-byte aligned on every bias-less Lt call even when the output is a
4-byte-aligned view. D is always `result_ptr`, so it is now derived from that.
Performance
-----------
One ring reduce-scatter step, `[M_shard, K] @ [K, N] + C` with C in a peer's
symmetric memory, 2 ranks on GB300, bf16, median of 60 iterations after 25
warmup, slowest rank. "before" and "after" are separate builds of this commit's
parent and this commit, so nothing is emulated.
| M_shard | N | K_per_rank | before | after | speedup |
| --- | --- | --- | --- | --- | --- |
| 8192 | 7168 | 3584 | 384.9 us (1094 TF) | 278.9 us (1509 TF) | 1.38x |
| 8192 | 4096 | 2048 | 181.1 us (759 TF) | 141.5 us (971 TF) | 1.28x |
| 4096 | 7168 | 1792 | 153.0 us (688 TF) | 131.0 us (803 TF) | 1.17x |
| 8192 | 7168 | 9216 | 737.0 us (1468 TF) | 655.4 us (1651 TF) | 1.12x |
| 2048 | 11264 | 11264 | 357.1 us (1456 TF) | 326.4 us (1592 TF) | 1.09x |
| 2048 | 8192 | 8192 | 222.7 us (1234 TF) | 207.1 us (1327 TF) | 1.08x |
| 2048 | 6144 | 8192 | 176.4 us (1169 TF) | 167.3 us (1232 TF) | 1.05x |
| 8192 | 512 | 32768 | 206.8 us (1329 TF) | 220.9 us (1244 TF) | 0.94x |
The last row is a real regression, not noise: for a very narrow N with a long K,
cuBLASLt appears to pick a worse algorithm once C and D are distinct pointers
than it does for the copy-then-accumulate form. The saved copy is only
`M_shard * N` elements there, so there is little to win back. Everything else
gains, most where the copy is largest relative to the GEMM.
The shared bias path is unaffected. `nn.Linear` before/after over float32 and
bfloat16 at 32x1024x1024, 128x4096x4096 and 4096x8192x8192: GPU time within
0.5% on the two large shapes and within ~2% on the launch-bound 32-row shapes,
with host launch cost unchanged (35-47 us both).
This landed once and was reverted by autorevert (test_addmm_mv, alpha=0.0).
The trigger is alpha == 0 together with beta == 1, where the operation reduces
to the identity D = C. cuBLASLt then skips the write entirely, which is a valid
shortcut while C has already been copied into D and the two pointers alias, but
silently drops the term once they are distinct. Measured with a sentinel-filled
output at m=1, fp32:
alpha=0 beta=1 D not written <-- sentinel survives
alpha=0 beta=0.5 0.5 * C correct
alpha=0 beta=2 2 * C correct
alpha=0 beta=-1 -C correct
alpha=1e-30 beta * C + eps correct
so beta == 1 is the only affected case, and with C aliased to the output it is
correct there too. Which shapes and dtypes hit it depends on the algorithm the
heuristic returns: fp32/fp64 leave D untouched at m=1 where fp16 does not, and
the wider shapes are unaffected.
alpha == 0 as a whole now falls back. That is broader than the failure requires,
deliberately: it does not depend on which algorithm is selected, and it costs
nothing because with alpha == 0 there is no matmul to overlap with the avoided
copy.
A sweep of the rest of the degenerate surface found nothing else in this family:
every failure was "D never written" rather than a wrong value, k <= 1 and n <= 1
are already excluded by the mat2 shape guard, and a non-finite C survives the
beta * C term. The tests now also fill `out` with a sentinel instead of using
`empty`, so a path that never writes D cannot pass on whatever the allocator
happened to return.
Test plan:
- `python test/test_linalg.py -k distinct_c_and_d TestLinalgCUDA` (292 cases:
dtypes float64/float32/float16/bfloat16 x alpha in {1, 0.5, 0} x beta x
shapes {64x96x32, 1x8x32} x mat1/mat2 transposes;
the fallback boundaries of 1D and broadcast C, beta=0, strided and
column-major C, and C aliasing the output; and a test that counts launched
kernels to pin that the fast path is actually selected -- it fails against
the previous revision, which rejected a padded C)
- `python test/test_linalg.py -k padded_leading_dim TestLinalgCUDA`
- `python test/test_linalg.py -k test_addmm_mv TestLinalgCUDA` (108 cases, the
test that triggered the revert)
- The path-selection test is skipped on ROCm: `@onlyCUDA` selects ROCm too, and
the guard is compiled out there, so it legitimately counts two kernels. Its
rejected-layout check also asserts strictly-more-kernels rather than exactly
two, so an unrelated extra kernel on some backend cannot fail it.
- `python test/test_linalg.py -k mm TestLinalgCUDA`, compared against a build of
this commit's parent: no failures on either side
- `python test/test_nn.py -k linear` (1106 tests, covers the shared bias path)
- `torchrun --nproc_per_node=2` remote-C ring-step benchmark and `nn.Linear`
timings, each run against a build of this commit and of its parent
This PR was authored with the help of an AI assistant.
Co-authored-by: Codex <[email protected]>
Co-authored-by: Claude <[email protected]>
Pull Request resolved: pytorch#191706
Approved by: https://github.com/ngimel
This reverts commit 7c70074. Reverted pytorch#191706 on behalf of https://github.com/atalman due to reverting, see above failures ([comment](pytorch#191706 (comment)))
Let CUDA addmm hand cuBLASLt distinct C and D pointers for
D = alpha * mat1 @ mat2 + beta * C, instead of copying C into D first.
Today, when beta != 0 and the addmm output is not the same tensor as C, the
CUDA path materializes C into the output via
`copy_(result, *expand_size(self, result.sizes(), "addmm"))` in
`aten/src/ATen/native/cuda/Blas.cpp` and then runs the GEMM in place. That copy
is tolerable when C is local, but it is expensive for matmul_reduce_scatter
style schedules where C is a peer allocation reached through symmetric memory:
the pre-copy turns into an exposed remote read before the GEMM. See the numbers below.
Rather than add a second cuBLASLt entry point, this extends `gemm_and_bias`
with optional `c_ptr` / `c_ld` / `beta` arguments that default to the existing
behavior, so the descriptor, reduction-scheme, SM-carveout, alignment and
heuristic handling stay in one place. When `c_ptr` is null the C and D layouts
are identical and the call is unchanged.
The guard is intentionally narrow. It requires a 2D, row-major C and D of
matching shape and dtype, no activation, beta != 0, and no shared storage
between C and D; everything else keeps the existing copy-then-GEMM path. Two
notes on what it deliberately excludes:
- It is off on ROCm. `isInputCompliesAddmmCudaLt()` already keeps 2D `self`
away from hipBLASLt, so enabling exactly that shape here would open an
untested path.
- It is off when TunableOp is enabled, since these shapes are tuned today
through the non-Lt gemm and silently bypassing that would be a regression.
Row-major operands with padding between rows are accepted, since the leading
dimension expresses them and cuBLASLt handles them; only genuinely strided or
column-major operands fall back. Note that `at::get_overlap_status()` cannot be
used for the aliasing check here because it reports TooHard for those padded
layouts, so the check is on shared storage instead.
While rewriting the alignment preferences, this also fixes a pre-existing bug
next door: `d_alignment` was derived from the bias pointer, and
`detail::getAlignment(nullptr)` returns 256, so cuBLASLt was told D is
256-byte aligned on every bias-less Lt call even when the output is a
4-byte-aligned view. D is always `result_ptr`, so it is now derived from that.
Performance
-----------
One ring reduce-scatter step, `[M_shard, K] @ [K, N] + C` with C in a peer's
symmetric memory, 2 ranks on GB300, bf16, median of 60 iterations after 25
warmup, slowest rank. "before" and "after" are separate builds of this commit's
parent and this commit, so nothing is emulated.
| M_shard | N | K_per_rank | before | after | speedup |
| --- | --- | --- | --- | --- | --- |
| 8192 | 7168 | 3584 | 384.9 us (1094 TF) | 278.9 us (1509 TF) | 1.38x |
| 8192 | 4096 | 2048 | 181.1 us (759 TF) | 141.5 us (971 TF) | 1.28x |
| 4096 | 7168 | 1792 | 153.0 us (688 TF) | 131.0 us (803 TF) | 1.17x |
| 8192 | 7168 | 9216 | 737.0 us (1468 TF) | 655.4 us (1651 TF) | 1.12x |
| 2048 | 11264 | 11264 | 357.1 us (1456 TF) | 326.4 us (1592 TF) | 1.09x |
| 2048 | 8192 | 8192 | 222.7 us (1234 TF) | 207.1 us (1327 TF) | 1.08x |
| 2048 | 6144 | 8192 | 176.4 us (1169 TF) | 167.3 us (1232 TF) | 1.05x |
| 8192 | 512 | 32768 | 206.8 us (1329 TF) | 220.9 us (1244 TF) | 0.94x |
The last row is a real regression, not noise: for a very narrow N with a long K,
cuBLASLt appears to pick a worse algorithm once C and D are distinct pointers
than it does for the copy-then-accumulate form. The saved copy is only
`M_shard * N` elements there, so there is little to win back. Everything else
gains, most where the copy is largest relative to the GEMM.
The shared bias path is unaffected. `nn.Linear` before/after over float32 and
bfloat16 at 32x1024x1024, 128x4096x4096 and 4096x8192x8192: GPU time within
0.5% on the two large shapes and within ~2% on the launch-bound 32-row shapes,
with host launch cost unchanged (35-47 us both).
This landed once and was reverted by autorevert (test_addmm_mv, alpha=0.0).
The trigger is alpha == 0 together with beta == 1, where the operation reduces
to the identity D = C. cuBLASLt then skips the write entirely, which is a valid
shortcut while C has already been copied into D and the two pointers alias, but
silently drops the term once they are distinct. Measured with a sentinel-filled
output at m=1, fp32:
alpha=0 beta=1 D not written <-- sentinel survives
alpha=0 beta=0.5 0.5 * C correct
alpha=0 beta=2 2 * C correct
alpha=0 beta=-1 -C correct
alpha=1e-30 beta * C + eps correct
so beta == 1 is the only affected case, and with C aliased to the output it is
correct there too. Which shapes and dtypes hit it depends on the algorithm the
heuristic returns: fp32/fp64 leave D untouched at m=1 where fp16 does not, and
the wider shapes are unaffected.
alpha == 0 as a whole now falls back. That is broader than the failure requires,
deliberately: it does not depend on which algorithm is selected, and it costs
nothing because with alpha == 0 there is no matmul to overlap with the avoided
copy.
A sweep of the rest of the degenerate surface found nothing else in this family:
every failure was "D never written" rather than a wrong value, k <= 1 and n <= 1
are already excluded by the mat2 shape guard, and a non-finite C survives the
beta * C term. The tests now also fill `out` with a sentinel instead of using
`empty`, so a path that never writes D cannot pass on whatever the allocator
happened to return.
Test plan:
- `python test/test_linalg.py -k distinct_c_and_d TestLinalgCUDA` (292 cases:
dtypes float64/float32/float16/bfloat16 x alpha in {1, 0.5, 0} x beta x
shapes {64x96x32, 1x8x32} x mat1/mat2 transposes;
the fallback boundaries of 1D and broadcast C, beta=0, strided and
column-major C, and C aliasing the output; and a test that counts launched
kernels to pin that the fast path is actually selected -- it fails against
the previous revision, which rejected a padded C)
- `python test/test_linalg.py -k padded_leading_dim TestLinalgCUDA`
- `python test/test_linalg.py -k test_addmm_mv TestLinalgCUDA` (108 cases, the
test that triggered the revert)
- The path-selection test is skipped on ROCm: `@onlyCUDA` selects ROCm too, and
the guard is compiled out there, so it legitimately counts two kernels. Its
rejected-layout check also asserts strictly-more-kernels rather than exactly
two, so an unrelated extra kernel on some backend cannot fail it.
- `python test/test_linalg.py -k mm TestLinalgCUDA`, compared against a build of
this commit's parent: no failures on either side
- `python test/test_nn.py -k linear` (1106 tests, covers the shared bias path)
- `torchrun --nproc_per_node=2` remote-C ring-step benchmark and `nn.Linear`
timings, each run against a build of this commit and of its parent
This PR was authored with the help of an AI assistant.
Co-authored-by: Codex <[email protected]>
Co-authored-by: Claude <[email protected]>
Pull Request resolved: pytorch#191706
Approved by: https://github.com/ngimel
A regression introduced in pytorch#191706 was caught internally on GB200 via `TestLinalgCUDA.test_addmm_out_distinct_c_and_d`, but that test was not included in the `ciflow/b200` smoke job. This adds a targeted `test_linalg -k "mm or addmv"` run to `test_python_smoke_b200()`, covering `test_mm*`, `test_addmm*`, and `test_addmv*` in test_linalg (~1000 small-tensor parametrized cases) without meaningfully extending the ~1.5-hour smoke job runtime. Note that `test_matmul_cuda` and `test_scaled_matmul_cuda` are already included in the smoke suite and cover mm and scaled mm independently. [Human note: to verify the increase of test time] Human update: This PR's smoke test (with keep-going) took 1hr 35 minutes. https://github.com/pytorch/pytorch/actions/runs/31434627639/job/93657733055?pr=192836#logs Trunk job https://github.com/pytorch/pytorch/actions/runs/31437490081/job/93620093271 took 1hr 30 minutes. **So 5 minute in crease in test time.** > [!NOTE] > This PR was authored with the assistance of an AI assistant. Pull Request resolved: pytorch#192836 Approved by: https://github.com/ngimel, https://github.com/Skylion007 Co-authored-by: Claude Sonnet 4.6 (1M context) <[email protected]>
A regression introduced in pytorch#191706 was caught internally on GB200 via `TestLinalgCUDA.test_addmm_out_distinct_c_and_d`, but that test was not included in the `ciflow/b200` smoke job. This adds a targeted `test_linalg -k "mm or addmv"` run to `test_python_smoke_b200()`, covering `test_mm*`, `test_addmm*`, and `test_addmv*` in test_linalg (~1000 small-tensor parametrized cases) without meaningfully extending the ~1.5-hour smoke job runtime. Note that `test_matmul_cuda` and `test_scaled_matmul_cuda` are already included in the smoke suite and cover mm and scaled mm independently. [Human note: to verify the increase of test time] Human update: This PR's smoke test (with keep-going) took 1hr 35 minutes. https://github.com/pytorch/pytorch/actions/runs/31434627639/job/93657733055?pr=192836#logs Trunk job https://github.com/pytorch/pytorch/actions/runs/31437490081/job/93620093271 took 1hr 30 minutes. **So 5 minute in crease in test time.** > [!NOTE] > This PR was authored with the assistance of an AI assistant. Pull Request resolved: pytorch#192836 Approved by: https://github.com/ngimel, https://github.com/Skylion007 Co-authored-by: Claude Sonnet 4.6 (1M context) <[email protected]>
First rtx40 release. Limitations checked against the packaged wheel on one RTX 4090 under WSL2 (driver 621.14): no CPU LAPACK (inv/cholesky/svd on CPU raise), CPU float32 matmul via Eigen, no MPI, no cuDNN, single GPU. Tests section names the 15 rtx40-only skips (addmm split-K, upstream pytorch#191706; 14 grouped_gemm bf16 cases, upstream pytorch#196075) and the pytest<9.2 pin. Assisted-by: Claude
Stack from ghstack (oldest at bottom):
Let CUDA addmm hand cuBLASLt distinct C and D pointers for
D = alpha * mat1 @ mat2 + beta * C, instead of copying C into D first.
Today, when beta != 0 and the addmm output is not the same tensor as C, the
CUDA path materializes C into the output via
copy_(result, *expand_size(self, result.sizes(), "addmm"))inaten/src/ATen/native/cuda/Blas.cppand then runs the GEMM in place. That copyis tolerable when C is local, but it is expensive for matmul_reduce_scatter
style schedules where C is a peer allocation reached through symmetric memory:
the pre-copy turns into an exposed remote read before the GEMM. See the numbers below.
Rather than add a second cuBLASLt entry point, this extends
gemm_and_biaswith optional
c_ptr/c_ld/betaarguments that default to the existingbehavior, so the descriptor, reduction-scheme, SM-carveout, alignment and
heuristic handling stay in one place. When
c_ptris null the C and D layoutsare identical and the call is unchanged.
The guard is intentionally narrow. It requires a 2D, row-major C and D of
matching shape and dtype, no activation, beta != 0, and no shared storage
between C and D; everything else keeps the existing copy-then-GEMM path. Two
notes on what it deliberately excludes:
isInputCompliesAddmmCudaLt()already keeps 2Dselfaway from hipBLASLt, so enabling exactly that shape here would open an
untested path.
through the non-Lt gemm and silently bypassing that would be a regression.
Row-major operands with padding between rows are accepted, since the leading
dimension expresses them and cuBLASLt handles them; only genuinely strided or
column-major operands fall back. Note that
at::get_overlap_status()cannot beused for the aliasing check here because it reports TooHard for those padded
layouts, so the check is on shared storage instead.
While rewriting the alignment preferences, this also fixes a pre-existing bug
next door:
d_alignmentwas derived from the bias pointer, anddetail::getAlignment(nullptr)returns 256, so cuBLASLt was told D is256-byte aligned on every bias-less Lt call even when the output is a
4-byte-aligned view. D is always
result_ptr, so it is now derived from that.Performance
One ring reduce-scatter step,
[M_shard, K] @ [K, N] + Cwith C in a peer'ssymmetric memory, 2 ranks on GB300, bf16, median of 60 iterations after 25
warmup, slowest rank. "before" and "after" are separate builds of this commit's
parent and this commit, so nothing is emulated.
The last row is a real regression, not noise: for a very narrow N with a long K,
cuBLASLt appears to pick a worse algorithm once C and D are distinct pointers
than it does for the copy-then-accumulate form. The saved copy is only
M_shard * Nelements there, so there is little to win back. Everything elsegains, most where the copy is largest relative to the GEMM.
The shared bias path is unaffected.
nn.Linearbefore/after over float32 andbfloat16 at 32x1024x1024, 128x4096x4096 and 4096x8192x8192: GPU time within
0.5% on the two large shapes and within ~2% on the launch-bound 32-row shapes,
with host launch cost unchanged (35-47 us both).
This landed once and was reverted by autorevert (test_addmm_mv, alpha=0.0).
The trigger is alpha == 0 together with beta == 1, where the operation reduces
to the identity D = C. cuBLASLt then skips the write entirely, which is a valid
shortcut while C has already been copied into D and the two pointers alias, but
silently drops the term once they are distinct. Measured with a sentinel-filled
output at m=1, fp32:
so beta == 1 is the only affected case, and with C aliased to the output it is
correct there too. Which shapes and dtypes hit it depends on the algorithm the
heuristic returns: fp32/fp64 leave D untouched at m=1 where fp16 does not, and
the wider shapes are unaffected.
alpha == 0 as a whole now falls back. That is broader than the failure requires,
deliberately: it does not depend on which algorithm is selected, and it costs
nothing because with alpha == 0 there is no matmul to overlap with the avoided
copy.
A sweep of the rest of the degenerate surface found nothing else in this family:
every failure was "D never written" rather than a wrong value, k <= 1 and n <= 1
are already excluded by the mat2 shape guard, and a non-finite C survives the
beta * C term. The tests now also fill
outwith a sentinel instead of usingempty, so a path that never writes D cannot pass on whatever the allocatorhappened to return.
Test plan:
python test/test_linalg.py -k distinct_c_and_d TestLinalgCUDA(292 cases:dtypes float64/float32/float16/bfloat16 x alpha in {1, 0.5, 0} x beta x
shapes {64x96x32, 1x8x32} x mat1/mat2 transposes;
the fallback boundaries of 1D and broadcast C, beta=0, strided and
column-major C, and C aliasing the output; and a test that counts launched
kernels to pin that the fast path is actually selected -- it fails against
the previous revision, which rejected a padded C)
python test/test_linalg.py -k padded_leading_dim TestLinalgCUDApython test/test_linalg.py -k test_addmm_mv TestLinalgCUDA(108 cases, thetest that triggered the revert)
@onlyCUDAselects ROCm too, andthe guard is compiled out there, so it legitimately counts two kernels. Its
rejected-layout check also asserts strictly-more-kernels rather than exactly
two, so an unrelated extra kernel on some backend cannot fail it.
python test/test_linalg.py -k mm TestLinalgCUDA, compared against a build ofthis commit's parent: no failures on either side
python test/test_nn.py -k linear(1106 tests, covers the shared bias path)torchrun --nproc_per_node=2remote-C ring-step benchmark andnn.Lineartimings, each run against a build of this commit and of its parent
This PR was authored with the help of an AI assistant.
Co-authored-by: Codex [email protected]
Co-authored-by: Claude [email protected]