Skip to content

Avoid D2D copy for addmm with distinct C and D - #191706

Closed
anijain2305 wants to merge 13 commits into
gh/anijain2305/1279/basefrom
gh/anijain2305/1279/head
Closed

anijain2305 wants to merge 13 commits into
gh/anijain2305/1279/basefrom
gh/anijain2305/1279/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

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")) 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]

@pytorch-bot

pytorch-bot Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 2 New Failures, 7 Unrelated Failures

As of commit e415b6e with merge base 2942118 (image):

NEW FAILURES - The following jobs have failed:

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

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

@pytorch-bot pytorch-bot Bot added ciflow/b200 ciflow/h100 ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 labels Jul 31, 2026
anijain2305 added a commit that referenced this pull request Jul 31, 2026
Add a guarded cuBLASLt addmm path that passes separate C and D pointers directly to cuBLASLt instead of first copying C into D. This will be used to improve matmul_reduce_scatter performance in later PRs.


ghstack-source-id: da8dea9
Pull-Request: #191706
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
@anijain2305 anijain2305 changed the title Avoid D2D copy for addmm with separate C and D Avoid D2D copy for addmm with distinct C and D Jul 31, 2026
@anijain2305
anijain2305 force-pushed the gh/anijain2305/1279/head branch from 5efe8b6 to 1d22c5b Compare July 31, 2026 21:14
@pytorch-bot pytorch-bot Bot added ciflow/h100-symm-mem ciflow/torchtitan Run TorchTitan integration tests labels Jul 31, 2026
@anijain2305
anijain2305 force-pushed the gh/anijain2305/1279/head branch from 681d380 to 1d22c5b Compare July 31, 2026 21:32
@anijain2305
anijain2305 marked this pull request as ready for review July 31, 2026 23:39
@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

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 review

PR Review: #191706

Summary

Adds at::cuda::blas::gemm_with_distinct_c_and_d plus a guarded call site in addmm_out_cuda_impl so that D = alpha*mat1@mat2 + beta*C can be issued to cuBLASLt with distinct C and D pointers, skipping the copy_(result, self) pre-pass. The pointer/leading-dimension math checks out, but there are no tests, TunableOp is silently bypassed for the affected shapes, several ROCm gates present in the existing Lt guard are not replicated, and ~200 lines are copy-pasted from gemm_and_bias.

Testing

No test changes in a 402-line PR that introduces a brand-new numeric kernel path. This is the blocking issue.

At minimum:

  1. A device-generic numerics test (instantiate_device_type_tests, @parametrize over dtype ∈ {float64, float32, float16, bfloat16}, alpha/beta ∈ {non-trivial values}, and mat1/mat2 transpose combinations) asserting torch.addmm(C, A, B, beta=..., alpha=...) matches the reference when out is a distinct tensor. test/test_linalg.py:6405 (test_addmm) is the natural home.
  2. A test that the guard boundaries actually fall back and stay correct: 1D self, broadcast self (e.g. (1, N) into (M, N)), non-contiguous self or out, self aliasing out, mat2 with a size-1 dim, complex dtypes, and beta=0.
  3. A test with DISABLE_ADDMM_CUDA_LT=1 to confirm the guard honors it.
  4. A TunableOp test (see below) — test/test_linalg.py:11069 has the existing pattern.

Without (1) the numerics of the new path are unverified anywhere, and without (2) the fallback edges are unverified. Fix this →

Infrastructure

TunableOp is silently bypassed. launchGemmAndBiasCublasLt (aten/src/ATen/native/cuda/Blas.cpp:335-342) checks getTuningContext()->IsTunableOpEnabled() and routes to launchTunableGemmAndBias; the non-Lt at::cuda::blas::gemm also honors TunableOp (aten/src/ATen/cuda/CUDABlas.cpp:1415-1421). The new launchGemmWithDistinctCAndDCublasLt (Blas.cpp:387-412) has no such check and returns early at Blas.cpp:489-491. Before this PR, 2D-self + activation == None + beta != 0 fell to the non-Lt GEMM branch, so it was tunable. After this PR, that exact shape stops being tuned. Either add a TunableOp early-out in canUseAddmmCudaLtWithDistinctCAndD (simplest, and matches "keep the optimization narrow"), or wire it through a tunable op. Fix this →

ROCm arch gate is dropped. Blas.cpp:441-444 re-runs isGloballyDisabledAddmmCudaLt(self.device()) on ROCm precisely because the result "is conditioned on the device index, which is not persistent". The new call site (Blas.cpp:465-474) passes only persistent_disable_addmm_cuda_lt || disable_addmm_cuda_lt_override, so on a multi-arch ROCm host the new path can run on a device whose arch has no hipBLASLt support. You can't just pass disable_addmm_cuda_lt since line 446 has already folded in !isInputCompliesAddmmCudaLt(...); hoist the global/device disable into its own local computed after line 444 and pass that. Fix this →

ROCm 2D-bias exclusion is inverted, and the ROCm 6.4 workaround is not replicated. isInputCompliesAddmmCudaLt returns false on ROCm whenever self.is_same(result) || self.dim() == 2 (Blas.cpp:168-176) — 2D self is deliberately never sent to hipBLASLt today. The new guard requires self.dim() == 2 (Blas.cpp:248), so it enables on hipBLASLt exactly the configuration the existing code excludes, with no ROCm test coverage. It also does not replicate the ROCm 6.4 transa=='t' && transb=='t' fp32 regression bail-out at Blas.cpp:178-184. Given the stated motivation is CUDA symmetric-memory matmul_reduce_scatter, consider gating the new guard behind #ifndef USE_ROCM for now rather than opening a path with no ROCm validation.

Code Quality

~200 lines duplicated from gemm_and_bias. gemm_with_distinct_c_and_d (aten/src/ATen/cuda/CUDABlas.cpp:1705-1907) is a near-verbatim copy of gemm_and_bias (CUDABlas.cpp:1500-1907). The only substantive differences are: no bias pointer / CUBLASLT_MATMUL_DESC_BIAS_POINTER, a separate Ddesc, and beta_val taken as an argument instead of derived from bias ? 0 : 1. Everything else — the ROCm dtype checks, the FP16/BF16 reduction-scheme masks, the SM-carveout handling, the alignment preferences, the heuristic call, the warning block — is copied. This will drift: any future fix to reduction masks or carveout handling now has to be made twice. Prefer extending gemm_and_bias with optional const C_Dtype* c_ptr / c_ld / explicit beta (defaulting to the current behavior) or factoring the shared descriptor/preference setup into a helper.

Concretely, the copy already carries a pre-existing bug forward: on ROCm, when returnedResult == 0 the _syncCurrentWithCarveoutStream(stream, false) unwind is skipped because it lives inside the else branch (CUDABlas.cpp:1873-1877 in the new function, mirroring 1665-1669). Deduplicating means fixing it once instead of twice. Fix this →

The activation parameter is dead. canUseAddmmCudaLtWithDistinctCAndD rejects activation != Activation::None (Blas.cpp:245), so activation_to_gemm_and_blas_arg(activation) at Blas.cpp:410 is always None and the CUBLASLT_MATMUL_DESC_EPILOGUE is always CUBLASLT_EPILOGUE_DEFAULT. Drop the parameter from launchGemmWithDistinctCAndDCublasLt and from canUseAddmmCudaLtWithDistinctCAndD, or drop the activation restriction and actually exercise it. Shipping an untestable parameter invites a future caller to pass RELU/GELU and assume it works.

TORCH_WARN on the fallback path will spam. CUDABlas.cpp:1879-1906 warns on every failed call. Unlike gemm_and_bias, whose failure triggers a one-shot recursion with Lt disabled, this path can fail on every iteration of a training loop for a shape cuBLASLt structurally does not support, producing one warning per addmm. Use TORCH_WARN_ONCE — falling back here is expected and benign, per the PR description.

Unrelated diff noise. #include <optional>, <string>, <vector> are added at CUDABlas.cpp:18-20 but the new function uses none of them, and there is a whitespace-only insertion at Blas.cpp:155. Both should be dropped.

Redundant guard conditions. At Blas.cpp:466, mat1.sizes()[1] != 0 is implied by the guard's own mat2.sizes()[0] > 1 (line 277), and beta.toComplexDouble() == 0.0 at line 245 is already guaranteed false by the caller's check at line 464.

Performance / Fragility

launchGemmWithDistinctCAndDCublasLt passes self.stride(0) as c_ld (Blas.cpp:407) while result_ld comes from args.result_ld, which cublasCommonArgs derives as result->stride(transpose_result ? 0 : 1) (cuBlasCommonArgs.h:141). The math works today only because the guard forces result.is_contiguous(), which forces transpose_result == true, which makes stride(0) the correct column-major leading dimension for both. If the contiguity guard is ever relaxed to allow a column-major result, c_ld becomes silently wrong and produces bad numerics with no error. Derive c_ld the same way result_ld is derived (or add a TORCH_INTERNAL_ASSERT_DEBUG_ONLY tying self.stride(0) == args.result_ld together with a comment explaining the row-major assumption).

Recommendation

Request 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 gemm_and_bias should be resolved before this lands since later PRs in the stack will build on it.

| Branch: `gh/anijain2305/1279/head`

Comment thread aten/src/ATen/cuda/CUDABlas.cpp Outdated
}

template <typename Dtype, typename C_Dtype>
bool gemm_with_distinct_c_and_d(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

check if you can reuse existing template, I'm pretty sure there's a lot of code repetition that we can avoid

Comment thread aten/src/ATen/native/cuda/Blas.cpp Outdated
if (self.sizes()[0] != result.sizes()[0] || self.sizes()[1] != result.sizes()[1]) {
return false;
}
if (!self.is_contiguous() || !result.is_contiguous()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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)

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added the release notes: linalg_frontend release notes category label Aug 4, 2026
@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Claude finished @anijain2305's task in 40m 57s —— View job


The refactor addressed both of @ngimel's comments well (gemm_and_bias is extended rather than duplicated, and padded leading dimensions are now accepted and tested), but the new tests never verify the fast path is actually taken, one of them compares uninitialized memory, and the early return result silently depends on a guard invariant that should be asserted.

Full review

PR Review: #191706 (v2)

What changed since the last round

Both reviewer comments are addressed:

  • @ngimel, "reuse existing template" — gemm_with_distinct_c_and_d is gone. gemm_and_bias now takes optional c_ptr / c_ld / beta_opt (aten/src/ATen/cuda/CUDABlas.cpp:1511-1513). This is the right call: ~200 lines of reduction-scheme / carveout / alignment / heuristic handling stay in one place. Net diff shrank from 402 to 279 lines.
  • @ngimel, "leading dimensions larger than sizes" — confirmed and enabled. isRowMajorWithValidLeadingDim (Blas.cpp:234) accepts stride(0) >= sizes()[1], and test_addmm_out_padded_leading_dim exercises it.
  • TunableOp is now explicitly excluded (Blas.cpp:255), and the ROCm device-index gate is preserved via disable_addmm_cuda_lt_for_new_path (Blas.cpp:463).

I verified the GEMM geometry independently. With transpose_result == true (forced by the row-major result guard), cublasCommonArgs sets blas m = mat2.size(1), n = mat1.size(0), and result_ld = result->stride(0) (cuBlasCommonArgs.h:136-141). So Cdesc(cType, m, n, self.stride(0)) and Ddesc(cType, m, n, result_ld) describe column-major N x M views of the row-major (M, N) C and D, with sizes guarded equal. Correct.


Testing

The tests never confirm the new path runs. Every assertion in all three new tests would pass identically if canUseAddmmCudaLtWithDistinctCAndD returned false unconditionally. test_addmm_out_padded_leading_dim's padding check does not discriminate either — copy_ into a narrow view leaves the padding columns alone too. So the entire 98-case matrix is a correctness net for addmm in general, not for this PR's path. Since the whole point of the change is which kernel sequence runs, at least one test should pin that down: expose a counter (there is precedent for torch._C._... debug counters), or compare kernel counts under torch.profiler against a DISABLE_ADDMM_CUDA_LT=1 run in a subprocess. Fix this →

test_addmm_out_padded_leading_dim compares uninitialized memory. test_linalg.py:6499-6506:

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

filler is a clone of torch.empty output, so the assertEqual(wide_out[:, n:], filler[:, n:]) at the end compares uninitialized device memory against a snapshot of itself. It happens to pass (assertEqual defaults to equal_nan=True, so garbage NaN payloads compare equal), but the check has no defined contract. Use initialized memory for the base and drop the _base introspection:

wide_out = make_tensor((m, 2 * n), dtype=dtype, device=device, low=-1, high=1)
filler = wide_out.clone()
out = wide_out[:, :n]

The out._base is None branch also makes the first loop iteration skip the padding check entirely, so the loop is doing two unrelated things. Two explicit cases would read better than the conditional. Fix this →

Minor: @reduced_f32_on_and_off(0.05) on an @onlyCUDA test is a no-op — the decorator gates on torch.device(device).type == "cpu" (common_mkldnn.py:97). It mirrors the surrounding style, so harmless, but it is not buying coverage.


Correctness

The early return result bypasses the args.result writeback. Blas.cpp:502-504 returns before line 623's if (!result.is_same(*args.result)) result.copy_(*args.result);. That is safe today only because the guard forces result to be row-major and non-conj, so prepare_matrix_for_cublas borrows rather than cloning (cuBlasCommonArgs.h:41-57) — the two escape hatches into an owned copy are the clone(Contiguous) fallback for genuinely strided tensors and resolve_conj_if_indicated, both excluded. This is a load-bearing invariant with no assertion behind it: relax the layout guard later and you get a silently discarded result. The existing TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!args.result->is_conj()) at Blas.cpp:490 does not cover it. Assert the aliasing and the leading dimension together:

TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
    args.result->is_same(result) && args.result_ld == result.stride(0));

Fix this →

d_alignment is getAlignment(nullptr) == 256 when both bias and c_ptr are null. CUDABlas.cpp:1628-1629:

uint32_t d_alignment = detail::getAlignment(reinterpret_cast<uintptr_t>(
    c_ptr ? static_cast<const void*>(result_ptr) : static_cast<const void*>(bias)));

getAlignment (CublasLtUtils.h:284) loops down from 256 and 0 % 256 == 0, so a null bias yields 256. That path is reachable today: launchGemmAndBiasCublasLt passes bias == nullptr whenever self.dim() != 1 (the activation != None + 2D-self branch of isInputCompliesAddmmCudaLt), so cuBLASLt is told D is 256-byte aligned when result may be a 4-byte-aligned view with a nonzero storage offset, and the heuristic may hand back an algorithm with vectorized stores it cannot legally use. This is pre-existing and the PR does not make it worse — the new path correctly passes result_ptr — but the PR is rewriting exactly these two lines, so it is the natural place to fix. d_alignment should always be getAlignment(result_ptr); the bias pointer's alignment has no cuBLASLt preference to express. Fix this →

TORCH_WARN -> TORCH_WARN_ONCE can now silence a real diagnostic. CUDABlas.cpp:1679. Suppressing the spam is right for the new path, where failure is expected and benign, but the counter is shared with the bias path. One benign distinct-C/D miss now permanently suppresses the warning for a genuine gemm_and_bias failure that costs a full recursion with Lt disabled. Two related nits: the message still says "Will attempt to recover by calling unfused cublas path", which is wrong for the new path (it recovers via copy-then-GEMM, possibly still on Lt), and it does not print c_ld or whether c_ptr was set, which are the two variables you would want when debugging a distinct-C/D rejection. Consider a separate warning site (or a c_ptr-aware message) rather than sharing the once-flag.

is_neg() / is_conj() guard. Blas.cpp:268 excludes neg and conj views of self and result. Correct and cheap — the fallback's copy_ resolves those bits, and the raw const_data_ptr here would not. Good catch by whoever added it.


Performance

One extra cublasLtMatrixLayoutCreate per call on the hot bias path. Ddesc is unconditionally constructed at CUDABlas.cpp:1618 even when c_ptr == nullptr, taking the descriptor count from 3 to 4 on every nn.Linear / addmm Lt call. cublasLtMatrixLayoutCreate allocates; for small eager-mode GEMMs, launch-side CPU overhead is the thing that matters. Since the layouts are provably identical when c_ptr is null, construct lazily:

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 nn.Linear shape would derisk the regression. Fix this →


Code quality

Dead clause in isRowMajorWithValidLeadingDim (Blas.cpp:235-236):

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. stride(0) >= sizes()[1] >= 1 covers it for any nonempty tensor, and the only way sizes()[1] can be 0 is numel() == 0, which the call site already excludes (Blas.cpp:485). Drop it; a reader will otherwise spend time working out what case it protects.

isRowMajorWithValidLeadingDim is unused on ROCm. canUseAddmmCudaLtWithDistinctCAndD returns false from inside #ifdef USE_ROCM before the only call site, so this file-static function is unreferenced in ROCm builds and will draw -Wunused-function (in -Wall). ROCm builds do not set WERROR, so it is noise rather than a break, but move it inside the #else (or guard it) to keep the build clean. Fix this →

Naming.

  • disable_addmm_cuda_lt_for_new_path (Blas.cpp:463) will not age well — nothing is "new" six months from now. disable_addmm_cuda_lt_unconditioned (or splitting isInputCompliesAddmmCudaLt's result into its own local, which is arguably cleaner than deriving one flag from another) says what it means.
  • The parameter is beta_val in the header (CUDABlas.h:130) but beta_opt in the definition (CUDABlas.cpp:1513). Legal, but pick one.
  • gemm_and_bias now also means "gemm with a distinct C and no bias", and the two features are mutually exclusive by TORCH_INTERNAL_ASSERT (CUDABlas.cpp:1514-1516). Extending is still the right trade against 200 duplicated lines, but the runtime assert on a signature-level invariant is a smell worth a comment on the declaration explaining why it is not two functions.

Minor precision note. With allowFP16AccumulationCuBLAS() and computeType == CUBLAS_COMPUTE_16F, hbeta_val = beta_val (CUDABlas.cpp:1550) now narrows a user-supplied beta to fp16. Before this PR beta_val was only ever 0 or 1 there, so the narrowing was exact. It matches how alpha is already handled and fp16 accumulation is opt-in and lossy by construction, so this is a note rather than a request.


Recommendation

Approve 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 d_alignment and lazy-Ddesc items are worth folding in while this code is open but are not blockers.

| Branch: `gh/anijain2305/1279/head`

[ghstack-poisoned]
@anijain2305

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Claude finished @anijain2305's task in 21m 31s —— View job


The refactor is in good shape and the geometry checks out, but the new ..._is_selected test will fail on ROCm CI (the guard is compiled off there while the test is @onlyCUDA), the fallback test labelled "input aliasing out" doesn't actually reach the aliasing guard, and the d_alignment fix silently changes the pre-existing nn.Linear path.

Full review

PR Review: #191706 (v3)

Summary

Extends gemm_and_bias with optional c_ptr/c_ld/beta_opt so CUDA addmm can hand cuBLASLt distinct C and D pointers instead of pre-copying C into D. Both of @ngimel's comments are addressed (no duplicated 200-line function; padded leading dimensions accepted). The prior round's uninitialized-memory issue in test_addmm_out_padded_leading_dim is fixed, isRowMajorWithValidLeadingDim is now #ifndef USE_ROCM-guarded, and the early-return invariant is asserted. Three problems remain: a ROCm CI break in the new selection test, a fallback test that does not exercise the guard it claims to, and an undocumented change to the pre-existing default path.

I re-verified the GEMM geometry independently. With transpose_result == true (forced by the row-major result guard), cublasCommonArgs gives blas m = mat2.size(1), n = mat1.size(0), result_ld = result->stride(0) (cuBlasCommonArgs.h:136-141). Cdesc(cType, m, n, self.stride(0)) and Ddesc(cType, m, n, result_ld) therefore describe column-major N x M views of the row-major (M, N) C and D. Also confirmed mat2.sizes()[0] > 1 (Blas.cpp:289) already excludes k == 0, so the block at Blas.cpp:485 cannot preempt the empty-reduction-dim short-circuit at Blas.cpp:524.


Testing

test_addmm_out_distinct_c_and_d_is_selected will fail on ROCm. canUseAddmmCudaLtWithDistinctCAndD returns false unconditionally inside #ifdef USE_ROCM (Blas.cpp:246-249), but the test is @onlyCUDA, and ROCm reports device_type == "cuda" (common_device_type.py:2010), so it runs in the ROCm jobs. There, kernel_count(contiguous) is the copy-then-GEMM count, not 1, and assertEqual(kernel_count(contiguous), 1) at test_linalg.py:6510 fails. skipIfRocm is already imported in this file (test_linalg.py:30) — apply it. The test also fails for anyone running with DISABLE_ADDMM_CUDA_LT=1. Fix this →

The kernel count is more brittle than it needs to be. test_linalg.py:6500-6503 counts every profiler event with device_type.name == "CUDA" and self_device_time_total > 0. That bucket includes GPU_MEMCPY and GPU_MEMSET (torch/csrc/profiler/kineto_shim.cpp:511-521), so a cuBLASLt workspace memset or a split-k reduction kernel turns 1 into 2 and the test reports a false regression. self_device_time_total > 0 is also a resolution-dependent filter for sub-microsecond kernels. The idiomatic approach in this repo is to filter cat == "kernel" out of export_chrome_trace (test/test_matmul_cuda.py:148-163, test/inductor/test_max_autotune.py:1154-1174). Asserting fast_count < fallback_count rather than exact 1 and 2 would also hold up better across cuBLASLt versions. Separately, add a kineto_available() guard: CUDA-only activities with no kineto raises AssertionError("Legacy CUDA profiling requires use_cpu=True") (torch/autograd/profiler.py:325-331) rather than skipping, and the torch.cuda.synchronize() inside the profiled region is redundant since profile.__exit__ already syncs (profiler.py:432-435). Fix this →

The "input aliasing out" fallback case never reaches the aliasing guard. test_linalg.py:6474-6477 does torch.addmm(aliased, mat1, mat2, beta=0.75, out=aliased). That makes result.is_same(self) true, so addmm_out_cuda_impl skips the entire if (!result.is_same(self)) block at Blas.cpp:480 — the distinct-C/D candidate check at Blas.cpp:485 is never evaluated, and self.is_alias_of(result) at Blas.cpp:275 is never reached. The case that guard exists for is two distinct tensors sharing storage, e.g.:

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. self.is_conj() || result.is_conj() || self.is_neg() || result.is_neg() (Blas.cpp:269) and the dtype-equality check (Blas.cpp:278, which is what keeps the half-in/float-out path away from data_ptr<scalar_t>()) are both unexercised. A neg view via torch._neg_view and a torch.addmm(half_c, half_a, half_b, out=float_out) case would each be one line in test_addmm_out_distinct_c_and_d_fallbacks.


Infrastructure

d_alignment changes behavior on the pre-existing default path, undocumented. CUDABlas.cpp:1634 now computes d_alignment from result_ptr where base computed it from bias. When c_ptr == nullptr — every pre-existing caller — that is a real change, in both directions:

  • bias == nullptr: getAlignment(nullptr) returned 256 (detail/CublasLtUtils.h:284-291, 0 % 256 == 0), so base over-promised D alignment. It now drops to the true alignment of result_ptr, which strictly narrows the algorithm set cublasLtMatmulAlgoGetHeuristic may return (CUDABlas.cpp:1638,1644). This is reachable: launchGemmAndBiasCublasLt passes bias == nullptr whenever use_bias_ptr_lt is false but Lt is on (Blas.cpp:475-477), i.e. the activation != None + 2D-self branch, and TunableGemm.h:55 can pass a null params->bias too.
  • bias != nullptr (the 1D-bias nn.Linear path): d_alignment now reflects D instead of the bias buffer, so it can move either way for an out= view at a nonzero offset.

This is a defensible fix — base was feeding the wrong pointer into CUBLASLT_MATMUL_PREF_MIN_ALIGNMENT_D_BYTES — but it is folded silently into a feature PR whose own header comment claims the "alignment preferences and heuristic selection ... is identical" (CUDABlas.h:132-134). Call it out in the commit message, correct that comment, and sanity-benchmark a plain nn.Linear shape: the PR's numbers only cover the new path, and the narrowing direction lands on untouched code. Fix this →

Duplicated eligibility logic. canUseAddmmCudaLtWithDistinctCAndD (Blas.cpp:281-289) re-lists the dtype set and the mat2_sizes[0] > 1 && mat2_sizes[1] > 1 shape restriction that isInputCompliesAddmmCudaLt already encodes (Blas.cpp:216-228), minus the #ifndef USE_ROCM on Double. Two independent answers to "is this Lt-eligible" will drift the next time cuBLASLt gains or loses a dtype. At minimum the dtype list should be a shared helper rather than a verbatim copy.


Code Quality

TORCH_INTERNAL_ASSERT on a signature-level invariant, on the hottest GEMM entry point. CUDABlas.cpp:1514-1516 checks !(bias && c_ptr) unconditionally in release builds, for a condition no caller can violate at runtime (each of the three call sites passes a compile-time-fixed combination). TORCH_INTERNAL_ASSERT_DEBUG_ONLY expresses the same contract without the release-mode branch. The header comment at CUDABlas.h:130-134 explaining why this is one function rather than two is good and should stay.

beta is now narrowed to fp16. CUDABlas.cpp:1550 does hbeta_val = beta_val when Dtype == at::Half and computeType == CUBLAS_COMPUTE_16F. Before this PR beta_val there was only ever 0 or 1, so the narrowing was exact; it now truncates a user-supplied beta. It matches how alpha is already handled at CUDABlas.cpp:1549 and allowFP16AccumulationCuBLAS is opt-in and lossy by construction, so this is a note rather than a request — but it belongs in the commit message alongside the alignment change.

@tf32_on_and_off(0.05) is applied to a float64 parametrization. test_addmm_out_distinct_c_and_d runs over floating_types_and(bfloat16, half), and the tf32 decorator has no effect for double/bfloat16/half. Harmless and consistent with the surrounding tests, but it means the 0.05 relative tolerance only ever applies to the float32 cases.


Recommendation

Request 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 cat == "kernel" so the selection test does not go flaky on a workspace memset. The d_alignment and fp16-beta items need a sentence in the commit message plus a plain-nn.Linear perf sanity check, since they touch code this PR is not otherwise about.

| Branch: `gh/anijain2305/1279/head`

[ghstack-poisoned]
@anijain2305

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

[ghstack-poisoned]
@anijain2305

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: New commits were pushed while merging. Please rerun the merge command.

Details for Dev Infra team Raised by workflow job

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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
For more information see pytorch-bot wiki.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@anijain2305

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

@anijain2305

Copy link
Copy Markdown
Contributor Author

mergedog handoff

Note

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 @pytorchbot merge.

Current PR head: 42f993f3f48349032b5e25cadc5d8ad716cd74ef.
No mergedog-authored commits were pushed during this run.

CI notes at handoff

mergedog is treating these still-failing checks as unrelated/spurious. Please verify before merging:

  • linux-jammy-cuda13.0-py3.12-gcc11-sm100 / test (smoke_b200, 1, 1, linux.dgx.b200)
  • linux-jammy-cuda13.2-py3.12-gcc11-sm100 / test (smoke_b200, 1, 1, linux.dgx.b200)

Warning: mergedog's suppressed check list differs from the latest Dr. CI summary.

Suppressed by mergedog but not marked unrelated by Dr. CI:

  • linux-jammy-cuda13.0-py3.12-gcc11-sm100 / test (smoke_b200, 1, 1, linux.dgx.b200)
  • linux-jammy-cuda13.2-py3.12-gcc11-sm100 / test (smoke_b200, 1, 1, linux.dgx.b200)
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 &rarr;</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 &rarr;</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.

nWEIdia added a commit to nWEIdia/pytorch that referenced this pull request Aug 10, 2026
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]>
pytorchmergebot pushed a commit that referenced this pull request Aug 11, 2026
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]>
ankitbhrdwj pushed a commit to ankitbhrdwj/pytorch that referenced this pull request Aug 12, 2026
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
ankitbhrdwj pushed a commit to ankitbhrdwj/pytorch that referenced this pull request Aug 12, 2026
ankitbhrdwj pushed a commit to ankitbhrdwj/pytorch that referenced this pull request Aug 12, 2026
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
ankitbhrdwj pushed a commit to ankitbhrdwj/pytorch that referenced this pull request Aug 12, 2026
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]>
gavinwang269 pushed a commit to gavinwang269/pytorch that referenced this pull request Aug 13, 2026
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]>
@github-actions
github-actions Bot deleted the gh/anijain2305/1279/head branch November 2, 2026 01:43
zbrad added a commit to zbrad/pytorch that referenced this pull request Nov 9, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/b200 ciflow/h100-symm-mem ciflow/h100 ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: linalg_frontend release notes category Reverted topic: performance topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants