Repository navigation
[ROCm]: Added Platform-Specific Configuration Structs to CK-Tile Group-Gemm Backend - #200640
TheRealMichaelWang wants to merge 54 commits into
Conversation
…r both gfx942 and gfx950
…s for CK-tile group gemm
…r CK-Tile backend of grouped gemm - prepare_grouped_gemm extracts the pointers, strides, and size of each GEMM from a_mat, b_mat, offsets and places it in the right ggroup_args element\ - this function runs on the device to avoid having to move offsets array from device to host (which is read for any case involving 2d a_mat or b_mat)
…ions for the ck tile backend of group gemm. - run_cktile_group_gemm launches the kernel, given layouts for the A matricies, B matricies, and a config struct - launch_cktile_group_gemm selects the config depending on data type, shape, etc...
…group gemm/grouped mm to the ck tile backend for grouped gemm
…o be on the device (so long as the other tensors, etc... are on the same device which they usually are)
…illing and added a config for backwards to speed backwards up
…nst mixed types, etc...
This reverts commit 40f1701.
This reverts commit a5178e6.
…s/test_matmul) that supports ck tile in addition to ck
…ectness isue in unbounded odd n case for fp16.
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". 🟡 AUTOMATED REVIEW - Changes requested:
Findings (10): Reviewed commit: 🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/200640
Note: Links to docs will display an error until the docs builds have been completed. ❌ 1 New Failure, 1 Unrelated FailureAs of commit ffb6fef with merge base 109544c ( NEW FAILURE - The following job has failed:
NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following job failed, but the AI CI Advisor judged the failure not to be evidence against this change:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
1 similar comment
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
|
@pytorchbot label "topic: not user facing" |
|
@pytorchbot review |
|
@slayton58 Appreciate if you could take a look at why this was reverted internally by D129530254. It was an automated DK revert. |
@slayton58 has given me the cause of the reversal. In summary, the revert was caused an internal meta lint issue with missing designated initializers for properties I intended to initiate to their default issues. That lint issue has been fixed, but now the primary blocker is the auto-review bot which had previously approved the pr, but now is raising issues about comments, etc... |
|
@pytorchbot review |
|
@pytorchbot review |
@TheRealMichaelWang The bot needs more work, it's pretty noisy at the moment. In this case, let me know if its suggestions make sense. If it goes too much into nitpicking, I can help opt-out the change from the bot and we can just ask @slayton58 for his review instead. |
That would be fantastic! Also wanted to mention that because of a cryptic quirk of meta's internal CI, this PR would have to be completely closed and a new one opened with it's exact changes. @slayton58 said he'd push it through so long as the CI on this PR was green |
There was a problem hiding this comment.
Automated review of ffb6fef: changes requested before human review.
The PR adds per-arch and per-dtype tile-config tables (gfx950/gfx942, bf16/fp16) to the CK-Tile grouped GEMM backend, picks a config with a load_cost heuristic, works around CK eight-wave bugs, and replaces the zero-filled dW output with at::empty plus a zero_empty_k_groups kernel. Recommendation: Request Changes. No correctness or BC defect was found, but the review asks for a shared support predicate, a type check on the raw memcpy, a compile-time error for malformed config specializations, the header glob entry, and test cleanups.
🔴 6 blocking findings are attached to the code below.
⚪ 4 non-blocking findings
Error macros are inconsistent. .hip:539 checks an invariant that canonicalization guarantees ("unexpected layout pair after canonicalization"), so it should be TORCH_INTERNAL_ASSERT, not TORCH_CHECK. Also, with_ck_type's default: at .hip:650 uses TORCH_CHECK(false, ...), while the neighbouring "no configs" errors at :663 and :673 use TORCH_CHECK_NOT_IMPLEMENTED.
load_cost hand-rolls existing helpers (.hip:279, :283). It defines a local ceil_div lambda and computes ceil_div(k, K_Tile) * K_Tile, which at::ceil_div and at::round_up in ATen/ceil_div.h already provide. They are C10_HOST_DEVICE; pass <int64_t> explicitly because Config::*_Tile is index_t.
Low confidence: new unshimmed dependency on CK internals. ck_tile::core::arch::amdgcn_target_id is new to the repo and is used only as a host-side template tag. The same backend's ck_tile_group_gemm_utils.h:10-47 already carries a shim so it builds against two CK versions, and this PR was reverted once over an internal build issue. A local enum class { GFX942, GFX950 } would give the same dispatch without tying the config tables to a CK revision. The reviewer could not confirm whether the symbol exists at the pinned CK commit.
zero_empty_k_groups does more work than it needs to (.hip:324-343, launched at :498-502). Each element does a 64-bit i / N and i % N, which AMDGPU emulates in software. The row_stride generality isn't needed: on this path out always comes from at::empty(...first) (GroupedBlas.cpp:807-808), so it is contiguous and row_stride == N; index group_out[i] directly. The grid is fixed at dim3(64, group_count) regardless of M*N, and the kernel launches on every dW call even when no group is empty. It is already much cheaper than the old full at::zeros, so this is not a regression, only an avoidable cost.
Please address the findings and push; a new commit normally gets a fresh automated review.
This review is AI-generated and advisory. Each new automated review replaces the previous one.
| return false; | ||
| } | ||
| // group_gemm_ck_tile stores sizes and leading dims in 32 bits; a 3D operand's group stride may be wider. | ||
| constexpr int64_t int32_max = std::numeric_limits<int32_t>::max(); |
There was a problem hiding this comment.
🔴 The ck_tile support checks are duplicated, and the PR adds another copy. The new int32 size/stride loop in ck_tile_group_gemm_supported (GroupedBlas.cpp:750-756) mirrors the TORCH_CHECK at ck_tile_group_gemm.hip:622-631. It sits next to the existing duplicated canonicalization (GroupedBlas.cpp:759-764 vs .hip:565-581) and 16-byte alignment check (:765-766 vs .hip:632-637). GroupedBlas.cpp:810-811 calls the kernel with no fallback, so if the copies drift, a hipBLASLt fallback becomes a hard error. That is exactly the bug test_grouped_gemm_ck_tile_large_stride_fallback covers. Fix: declare one predicate in ck_tile_group_gemm.h (CK-free, already included by GroupedBlas.cpp:26) and define it in the .hip next to the checks it must agree with.
| .stride_Ds = {}, .stride_E = static_cast<index_t>(ldc), .k_batch = 1}; | ||
| const index_t no_blocks = 0; | ||
| char* arg = static_cast<char*>(group_args) + thread_id * sizeof(GroupArg); | ||
| __builtin_memcpy(arg + offsetof(GroupArg, group_karg), &karg, sizeof(karg)); |
There was a problem hiding this comment.
🔴 Nothing checks the type of the memcpy target in prepare_grouped_gemm_data (.hip:427-437). The code copies sizeof(karg) bytes of a UniversalGemmKernelArgs<> to offsetof(GroupArg, group_karg) and writes index_t values into block_start/block_end. The only static_assert checks trivially-copyable and standard-layout. The old named-field writes enforced these types; the raw copy does not. If CK changes GemmTransKernelArg's default template argument or field types, the code still compiles and writes the wrong layout. Fix: add static_assert(std::is_same_v<decltype(GroupArg::group_karg), ck_tile::UniversalGemmKernelArgs<>>), plus the same check for block_start and block_end against index_t.
| with_ck_type(mat_a.scalar_type(), [&](auto data_tag) { | ||
| constexpr amdgcn_target_id Arch = decltype(arch_tag)::value; | ||
| using DataType = decltype(data_tag); | ||
| if constexpr (GroupGemmConfigs<CkTileGroupGemmConfigs<Arch, DataType>>) { |
There was a problem hiding this comment.
🔴 A malformed config specialization becomes a runtime error, not a compile error (.hip:137, :657). The comment says "A specialization missing a name fails its static_assert", but only the four hand-written asserts at :250-253 enforce that. if constexpr (GroupGemmConfigs<CkTileGroupGemmConfigs<Arch, DataType>>) treats an undefined specialization and a defined-but-misspelled one (e.g. GradWeights) the same way. The misspelled one compiles and raises NotImplementedError at :663 for inputs the support predicate already accepted, with no fallback. Fix: test for a defined specialization separately (e.g. a completeness trait), then static_assert(GroupGemmConfigs<...>) inside the branch.
| @@ -0,0 +1,23 @@ | |||
| #pragma once | |||
There was a problem hiding this comment.
🔴 The new headers are left out of the header glob (aten/src/ATen/CMakeLists.txt:193). native_hip_h explicitly lists the native/hip/bgemm_kernels/.h subdirectory but not the new native/hip/ck_tile_group_gemm/.h, so four_wave_tail_comp_v3.h and no_split_k_epilogue.h are missing from INSTALL_HEADERS. Nothing breaks today, since only the .hip includes them. Add the glob entry to match the bgemm_kernels precedent.
| @onlyCUDA | ||
| @skipCUDAIfNotRocm | ||
| @dtypes(torch.bfloat16) | ||
| def test_grouped_gemm_ck_tile_large_stride_fallback(self, device, dtype): |
There was a problem hiding this comment.
🔴 test_grouped_gemm_ck_tile_large_stride_fallback covers only one of the new int32 guards (test_linalg.py:12229-12237). It tests a 3D mat_a with stride(-2) > int32. Nothing covers mat_b, sizes above int32, or a 2D operand's leading dimension (stride(0)), which is the case the .hip check changed by dropping the old d == 0 exemption. A size-1 2D case (e.g. shape (1, 16), strides (2**32, 1)) is cheap and would catch a gate regression. The test is also a near-copy of test_grouped_mm_large_stride_fallback (:12295-12301), which builds the same as_strided input. Parametrize that test over the backend env var, as test_grouped_gemm_rocm_backend does, rather than keeping a second copy.
| a = self._make_grouped_mm_matrix(a_shape, a_row_major, device, dtype, strided) | ||
| b = self._make_grouped_mm_matrix(b_shape, b_row_major, device, dtype, strided) | ||
| offs = None if offsets is None else torch.tensor(offsets, device=device, dtype=torch.int32) | ||
| with profile(activities=[ProfilerActivity.CUDA]) as prof: |
There was a problem hiding this comment.
🔴 test_grouped_gemm_ck_tile_config_coverage is slow and fails unhelpfully (:12258-12271). with profile(...) is opened inside the loop: 22 aligned cases x 8 layouts = 176 separate Kineto sessions, each also running the reference torch.mm and backward. The names are only unioned, so one profile around the whole loop collects the same set. Also, re.search(shape_re, name).groups() and re.search(traits_re, name).groups() raise AttributeError: 'NoneType' object has no attribute 'groups' without naming the kernel when a name doesn't match. That happens after a CK rename, for example, and the "GroupedGemmKernel" substring filter matches more than one kernel family. Check that each match is not None and include name in the failure message.
Request Simon for a real review
slayton58
left a comment
There was a problem hiding this comment.
This is the same approved PR + fixes needed for the internal build failure that caused the revert - stamping
|
@pytorchbot merge -f "unrelated CI fails, cannot unlink internal diff, suggestion from Huy to force" |
Merge startedYour change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
…p-Gemm Backend (pytorch#200640) This PR adds config structs for each input and output type and platform combination. Each config struct stores kernel configs (things like M, N, K output tile size, the MFMA M, K, N sizes, etc...) for the CK-Tile group GEMM backend. This PR builds on top of pytorch#200307 - Only configs for bf16/fp16 on the mi300 and mi350 will be added in this PR. Support for fp32 on mi300 and mi350 will be added in subsequent PRs - PR adds support for a load-cost heuristic that is used to select configs for CK-Tile - Additionally performance work was done to bring CK-Tile group gemm performance back to where it was on ROCm 7.2.0. - For more details on the 7.2.0 regression see AIPYTORCH-1471 on amd jira. - To be clear the regression was only known to happen for bf16 on the mi350. ### Linked issue or supporting maintainer Supported by @jeffdaily Also tracked internally at AMD (AIPYTORCH-1471): CK-Tile grouped GEMM lost performance on MI350 (gfx950) going from ROCm 7.2.0 to ROCm 10.1. ### Performance `F.grouped_mm` 2D x 3D over 396 MoE shapes, CK-Tile at this PR vs its merge base, and vs the default path (the per-group hipBLASLt loop); geomean speedups, median of 50, every row checked against the default path's output and gradients (measured at 9b613f0; later commits only change tests and comments): | arch | dtype | fwd vs merge base | bwd vs merge base | fwd vs default | bwd vs default | |---|---|---|---|---|---| | MI355X | bf16 | 1.21x | 1.39x | 1.06x | 0.98x | | MI355X | fp16 | 1.18x | 1.34x | 1.07x | 0.99x | | MI300X | bf16 | 1.30x | 1.02x | 1.12x | 0.85x | | MI300X | fp16 | 1.27x | 1.02x | 1.10x | 0.93x | No row is more than 4% slower than the merge base. On MI300X, backward is essentially unchanged and still trails the default path on most shapes. Pull Request resolved: pytorch#200640 Approved by: https://github.com/jeffdaily Co-authored-by: Jeff Daily <[email protected]>
This PR adds config structs for each input and output type and platform combination. Each config struct stores kernel configs (things like M, N, K output tile size, the MFMA M, K, N sizes, etc...) for the CK-Tile group GEMM backend. This PR builds on top of #200307
Linked issue or supporting maintainer
Supported by @jeffdaily
Also tracked internally at AMD (AIPYTORCH-1471): CK-Tile grouped GEMM lost performance on MI350 (gfx950) going from ROCm 7.2.0 to ROCm 10.1.
Performance
F.grouped_mm2D x 3D over 396 MoE shapes, CK-Tile at this PR vs its merge base, and vs the default path (the per-group hipBLASLt loop); geomean speedups, median of 50, every row checked against the default path's output and gradients (measured at 9b613f0; later commits only change tests and comments):No row is more than 4% slower than the merge base. On MI300X, backward is essentially unchanged and still trails the default path on most shapes.
cc @jeffdaily @sunway513 @jithunnair-amd @pruthvistony @ROCmSupport @jataylo @hongxiayang @naromero77amd @pragupta @jerrymannil @xinyazhang