Repository navigation
[CK] [Bugfix] Make a8w8 blockscale split-K deterministic - #8541
AndreasKaratzas wants to merge 7 commits into
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
READY FOR HUMAN REVIEWPR Self-ReviewRevision Author self-review accepted. Readiness report: Author answers
Show the author's self-review answersBehavior and intentValidation and unverified scopePR-specific questionChanged op testsPR state
Copilot findings
Code and op-test hygiene
Required CI
Shadow mode reports what would block but keeps the status successful. Set |
With splitK >= 2 (KBatch = 1 << splitK >= 4) the CK and CK-Tile blockscale GEMMs add their K partials into the BF16/FP16 output with atomics, so the result depends on arrival order: on gfx950, 426 of the 436 tuned ck/cktile rows with splitK >= 2 give different bits from call to call. CK (KBatch 4, 8, 16): the last K batch to finish an output tile reduces it inside the GEMM. - Each instance also instantiates the same kernel with FP32 output. Every K batch stores its partial to its slice of a [KBatch, M, N] workspace with device-scope (sc1) stores, waits for them, and increments a per-tile counter. - The workgroup that sees count == KBatch - 1 loads the KBatch partials with device-scope loads, adds them in batch order, rounds once to BF16/FP16, and resets the counter to zero. - Device-scope loads and stores are coherent across XCDs, so no release/acquire fence (buffer_wbl2 / buffer_inv of the whole L2) is needed. - The counters live in a per-device arena (one slot per stream, zeroed once, one counter per cache line), so there is no memset and no second kernel per call. Calls that cannot use a slot (first call under stream capture, more than 16 streams or 4096 tiles) zero per-call counters in the stream. - Wave32 and pipelines other than v1/v3 keep the atomic path (no current instance). CK-Tile (KBatch > 2) writes FP32 partials to the workspace and a small kernel adds them in batch order: fusing the reduction made the CK-Tile GEMM several times slower. Both paths are gfx950 only. The dispatch checks the device arch at run time, because the host code is shared by every GPU_ARCHS target; the fused kernel body and the sc1 store specialization are also compiled for gfx950 only. On other archs (gfx942) split-K runs main's memset + atomic path, and the gfx942 ISA of every kernel main builds is unchanged. KBatch = 2 (splitK 1) keeps the atomic path, which is already deterministic: each FP32 partial is rounded to BF16/FP16 in the epilogue and atomically added into the zeroed output, so the result is round(p0 + p1) in either arrival order. The affected gfx950 tuned rows were re-measured with the new path (CK kernel ids 0-18, splitK 0/2/3/4, CUDA graph, rotating weights, 20-call bitwise check). 175 of them change to a faster config. The 3 CK-Tile rows move to CK. No other arch's rows change. The output is as accurate as splitK = 0. Co-Authored-By: Claude <[email protected]> Signed-off-by: Andreas Karatzas <[email protected]>
3aea986 to
8641ee0
Compare
Co-authored-by: Claude <[email protected]> Signed-off-by: Andreas Karatzas <[email protected]>
Picks up ROCm#8790, which refreshes the MoE dispatch golden that failed tests/test_moe_dispatch_snapshot.py on the previous head. Signed-off-by: Andreas Karatzas <[email protected]> Co-Authored-By: Claude Code <[email protected]>
The counter slot was keyed by stream, and PyTorch captures every graph on one default capture stream, so all graphs shared a slot. Replaying two of them at once on different streams left tiles unreduced (garbage output) and the counters corrupt for the rest of the process. A region now belongs to a stream or, under capture, to the capture. The regions come from 8 MB chunks that are added outside of capture as they fill up, so a capture adds no node to its graph. Signed-off-by: Andreas Karatzas <[email protected]> Co-Authored-By: Claude Code <[email protected]>
Re-timed all 452 gfx950/cu256 rows that use split-K on main (the 16 Qwen3.8-27B rows main added after the first retune included) against every repeatable CK config, and moved 18 rows to a faster one. The worst row, 80x5120x8704, goes from +9% to -18% vs main. Signed-off-by: Andreas Karatzas <[email protected]> Co-Authored-By: Claude Code <[email protected]>
A capture cannot add a chunk, and the graphs captured for one batch size can need more than the half chunk that was kept free. The rest fell back to per-call zeroed counters, 1.6 to 3.6 us slower per call. Signed-off-by: Andreas Karatzas <[email protected]> Co-Authored-By: Claude Code <[email protected]>
|
Four commits pushed on top of 3a1324c: main merged, one bug of this PR fixed, 18 rows retuned. Measured on MI355X (gfx950, 256 CUs, ROCm 10, torch 2.13) against main 1c96e23. Summary
The bug: captured graphs shared countersThe counter slot was keyed by stream. PyTorch captures every graph on one default capture stream, so every captured graph got the same slot. That is fine while graphs are replayed one after the other. Two graphs replayed at the same time on two streams corrupt each other's arrival counts.
A framework that replays one graph at a time was never affected. Main's atomic path cannot fail this way. Timing
Method
Rows still slower with this PR aloneMore than 2% slower than both main workers in both passes. The range covers both passes and both main workers.
Above +2% in one pass only: 8x256x2048, 8x2624x6144, 16x1024x6144, 16x2624x6144, 32x256x2048, 32x1536x6144, 32x5120x3072. All of them run the fused path, and no other repeatable CK config was faster on them. The reason is a fixed cost. In a build with the steps switched off one at a time, 16x1024x6144 (CK 16x64x256, Repeatability and accuracy
End to endQwen3-Next-80B-A3B-Instruct-FP8 (
Not covered
|
|
@aiter-bot review |
|
aiter-bot — queued behind 3 review(s); expect to start in about 52 min. The box reviews one PR at a time. |
aiter-bot
left a comment
There was a problem hiding this comment.
ROCm/aiter PR #8541 — [CK] [Bugfix] Make a8w8 blockscale split-K deterministic
Review (advisory, not independently refuted):
Validation (deterministic): NOT RUN — REVIEW_AUTO_VALIDATE=0 disabled the auto-run and no validation report was supplied, so the PR's own evidence (op test exit 0, 476 rows × 50 calls bitwise, 0/800 concurrent-graph replays, gfx942 ISA identical to main) is un-reproduced here
Perf (advisory): NOT RUN — REVIEW_AUTO_VALIDATE=0, so no stages.perf exists; the PR's own base-vs-head benchmark (452 rows, cold −4.4% / warm −4.3% geomean, worst row +5.4%, A/A control) is the only timing evidence
Size: 1379 lines / 12 files — over the review bar
Design (advisory): SPLIT — the natural seams: the deterministic split-K mechanism (the three csrc headers + gen_instances.py), the 189-row gfx950 retune (7 CSVs, data-only), and the op tests
Human: recommend yzhou103 review whether sc1 device-scope stores + s_waitcnt vmcnt(0) + a relaxed agent-scope atomic are a sufficient cross-XCD visibility argument for PR #8541's fused split-K reduction (the OPUS precedent is intra-XCD only), and whether the permanent 8–256 MB per-device counter arena is acceptable
📝 [verified] Every generated instance now also instantiates an FP32-output twin (gen_instances.py), growing module_gemm_a8w8_blockscale from 40 MB to 105 MB with 1376 never-launched FP32 instantiations and 784 empty fused kernels on gfx942 too, and the PR states build time was "not measured again for this revision" — every fresh JIT build on every arch pays this once. Author must measure and state the build-time delta for this revision.
3 finding(s) posted inline, on the lines they are about:
csrc/ck_gemm_a8w8_blockscale/include/gemm_a8w8_blockscale_splitk_reduce.cuh:296-304— gemm_a8w8_blockscale_splitk_reduce.cuh:296-304 orders the fused reduction on sc1 device-scope stores +…csrc/ck_gemm_a8w8_blockscale/include/gemm_a8w8_blockscale_cktile_common.cuh:445-452— The CK-Tile partials branch (gemm_a8w8_blockscale_cktile_common.cuh:445-452) takes any k_batch > 2 with no…csrc/ck_gemm_a8w8_blockscale/include/gemm_a8w8_blockscale_splitk_reduce.cuh:82-160— gemm_a8w8_blockscale_splitk_reduce.cuh:82-160 hipMallocs an 8 MB counter chunk on the first fused call that…
| __builtin_amdgcn_s_waitcnt(0x0f70); | ||
| __syncthreads(); | ||
| if(threadIdx.x == 0) | ||
| { | ||
| const uint32_t prev = | ||
| __hip_atomic_fetch_add(counter, 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); | ||
| last[0] = prev == static_cast<uint32_t>(kbatch - 1); | ||
| if(last[0]) | ||
| __hip_atomic_store(counter, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); |
There was a problem hiding this comment.
There was a problem hiding this comment.
fair, here's the basis. it's the code sequence table in LLVM AMDGPUUsage, "Memory Model GFX942" (https://llvm.org/docs/AMDGPUUsage.html#memory-model-gfx942). gfx950 gets the same sequences from the compiler, I checked both targets.
store atomic monotonic agentisglobal_store sc1=1andload atomic monotonic agentisload sc1=1. so every partial store and every reducer load uses the agent-scope atomic encoding, which is coherent across the XCD L2s.atomicrmw release agentisbuffer_wbl2 sc1+s_waitcnt vmcnt(0)+ the atomic. thebuffer_wbl2only writes back plain stores that can sit dirty in one L2. here there are none: in the gfx950 build all 784 fused kernels have only sc1 stores before the counter atomic, no plain ones.- the acquire side adds
buffer_inv sc1after the atomic, which only protects later plain loads. the reducer only does sc1 loads.
to be clear, this follows from the mapping in that table. the doc does not say "sc1 stores + vmcnt(0) are a release" in words, and at the C++ level these are relaxed atomics. if you want the language-level guarantee, the fix is __ATOMIC_ACQ_REL on the counter fetch_add (that emits exactly the buffer_wbl2 sc1 / buffer_inv sc1 pair), but that wbl2/inv fence made the kernel 30% to 5x slower when I tried it. happy to switch if a CK or compiler owner prefers that.
| if(aiter_blockscale::use_splitk_partials(k_batch)) | ||
| { | ||
| // Equal K ranges on plain B: run each batch as its own K=K/k_batch GEMM | ||
| // (k_batch=1 in the kernel, so the epilogue stores instead of adding). | ||
| // The batch index still comes from blockIdx.z. Otherwise the batches add | ||
| // into a zeroed slice, one writer per element. | ||
| const bool store_partials = !PreshuffleB && K % (k_batch * GemmInstance::K_Tile_v) == 0; | ||
| auto ws = aiter_blockscale::splitk_workspace(Y, k_batch, M, N, /*zeroed=*/!store_partials); |
There was a problem hiding this comment.
There was a problem hiding this comment.
good catch, added the same KBatch * M * N * 4 <= INT32_MAX gate on the CK-Tile partials branch. over it the call falls back to the atomic path, same as the CK side. checked 16384x8448 with splitK 2 (2.06 GB workspace): no workspace gets allocated and the output matches splitK 0.
| inline SplitKCounters splitk_counters(const torch::Tensor& Y, int64_t tiles, hipStream_t stream) | ||
| { | ||
| constexpr int64_t kMaxTiles = 4096; | ||
| constexpr int64_t kChunkTiles = 65536; // 8 MB | ||
| constexpr size_t kMaxChunks = 32; | ||
| struct Region | ||
| { | ||
| uint32_t* ptr = nullptr; | ||
| int64_t tiles = 0; | ||
| }; | ||
| struct Chunk | ||
| { | ||
| uint32_t* ptr; | ||
| int64_t used; | ||
| }; | ||
| struct Device | ||
| { | ||
| std::vector<Chunk> chunks; | ||
| // Keyed by stream handle and by capture id. | ||
| std::map<uint64_t, Region> streams; | ||
| std::map<uint64_t, Region> captures; | ||
| }; | ||
| static std::mutex mu; | ||
| static std::map<int, Device> devices; | ||
|
|
||
| hipStreamCaptureStatus capture = hipStreamCaptureStatusNone; | ||
| unsigned long long capture_id = 0; | ||
| if(hipStreamGetCaptureInfo(stream, &capture, &capture_id) != hipSuccess) | ||
| { | ||
| (void)hipGetLastError(); | ||
| } | ||
| else if(tiles <= kMaxTiles) | ||
| { | ||
| const bool capturing = capture != hipStreamCaptureStatusNone; | ||
| std::lock_guard<std::mutex> lock(mu); | ||
| Device& dev = devices[Y.get_device()]; | ||
| const int64_t reserve = dev.captures.empty() ? kChunkTiles / 2 : kChunkTiles; | ||
| if(!capturing && dev.chunks.size() < kMaxChunks && | ||
| (dev.chunks.empty() || kChunkTiles - dev.chunks.back().used < reserve)) | ||
| { | ||
| const size_t bytes = kChunkTiles * kSplitKCounterStride * sizeof(uint32_t); | ||
| void* p = nullptr; | ||
| if(hipMalloc(&p, bytes) == hipSuccess && | ||
| hipMemsetAsync(p, 0, bytes, stream) == hipSuccess && | ||
| hipStreamSynchronize(stream) == hipSuccess) | ||
| { | ||
| dev.chunks.push_back({static_cast<uint32_t*>(p), 0}); | ||
| } | ||
| else | ||
| { | ||
| (void)hipGetLastError(); | ||
| (void)hipFree(p); | ||
| } | ||
| } | ||
| auto& regions = capturing ? dev.captures : dev.streams; | ||
| const uint64_t key = capturing ? capture_id : reinterpret_cast<uintptr_t>(stream); | ||
| const auto it = regions.find(key); | ||
| if(it != regions.end() && it->second.tiles >= tiles) | ||
| return {it->second.ptr, {}}; | ||
| // A larger region replaces a smaller one, which stays reserved: launched | ||
| // kernels and captured nodes still point into it. | ||
| int64_t size = capturing ? 64 : 256; | ||
| while(size < tiles) | ||
| size *= 2; | ||
| for(Chunk& chunk : dev.chunks) | ||
| { | ||
| if(chunk.used + size <= kChunkTiles) | ||
| { | ||
| uint32_t* ptr = chunk.ptr + chunk.used * kSplitKCounterStride; | ||
| chunk.used += size; | ||
| regions[key] = {ptr, size}; | ||
| return {ptr, {}}; | ||
| } | ||
| } | ||
| } | ||
| auto holder = at::zeros({tiles * kSplitKCounterStride}, Y.options().dtype(at::kInt)); | ||
| return {reinterpret_cast<uint32_t*>(holder.data_ptr<int32_t>()), holder}; | ||
| } | ||
|
|
There was a problem hiding this comment.
📝 [verified] gemm_a8w8_blockscale_splitk_reduce.cuh:82-160 hipMallocs an 8 MB counter chunk on the first fused call that is never freed (up to 32 chunks = 256 MB per device), hipStreamSynchronize's the calling stream whenever a chunk is added, and leaves replaced regions reserved forever — a permanent device-memory cost for any process that touches the op once, disclosed in the PR but signed off by no downstream. Reviewer should ask whether vLLM/SGLang deployments accept the permanent allocation.
There was a problem hiding this comment.
yeah, fair. it's 8 MB chunks per device, at most 32 (256 MB). in practice Qwen3-Next-80B through vLLM (51 batch sizes, piecewise and full graphs) ends with 4 chunks (32 MB) and no fallback. the stream sync only runs when a chunk is added, which is never under capture and at most 32 times per device. also fixed the stale arena text in the description.
The CK-Tile partials branch allocated KBatch*M*N*4 bytes with no limit. Use the INT32_MAX bound of the CK fused path and fall back to the atomic path above it. Co-authored-by: Claude <[email protected]> Signed-off-by: Andreas Karatzas <[email protected]>
|
@yzhou103 could you take a look and sign off on this one? two things need an owner's eye:
on the SPLIT advisory: the retune was timed on the new path, so the CSVs should land with it. without them the fused path would run configs that were picked for the atomic path. happy to split out the op tests if you prefer. |
|
@aiter-bot review |
|
aiter-bot — queued behind 4 review(s); expect to start in about 36 min. The box reviews up to 4 PRs at a time. |
@zufayu — please take a look. Re-comment |
…runcated watchdog read, size the agent timeouts for the 4-lane pool (#9201) * [CI] review-bot: read WORK out of a binary fetch log, retry a stalled watchdog read, size the agent timeouts for the 4-lane pool Three failure modes from the 2026-12-04 outage (6 failed runs, 01:24-03:02): - run_one.sh extracted WORK= from the tee'd fetch log with a bare grep, so a PR with binary artifacts (OPUS .co blobs put NULs in that log) made grep answer "binary file matches" instead of the match -- a fetch that SUCCEEDED was reported as "fetch produced no WORK dir" on every retry (#8283/#7979/#7983). grep -a reads the log as text. - watchdog.py caught only HTTPError, so a 30s socket timeout crashed the watchdog with a bare TimeoutError and failed a run whose review had already published a green card (#9178). A stalled GET is now retried (3 attempts, 5s backoff); a POST is never retried, because a retried comment can land twice, and a failed POST degrades to 0, which the caller already warns about. - AITER_AGENT_TIMEOUT=2400s was sized for one review at a time; the 4-lane pool serves four through the same GLM endpoint and workers measured 25-40+ min under that load, so 2400s timed out live while the backend answered normally (#8983/#8541). Defaults now 3300s/agent and 6900s/run (115 min, still under the job's timeout-minutes of 120; check_prompts.py asserts it). watchdog_test.py gains real-socket transport checks (the retry lives below the _get/_post seam its fakes replace) with a mutation guard; _fetchfail_test.sh gains the binary-log case. selftest: 156 green / 0 red. Co-Authored-By: Claude Code <[email protected]> * watchdog: retry a truncated response body, not just a stalled read A response that dies mid-body raises http.client.IncompleteRead -- an HTTPException, not an OSError -- so the OSError-only retry net added for the 2026-12-04 stall let it escape unretried and unnamed: the same bare-traceback crash one layer up, and _post's RuntimeError guard could not degrade it either. Name the family in the catch so a truncated GET is retried like a stalled one and a truncated POST degrades to 0. Co-Authored-By: Claude Code <[email protected]> --------- Co-authored-by: zufayu <[email protected]> Co-authored-by: Claude Code <[email protected]>
|
@aiter-bot review |
|
aiter-bot — queued behind 3 review(s); expect to start in about 39 min. The box reviews up to 4 PRs at a time. |
aiter-bot
left a comment
There was a problem hiding this comment.
ROCm/aiter PR #8541 — [CK] [Bugfix] Make a8w8 blockscale split-K deterministic
Review (advisory):
Validation (deterministic): NOT RUN — REVIEW_AUTO_VALIDATE=0 and this review box has no usable GPU (/dev/kfd permission denied, all 8 GPUs at 99% use); the target op_tests/test_gemm_a8w8_blockscale.py exists and CI's Aiter Test Gate passed on head 953f740 per the PR's self-review bot — an environment gap, not a PR defect
Perf (advisory): NOT RUN — no GPU access from this review box; the PR's own 452-row base-vs-head benchmark (-4.4% geomean, 18 rows >2% slower, worst +5.4% on 48x256x2048) is the PR's claim, not an independent measurement
Size: 1381 lines / 12 files — over the review bar
Design (advisory): SPLIT — the deterministic mechanism (fused kernel, sc1 store specialization, counter arena, CK-Tile partials path) can land first on the old configs; the 189-row CSV retune and the op-test additions stack on top of it
Human: recommend yzhou103 review the sc1-coherence-without-fence decision in PR #8541 — whether the FP32 partial stores through the specialized amd_buffer_store (sc1) plus s_waitcnt vmcnt(0) before a relaxed agent-scope counter RMW is a safe cross-XCD ordering on gfx950 without a release/acquire pair, and who owns that invariant if CK changes amd_buffer_store's store widths
4 finding(s) posted inline, on the lines they are about:
csrc/ck_gemm_a8w8_blockscale/include/gemm_a8w8_blockscale_common.cuh:173-191— gemm_a8w8_blockscale_common.cuh:173-191 specializes only amd_buffer_store<float, {1,2,4,8}, DefaultCoherence>…csrc/ck_gemm_a8w8_blockscale/include/gemm_a8w8_blockscale_cktile_common.cuh:453— All four cktile cases in op_tests/test_gemm_a8w8_blockscale.py use K=3072 with splitK 2/3, which the K %…csrc/ck_gemm_a8w8_blockscale/include/gemm_a8w8_blockscale_splitk_reduce.cuh:309-314— gemm_a8w8_blockscale_splitk_reduce.cuh:309-314 ends splitk_tile_fixup with a bareelsethat assumes…csrc/ck_gemm_a8w8_blockscale/gen_instances.py:121— gen_instances.py:121 instantiates the FP32-output twin for every CK instance unconditionally, so gfx942 and…
| #define AITER_SPLITK_COHERENT_FLOAT_STORE(N) \ | ||
| template <> \ | ||
| __device__ void amd_buffer_store<float, N, AmdBufferCoherenceEnum::DefaultCoherence>( \ | ||
| const typename vector_type_maker<float, N>::type::type src_thread_data, \ | ||
| float* p_dst_wave, \ | ||
| const index_t dst_thread_element_offset, \ | ||
| const bool dst_thread_element_valid, \ | ||
| const index_t dst_element_space_size) \ | ||
| { \ | ||
| amd_buffer_store<float, N, kSplitKStoreCoherence>(src_thread_data, \ | ||
| p_dst_wave, \ | ||
| dst_thread_element_offset, \ | ||
| dst_thread_element_valid, \ | ||
| dst_element_space_size); \ | ||
| } | ||
| AITER_SPLITK_COHERENT_FLOAT_STORE(1) | ||
| AITER_SPLITK_COHERENT_FLOAT_STORE(2) | ||
| AITER_SPLITK_COHERENT_FLOAT_STORE(4) | ||
| AITER_SPLITK_COHERENT_FLOAT_STORE(8) |
There was a problem hiding this comment.
| // (k_batch=1 in the kernel, so the epilogue stores instead of adding). | ||
| // The batch index still comes from blockIdx.z. Otherwise the batches add | ||
| // into a zeroed slice, one writer per element. | ||
| const bool store_partials = !PreshuffleB && K % (k_batch * GemmInstance::K_Tile_v) == 0; |
There was a problem hiding this comment.
| if(kbatch == 4) | ||
| splitk_sum_tile<4, TileM, TileN, BlockSize, IsBF16>(ws, out, ldo, M, N, m0, n0); | ||
| else if(kbatch == 8) | ||
| splitk_sum_tile<8, TileM, TileN, BlockSize, IsBF16>(ws, out, ldo, M, N, m0, n0); | ||
| else | ||
| splitk_sum_tile<16, TileM, TileN, BlockSize, IsBF16>(ws, out, ldo, M, N, m0, n0); |
There was a problem hiding this comment.
📝 [verified] gemm_a8w8_blockscale_splitk_reduce.cuh:309-314 ends splitk_tile_fixup with a bare else that assumes kbatch==16 — extending use_splitk_fused to any other KBatch (e.g. 32, which the 2 GB workspace gate admits at small M,N) would make the last workgroup sum only 16 of 32 slices: wrong output, no error; the CK-Tile reduce kernel handles the same default explicitly at runtime. Author must make it else if(kbatch == 16) with an assert on the unreachable values.
| ck::BlockGemmPipelineScheduler::{k.PIPELINE_Sched}, | ||
| {instance_params}>; | ||
| // The same kernel with FP32 output, for the deterministic split-K partials. | ||
| using PartialsGemmInstance = DeviceLegacyGemmHelperF8BlockScale< |
There was a problem hiding this comment.
📝 [verified] gen_instances.py:121 instantiates the FP32-output twin for every CK instance unconditionally, so gfx942 and every non-gfx950 arch compile 1376 never-launched instantiations — the PR measures +31% JIT build time (66.8s → 87.2s) and .so size 40 MB → 105 MB on archs that keep the nondeterministic path. Author must either guard the PartialsGemmInstance instantiation with gfx950 (the PartialsInstance=void default already supports it) or confirm the build-cost regression on gfx942 is accepted.
Summary
On gfx950, tuned CK and CK-Tile
gemm_a8w8_blockscalerows withsplitK >= 2(KBatch4 or 8) add their K partials into the BF16/FP16 output with atomics, so the output bits change from call to call. With this PR those rows return the same bits on every call and are as accurate assplitK = 0.Benchmark on MI355X, all 452 affected rows: -4.4% geomean vs main (cold activations; -4.3% warm), one row above +5% (+5.4%). Relative error vs FP64: 0.0017 median here, 0.0032 on main.
Motivation
vLLM's
AiterFp8BlockScaledMMKernel(w8a8, per-token-group-128 activations, 128x128 weight blocks) callsaiter.gemm_a8w8_blockscaleon gfx950. For decode-sized M the tuned rows pickck/cktilewithsplitK2 or 3, so 4 or 8 partials are atomically added into the BF16 output, and the rounding depends on arrival order. This showed up as run-to-run and graph-vs-eager differences when serving Hy4 / Hy4-Flash FP8 in vLLM.layers.1.self_attn.linear_gateweights (N=8192, K=3072) the same input differs on 20 of 20 calls, by up to 0.094 abs at M=6. 36 of 50 Hy4-flash (shape, M) cases are nondeterministic.splitK = 0at the median, 3.0x at worst, because the BF16 atomic adds round several times.Why this revision is different from the first one
The first revision of this PR wrote FP32 partials and launched a separate reduce kernel. It was deterministic but cost +7.2% geomean (382 rows above +3%, worst +21.5%). This revision replaces it with a fused last-arriving-workgroup reduction for CK and retunes the affected rows on the new path.
KBatch = 2(splitK = 1) is left alone: it is already deterministic (see Changes). An earlier version of this description said otherwise; that was wrong.Changes
gemm_a8w8_blockscale_common.cuh,gen_instances.py(CK). Every instance also instantiates the same kernel with FP32 output. ForKBatch4, 8 or 16,kernel_gemm_blockscale_splitk_fused:blockIdx.zof a[KBatch, M, N]FP32 workspace;s_waitcnt vmcnt(0)) and increments a per-tile counter;KBatch - 1loads the partials, adds them in batch order, rounds once to BF16/FP16, and resets the counter to 0.Kernel selection follows the device op (v1/v3 pipeline, tail number, min occupancy). Wave32, other pipelines (no current instance) or a workspace over 2 GB fall back to the atomic path.
Coherence without a fence: the
sc1store specialization. Partial stores and the reducer's loads are device-scope (sc1), which keeps them coherent across XCDs. A release/acquire fence (buffer_wbl2/buffer_invof the whole L2) made the kernel 30% to 5x slower. CK has no per-call coherence knob on its epilogue store, so the header adds an explicit specialization ofck::amd_buffer_store<float, N, DefaultCoherence>that emitsDEVICE_NT0(sc1). Constraints:__gfx950__; in those TUs the FP32 partials are the only float global stores.sc1(the relaxed agent-scope atomic encoding) pluss_waitcnt vmcnt(0)before the counter increment, not on a C++ release/acquire pair. Without it, M=2000 N=128 gives relerr 0.8.store atomic monotonic agentisstore sc1=1andload atomic monotonic agentisload sc1=1.atomicrmw release agentisbuffer_wbl2 sc1+s_waitcnt vmcnt(0)+ the atomic, andbuffer_wbl2 sc1is there to write back plain stores. In the gfx950 build, all 784 fused kernels have onlysc1stores before the counter atomic and onlysc1loads after it. The table does not state this shortcut as a rule; it follows from the mapping.__ATOMIC_ACQ_RELon the counter is the language-level alternative (it emitsbuffer_wbl2 sc1/buffer_inv sc1).amd_buffer_store's signature would break the specialization at compile time, not silently.Counter arena (
gemm_a8w8_blockscale_splitk_reduce.cuh, new). Per device, 8 MB chunks (65536 counters each, one counter per 128-byte line), at most 32 chunks (256 MB). The reducer resets each counter, so a chunk is zeroed only once.hipStreamGetCaptureInfo). So concurrent launches and concurrently replayed graphs never share counters.hipMalloc,hipMemsetAsync, thenhipStreamSynchronizeof the calling stream), when less than half a chunk is free, or less than a whole chunk once the device has captured. They are never freed, because captured graphs keep pointers into them.[KBatch, M, N]FP32 per call).gemm_a8w8_blockscale_cktile_common.cuh(CK-Tile,KBatch > 2). FP32 partials plus a separate reduce kernel, because fusing the reduction made the CK-Tile GEMM 2.5-4x slower. With plain B andK % (KBatch * K_Tile) == 0each batch runs as aK / KBatchGEMM withk_batch = 1(plain stores); otherwise each batch adds into its own zeroed slice, so every element has one writer. A workspace over 2 GB (KBatch * M * N * 4 > INT32_MAX) falls back to the atomic path, the same bound as the CK fused path.gfx950 gating.
use_splitk_fused/use_splitk_partialsalso requireget_device_gfx() == "gfx950"(cached per device, evaluated only after theKBatchtest). The check is at run time because a JIT module's host code is shared by everyGPU_ARCHStarget, so only a runtime check can choose workspace vs memset and which kernel to launch. The fused kernel body and thesc1specialization are additionally compiled only under__gfx950__; the same exact name is used on both sides, so no arch can pass the dispatch check and launch an empty kernel.Tuned CSVs (
a8w8_blockscale_tuned_gemm.csvand 6model_configs/*files): 189 gfx950/cu256 rows differ from main. 167 change config (libtype,kernelId,splitK,kernelName); 22 keep it and only get newus/tflops/bwvalues. The first retune changed 175 rows; c3be5b8 moved 18 more rows (4 of them already in the 175) to a faster config. Candidates were CK ids 0-18 xsplitK{0,2,3,4}, timed on the new path (CUDA graph, rotating weights), checked bitwise over 20 calls, relerr within 1.02x ofsplitK = 0. A row changes only if the new config is at least 3% faster than its current one on the new path, or if the current one was more than 2% slower than main and the new one at least 1% faster. The 3 CK-Tile rows move to CK. gfx942 rows are byte-identical to main.op_tests/test_gemm_a8w8_blockscale.py:test_splitk_deterministic(see "Changed op tests").Why
KBatch = 2is already deterministic. CK'sRunMultiDEpilogueconverts the FP32 C-shuffle throughPassThroughtoEDataTypebeforeAtomicAdd(global_atomic_pk_add_bf16), and CK-Tile callscast_tile<ODataType>before the atomicupdate_tile. The output is zeroed first. So the result isr(0 + r(p0)) = r(p0)thenr(r(p0) + r(p1)), which is the same in either order. With three or more partials the intermediate roundings depend on order, which is whyKBatch >= 4needed the fix. Measured: 1000 calls x 5 cases (4 tuned CKsplitK = 1rows and the CK-Tile 32x128 kernel; adversarial cancelling K halves; concurrent GEMM on a side stream): 0/5000 mismatches on main and here, and every element equalsbf16(bf16(p0) + bf16(p1)). The same harness withsplitK = 2on main differs on 1000/1000 calls.Performance (if applicable)
MI355X (gfx950, 256 CUs), BF16 out,
aiter.gemm_a8w8_blockscalewith each tree's shipped CSVs, against main 1c96e23.All 452 affected gfx950 rows (every gfx950/cu256 row with
splitK >= 2on main, including the 16 Qwen3.8-27B rows of #8016), change vs main:splitK = 1rows +0.14% / -0.08% (cold / warm), 53 other tuned rows +0.05% / +0.05%.Method.
Rows still slower (more than 2% slower than both main workers in both passes; the range covers both passes and both main workers):
Above +2% in one pass only: 8x256x2048, 8x2624x6144, 16x1024x6144, 16x2624x6144, 32x256x2048, 32x1536x6144, 32x5120x3072. All of these rows run the fused path, and no other repeatable CK config was faster on them. #8609 moves 8 of the 13 to slice-K kernels.
Where the fused path spends its time. 16x1024x6144, CK 16x64x256,
splitK = 3, in a build with the steps switched off one at a time: 4.70 us when the kernel stops after the partial stores; +0.08 us for waiting for the stores; +0.57 us for the arrival counter; +1.08 us for loading, adding and storing the 8 partials. Total 6.43 us, against 6.16 us for main's memset and atomic adds. Letting only the first wave reduce was 14% to 26% slower on five such rows.Build time. Fresh JIT build of
module_gemm_a8w8_blockscale(empty build dir,GPU_ARCHS=gfx950,AITER_MAX_JOBS=64, same CK checkout, 43 TUs in both trees), main 1c96e23 vs this head, 3 runs each in the order main, head, head, main, main, head:.sosizeThe extra cost is the FP32-output instantiations. The host was shared with other jobs (load average 33 to 95 during the runs). gfx942 was not timed.
Testing
Documentation
No API, flag or env change. The same calls now return reproducible results on gfx950, and the tuned CSVs pick different kernels for 167 gfx950 rows.
Dependencies
Breaking Changes
None in the API. On gfx950, output bits change for
splitK >= 2rows (now rounded once from an FP32 sum) and for the 167 rows that change config. New resources on gfx950: split-K counters in 8 MB per-device chunks (at most 32, 256 MB), allocated outside of capture and never freed, and a per-call[KBatch, M, N]FP32 workspace from the caching allocator (at most 2 GB, else the atomic path).PR Self-Review
Reviewed revision
953f740b8c0e2844036da15a9d7cd4d0fe3b5b32Behavior and intent
On gfx950, CK blockscale GEMMs with 4, 8 or 16 K batches (wave64, v1/v3 pipelines) return the same bits for the same inputs: the last K batch of each tile adds the FP32 partials in K order and rounds once. CK-Tile with more than 2 K batches gets the same result through FP32 partials and a reduce kernel.
KBatch1 and 2 are unchanged (KBatch = 2is already deterministic). Every other arch runs main's code path. The affected gfx950 tuned rows were re-measured on the new path and 167 changed config, so the fix costs nothing overall.Validation and unverified scope
MI350X (gfx950, 256 CUs), base main adbb6ac, fresh JIT builds (module
.sofiles and build dirs deleted),GPU_ARCHS=gfx950.python3 op_tests/test_gemm_a8w8_blockscale.pyexits 0; all 9test_splitk_deterministiccases reportmismatching calls=0/20, err=0. On main the test fails at the first case (20/20 calls differ).aiter.gemm_a8w8_blockscalewith this branch's CSVs: 50 eager calls bitwise, plus CUDA-graph capture and 10 replays compared with eager: 0 nondeterministic rows, 0 graph-vs-eager mismatches, relerr 1.000xsplitK = 0(FP64 reference) on every row.splitK2/3/4, 50 calls: 0 mismatches, relerr equal tosplitK = 0. CK-Tile with preshuffled B: 0/30 mismatches.KBatch = 2adversarial test: see Changes (0/5000 here and on main; positive control 1000/1000).GPU_ARCHS=gfx942JIT builds ofmodule_gemm_a8w8_blockscaleandmodule_gemm_a8w8_blockscale_cktilesucceed. Per-kernel disassembly vs a gfx942 build of main: all 2753 CK and 5121 CK-Tile kernels of main are present with identical ISA. Extra kernels on gfx942: 784 fused kernels (s_endpgmonly), 1376 never-launched FP32-output CK instantiations, and the CK-Tile partials/reduce kernels, which the runtime check never launches.splitK = 2: at 8192x8192x1024 the call allocates the 1 GB workspace; at 16384x8448x1024 (2.06 GB) it allocates none and matchessplitK = 0. Passed 10 of 10 runs, together with 10 of 10 runs of the op test.git clang-formatclean on the changed C++ lines;black --checkandruff checkclean.model_configs/a8w8_blockscale_tuned_gemm_qwen38_27b.csv([Config] Add Qwen3.8-27B FP8 a8w8 blockscale GEMM tunings for gfx950 #8016). It has 16 gfx950 CK rows withsplitK >= 2. They now run the fused path. c3be5b8 re-timed them on it and moved 5 of them to a faster config.GPU_ARCHS=gfx942JIT builds:python op_tests/test_gemm_a8w8_blockscale.py -m 1 2 4 8 16 32 64 128 --ck_preshuffle Falseexits 0 in 10 of 10 runs (ck and asm err 0 on every shape). The determinism checks are gfx950 only. In 3 of 10 runs,test_splitk_correctness(m=4, n=512, k=16384, splitK=2)warns: 1 of 2048 outputs differs fromsplitK = 0by 0.125. This is main's atomic path, which gfx942 keeps.Unverified:
splitK >= 2rows stay nondeterministic, as on main; a gfx942 port of the fused path and retune is a follow-up.__gfx950__guard are extended.PR-specific question
KBatch4/8/16 partials are no longer added atomically into BF16/FP16 in arrival order; they are stored as FP32 and reduced in K order by the last workgroup of each tile. CK-TileKBatch > 2gets the same through a reduce kernel. 167 gfx950 rows change config. The atomic path made outputs differ between identical calls and between eager and CUDA-graph replay (431/436 rows; vLLM Hy4 serving affected), with 1.9-3.0x the error ofsplitK = 0. ClampingsplitK <= 1([Bug] Make blockscale split-K deterministic #4581) is deterministic but +26.6% geomean with 1.48x error; the first revision's separate reduce kernel was +7.2%.get_device_gfx() == "gfx950") andKBatchin {4, 8, 16} and wave64 andKBatch * M * N * 4 <= INT32_MAXand a v1/v3 kernel selection; output BF16/FP16 (the only generatedEDataTypes);Y.stride(-1) == 1(TORCH_CHECK).KBatch > 2andKBatch * M * N * 4 <= INT32_MAX.KBatch1/2/>=32, wave32, other pipelines, huge workspace) runs main'sGemmInstanceinvoker, which still checksIsSupportedArgument.__gfx950__device guard use the same exact name, so no arch reaches an empty kernel; theKBatchtest comes first, soKBatch1/2 never query the arch. CSV changes are confined togfx950,256rows that hadsplitK >= 2.module_gemm_a8w8_blockscale_bpreshuffle_cktileincludes the CK-Tile header and gets the same gate; all its tuned rows usesplitK = 0.op_tests/test_gemm_a8w8_blockscale.pyaddstest_splitk_deterministic; see below.Changed op tests
op_tests/test_gemm_a8w8_blockscale.pyaddstest_splitk_deterministic, run on gfx950:splitK = 0: CK v1 16x64x256, 16x128x256, 16x64x128 and CK v3 128x128 (fused path); CK-Tile 4-wave 32x128 and 8-wave 192x256 (partials path);splitK2/3.test_splitk_correctnesschecks only closeness with default kernels, where the race does not show up even on main. The new test fails on main (20/20 calls differ). Kernels are named rather than taken from the CSV so the CK-Tile path stays covered now that no tuned gfx950 row selects it.Related
splitKto <= 1: deterministic, but its rows are 1.26-2.05x slower than main on the M=1 rows here, and asplitK <= 1retune is +26.6% geomean with 1.48x the error.Duplicate work
This updates PR #8541 itself; no other PR is opened for the same fix.
AI assistance (Claude) wrote this change, the retune and this description, and ran the tests and measurements above on MI350X. A human has not yet reviewed every changed line.