Skip to content

[BE] Extend grouped_mm test coverage - #196075

Closed
Isalia20 wants to merge 3 commits into
pytorch:mainfrom
Isalia20:grouped-mm-tests
Closed

Isalia20 wants to merge 3 commits into
pytorch:mainfrom
Isalia20:grouped-mm-tests

Conversation

@Isalia20

@Isalia20 Isalia20 commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

Add more grouped_mm tests on MPS and other devices and some cleanups. The additional cases and why they are needed:

  • 2d_2d_ragged: Uses non-equal K groups of sizes 17, 13, 8 and 10.
  • 2d_3d_ragged: Uses 4 experts with 17, 13, 8 and 10 tokens, leaving partially filled kernel tiles.
  • 2d_2d_unequal_backing_k: This test uses different K dimensions for A and B, leaving some unused values after the last group.
  • wide_tiles: This one uses large weights to test MPS kernels that process 128 or 256 columns per tile.
  • large_stride_fallback: This one uses a stride above the int32 limit on a dimension of size one to test the MPS fallback.
  • u64_indexing: and finally, uses memory offsets above the int32 limit while each stride fits in int32.

@pytorch-bot

pytorch-bot Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 6ba0ca3 with merge base ad644bd (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Sep 4, 2026
@Isalia20 Isalia20 added better-engineering Relatively self-contained tasks for better engineering contributors ciflow/trunk Trigger trunk jobs on your pull request labels Sep 4, 2026
Comment thread test/test_linalg.py Resolved
@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this PR

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 24m 11s —— View job


Reviewed — the refactor is a real readability win, but it drops zero-size-group coverage (which answers @Skylion007's "we dropped a bunch of combinations here?"), and I can't find the MPS grouped_mm code that three of the new tests claim to target.

Full review

PR Review: #196075

Summary

Consolidates four TestGroupedMM shape-specific tests into one table-driven test_grouped_gemm plus three new MPS-targeted tests, and enables the class on MPS. The consolidation is a genuine improvement, but it silently drops empty-group coverage, and the three new tests reference MPS implementation details I cannot locate in this tree.

Testing

1. Zero-size group coverage is gone. The removed test_grouped_gemm_2d_3d and test_grouped_gemm_3d_2d each ran a check_zero_size variant that set offs[0] = offs[1], producing an empty group. None of the seven new subtests at test/test_linalg.py:11544-11550 has a repeated offset or a leading 0. This is not a hypothetical case — it is the normal MoE situation where an expert receives no tokens, and aten/src/ATen/native/GroupedMMUtils.h:110-115 zero-initializes the output specifically to get K=0 groups right on ROCm. The only remaining eager coverage is nothing; test/test_matmul_cuda.py:856 covers it but only under torch.compile and only on SM90+. Please add a subtest with e.g. [0, 17, 17, 48].

Fix this →

2. The fixture no longer self-validates, and strided=False is no longer contiguous. The old tests asserted self.assertTrue(a_contig.is_contiguous() is not strided), confirming the strided axis actually produced non-contiguous inputs. _make_grouped_mm_matrix (test/test_linalg.py:11500-11508) has no such check, so a stride-math bug would silently collapse all strided=True cases to contiguous and the entire axis would test nothing.

Worse, the assertion could no longer hold: for 2d_3d_ragged with a_shape=(48, 19) and bf16, stride = max(8, ceil(19/8)*8) = 24, so even at strided=False the tensor is 48x19 with strides (24, 1) — not contiguous. So the ragged subtests have no contiguous-input coverage on any device, including CPU/MPS where the 16-byte alignment padding that forces this isn't required. Consider padding only when the device needs it, and restoring the contiguity assertion for the cases where it should hold.

3. The CUDA skip is broader than the constraint it works around. At test/test_linalg.py:11554-11557:

unaligned = any(size % (16 // dtype.itemsize) for size in sizes)
if self.device_type == "cuda" and dtype != torch.float32 and unaligned:

On CUDA, bf16 only reaches a hardware grouped kernel when scaled_mm_arch_allowed(sm90_only, sm100_only) holds (aten/src/ATen/native/cuda/GroupedBlas.cpp:752) or cuBLASLt is preferred, and fp16 needs SM 9-11 plus CUDA >= 13.3 (GroupedBlas.cpp:76-101). On SM80/SM86/SM89 every dtype falls through to _grouped_mm_fallback, which handles unaligned shapes fine — so this skips all three ragged subtests for bf16/fp16 on hardware where they would pass. Net effect: on CUDA the new ragged coverage exists only for fp32. Gating on the arch/dtype combination that actually selects a hardware kernel would keep it.

Two smaller points on the same lines: sizes includes the raw offsets, but the quantity that must be aligned is the per-group size (the successive differences), not the cumulative offset — conservative, so not a bug, but it's checking the wrong number. And the message "Unaligned cases require the CUDA float32 fallback" reads backwards; it means "only fp32 reaches the fallback that tolerates unaligned shapes".

4. test_grouped_gemm_wide_tiles runs everywhere but is justified only for MPS. test/test_linalg.py:11563-11576 has no @onlyOn, so it also instantiates for CPU and CUDA, where it allocates a 32 MiB fp32 weight matrix and runs a full forward+backward with a per-group reference torch.mm — the CPU variant in particular is a slow test buying no coverage, since the comment states its purpose is reaching MPS BN128/BN256 dispatch. It also has no largeTensorTest guard despite the size. Same for test_grouped_mm_u64_indexing (:11589-11605), which allocates a ~4 GiB single buffer and is marked @onlyOn(["cuda", "mps"]); on CUDA it is just at::mm_out on a 1x1 and 1x2 matmul behind a largeTensorTest("6GB") + serialTest() gate. Both read as MPS-only tests; restricting them to mps would keep CUDA runners free.

5. torch.empty for the u64 storage. At :11599-11601 only storage[row*stride : row*stride+8] for rows 0-2 is initialized, which does cover every element b addresses. But the surrounding ~4 GiB is uninitialized, so any tiled kernel that reads a full tile past the 8 initialized columns pulls in garbage and can produce NaN. Since the whole point of the test is a tiled kernel, that's a plausible flake.

Code Quality

6. The index-selection block in grouped_mm_helper is hard to follow. test/test_linalg.py:11522-11528 branches on a.dim() == b.dim() and then re-branches on a.dim() == 2 inside a conditional expression, so the 2d/2d and 3d/3d cases share a line that means different things in each. Splitting it into four explicit named cases (2d/2d, 2d/3d, 3d/2d, 3d/3d) would be longer but immediately readable, and would make the out_idx conventions checkable by eye.

7. ends = ... else [0] * a.size(0) is an obscure sentinel. At :11518, the no-offsets (3d/3d) path builds a list of zeros purely to get a.size(0) loop iterations; span is then computed and never used, and start = end keeps start pinned at 0. It works, but range(a.size(0)) with the span computation skipped would say what's meant.

8. backward=False on 2d_2d_unequal_backing_k is unexplained. :11546 disables the backward check without a comment, unlike the other new tests which all carry a rationale comment. A short note on why (unequal backing K isn't differentiable through this path) would prevent someone from "fixing" it later.

9. Comment at :11515 describes a constraint the helper works around implicitly. "Odd output widths need padded gradients to satisfy grouped_mm alignment" explains the _make_grouped_mm_matrix call for the gradient, but the padding is produced as a side effect of the helper rather than stated at the call site. Worth naming the alignment requirement (check_valid_strides_and_return_transposed in GroupedMMUtils.h:40-48) so the link is traceable.

Infrastructure

10. I cannot find the MPS code that three tests claim to exercise. _grouped_mm in aten/src/ATen/native/native_functions.yaml:7169-7173 dispatches only CompositeExplicitAutograd: _grouped_mm and CUDA: _grouped_mm_cuda — there is no MPS entry, so on MPS this goes through _grouped_mm_fallback (GroupedMMUtils.h:156-205), a loop over at::mm_out/at::bmm_out. Searching aten/src/ATen/native/mps/ for grouped_mm/GroupedMM returns nothing, and BN128/BN256 appear nowhere in the repo except the new comment in this file. Reading aten/src/ATen/native/mps/operations/LinearAlgebra.mm, the MPS matmul path has TILE_DIM = 16 and a fixed BN = 64 with no 128/256 variant, no N >= 1024 + 32 MiB weight gate, and the offsetsFitIn<int32_t> check (aten/src/ATen/native/mps/OperationUtils.h:85-88, used at LinearAlgebra.mm:316) applies to the gemv path only, not mm/bmm.

So, as this branch stands, all three comments describe behavior that doesn't exist here:

  • :11571-11572 "MPS MPP BN128/BN256 kernels ... dispatch requires N >= 1024 and at least 32 MiB of weights"
  • :11582-11583 "Forces MPS's oversized-stride guard and jagged-column transposed fallback" — and separately, a stride of 2**32 on a size-1 dimension is exactly what an extent-based canUse32BitIndexMath-style check normalizes away, so even once the guard lands this may not trip it
  • :11596-11597 "Exercises MPS's combined extent/stride guard and 64-bit indexing"

If these depend on an unlanded MPS grouped_mm PR, please say so in the description and stack this on top — landing MPS-motivated tests ahead of the code they cover means they pass vacuously and nobody notices when the real kernel regresses. If the MPS kernel is already in tree somewhere I missed, point me at it and I'll re-check. Either way the comments need to name the file they refer to.

11. largeTensorTest("6GB") measures the wrong thing on MPS. _has_sufficient_memory in torch/testing/_internal/common_device_type.py:1736-1798 has no mps branch; MPS falls through to the psutil host-RAM path. So on MPS the 6GB guard checks system RAM, not device capacity. largeMPSBufferTest (:1850-1877) correctly covers the single-buffer cap, so stacking both is right — but worth knowing the footprint half of the guard is only approximate on MPS.

Recommendation

Needs Discussion

The consolidation is good and I'd take it. Two things should be resolved first: the dropped zero-size-group subtests are a straight coverage regression on a case the ROCm path has explicit handling for, and the three MPS-motivated tests need either the MPS kernel they target (stacked underneath) or corrected comments. The CUDA skip breadth and the @onlyOn scoping on the two expensive tests are worth folding in while you're here.

· branch [`grouped-mm-tests`](https://github.com/pytorch/pytorch/tree/grouped-mm-tests)

@Isalia20

Copy link
Copy Markdown
Collaborator 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

pytorchmergebot pushed a commit that referenced this pull request Sep 12, 2026
…h cuBLAS 13.1.1.3 used by CD (#196869)

## Summary

CI docker images for CUDA 13.0 (`.ci/docker/build.sh`, `install_cuda.sh`) are still pinned to CUDA
toolkit **13.0.2**, but the CD binary build matrix
([`generate_binary_build_matrix.py`](https://github.com/pytorch/pytorch/blob/d1ae7eed74b9ed5e31ac786b6434d2510169135b/.github/scripts/generate_binary_build_matrix.py#L34))
already builds cu130 wheels against **cuBLAS 13.1.1.3**, which ships with CUDA toolkit **13.0.3**, not
13.0.2. This CI/CD toolkit skew means CI tests run the CD-built wheel's cuBLAS 13.1.1.3 against an
older 13.0.2 driver/runtime stack than what it was built/validated for.

This is the root cause of the illegal-memory-access failures in
`TestGroupedMMCUDA.test_grouped_mm_u64_indexing_cuda_float16` on the periodic CUDA 13.0 B200 smoke lane
(e.g. https://github.com/pytorch/pytorch/actions/runs/34476417747/job/102891503623), which only started
showing up after [3c71ead](#196075) added coverage exercising this path, and which
#196775 worked around by skipping the test rather than fixing the underlying version mismatch.

- Bump `CUDA_VERSION` 13.0.2 -> 13.0.3 in `.ci/docker/build.sh`, `.ci/docker/common/install_cuda.sh`
  (installer bumped to `cuda_13.0.3_580.126.20_linux`, verified to exist at
  https://developer.download.nvidia.com/compute/cuda/13.0.3/local_installers/), and
  `.ci/docker/common/install_inductor_benchmark_deps.sh` (comment only).
- Same bump for the FA3 wheel build matrix in
  `.github/workflows/_binary-build-flash-attention-wheel-linux.yml` (x86_64 + aarch64 legs, including
  the aarch64 `cuda_installer_name`).
- `RELEASE.md` supported-architectures table version bump.
- Revert #196775 (`[CUDA] Skip grouped_mm u64 indexing on SM100 CUDA 13.0`) now that the underlying
  toolkit/cuBLAS mismatch causing the false failure is fixed.

## Test plan

- [ ] CI docker images rebuild successfully with CUDA 13.0.3.
- [ ] `TestGroupedMMCUDA.test_grouped_mm_u64_indexing_cuda_float16` passes on the periodic CUDA 13.0
      B200 smoke lane without the skip from #196775.
- [ ] FA3 wheel build workflow (`_binary-build-flash-attention-wheel-linux.yml`) succeeds for both
      x86_64 and aarch64 cu130 legs with the new installer.

Debugged by @nWEIdia _manually_ but 🤖 Generated with [Claude Code](https://claude.com/claude-code)
p.s. the timing is a bit awkward that we are sunsetting cuda 13.0 CI, so... I think it is a good fyi anyways.

Pull Request resolved: #196869
Approved by: https://github.com/Skylion007

Co-authored-by: Claude Sonnet 5 <[email protected]>
zbrad added a commit to zbrad/pytorch that referenced this pull request Nov 9, 2026
The 2026-11-08 full run after the 3d_3d skip failed on six more cases of
the same upstream test (pytorch#196075): strided, column-major a, bf16, the
2d_2d/2d_3d/3d_2d regular shapes. Same cause: sm_89 runs
_grouped_mm_fallback, whose gradients differ from the per-group torch.mm
reference by one bf16 ulp; against float64 grouped_mm is the more accurate
(0.058-0.062 vs 0.075-0.089). All 14 failures were 3 of 3 runs of every
CUDA test_grouped_gemm case; the other 196 pass. Listed by full name;
checked that the expression deselects exactly those 14.

Assisted-by: Claude
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

better-engineering Relatively self-contained tasks for better engineering contributors ciflow/trunk Trigger trunk jobs on your pull request Merged open source topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants