Skip to content

fix(nf12): split-K geometry and HIP review fixes - #3676

Merged
Qubitium merged 4 commits into
mainfrom
feat/nf12-hip-splitk-review-fixes
Nov 9, 2026
Merged

Qubitium merged 4 commits into
mainfrom
feat/nf12-hip-splitk-review-fixes

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator

Supersedes #3669: the same split-K geometry and per-device capability commit,
rebased onto current main, plus every fix from the review of 08cf3857b.

Four commits: the split-K sync, the activation-layout fix, the vendored kernel
fixes, and the ROCm inventory fix.

Review findings resolved

Finding (severity) Fix
Module lost leading dimensions: [2,8,256] returned [16,256] (P1) Every return is out.reshape(out_sizes) / dense.reshape(out_sizes)
Direct op ignored activation strides: padded M=16 gave 3562/4096 out-of-tolerance elements (P1) x2 = x.contiguous().reshape({m, k}) at entry; all routes use x2
Routed WMMA read the unspecified gather tail (P1) Clamp to the expert's valid interval row_base + m
Unsupported WMMA targets launched an empty kernel (P1) Both weight sources gate on the cached per-device capability
Native encoder ignored workspace_bytes (P1) Validated before any memset/launch
grouped_operands copied with a null gather (P1) Returns after publishing the group ends
Launch status consumed by hipGetLastError() (P2) Read once into a variable
BF16 twin could not validate the split plan (P2) Twin runs the identical (tiles, splits, m_blocks) plan
NF12ADLinear missing from ROCM_KERNELS (7 test failures) Added

New dispatch flow

flowchart TD
    A["linear_dispatch receives x of any shape"] --> B["k = x.size(-1), m = x.numel() / k"]
    B --> C["x2 = x.contiguous().reshape({m, k})"]
    C --> D["out_sizes = x.sizes(); out_sizes.back() = n"]
    D --> E{"m < 16 and nf12_ad_linear_fused_small_m_supported(m)?"}
    E -- Yes --> F["nf12_ad_linear_fused on x2"]
    F --> F1["return out.reshape(out_sizes)"]
    E -- No --> G{"nf12_ad_wmma_supported(m)?"}
    G -- Yes --> H["nf12_ad_linear_wmma on x2 with caller-sized workspace"]
    H --> H1["return out.reshape(out_sizes)"]
    G -- No --> I["decode_dispatch per row slice"]
    I --> J["at::matmul / at::addmm on x2"]
    J --> K["cat slices, then return dense.reshape(out_sizes)"]
    classDef entry fill:#e8f0ff,stroke:#003f8a,color:#111;
    class C,D entry;
Loading

Failure path: an unsupported shape (n % 16 != 0, k % 64 != 0, packed
not contiguous) still raises TORCH_CHECK before any launch, so the
normalization never turns a rejection into a wrong answer. The raw C ABI keeps
rejecting a padded ldx explicitly; only the torch op normalizes.

Before / after

Mechanism Before Current
Fused small-M eligibility Required x.dim() == 2 && x.is_contiguous() (08cf3857b:gptqmodel_ext/nf12_hip/nf12_ad_torch.cpp:214) Uses only m, after x2 = x.contiguous().reshape({m, k}) (...:218-221)
Kernel input pointer x.data_ptr() (08cf3857b:...:240, :290) x2.data_ptr() (...:246, :296)
GEMM operand at::matmul(x, ...) (08cf3857b:...:338) at::matmul(x2, ...) (...:339-341)
Output shape [m, n] (08cf3857b:...:245, :296, :338) reshape(out_sizes) (...:251, :302, :345)
WMMA routed tail max_assignments - 1 (nf12_ad_wmma.hip:193) row_base + m - 1
BF16 twin plan Fixed eight tiles, one K pass (nf12_ad_wmma.hip:593) Same plan as nf12; bitwise equal
Encode workspace Discarded (nf12_ad_encode.hip:257, :306) Validated
No-gather operands Copied (nf12_ad_moe.hip:343) Returns after the ends
Launch status hipGetLastError() in the condition (nf12_ad_moe.hip:436) Read once
ROCm inventory NF12ADLinear missing Added

Measured results

R9700 (gfx1201), PYTHON_GIL=0.

Check Before After
Padded activation, M=16 vs F.linear 3562/4096 out of tolerance 0 violations
Padded activation, M=64 15021/16384 out of tolerance 0 violations
3-D [2, 8, 256] [16, 256] [2, 8, 256]
3-D [2, 32, 256] [64, 256] [2, 32, 256]
nf12 + ROCm suites 7 failed 636 passed, 1 skipped
Accuracy, canonical cells 0 violations 0 violations (unchanged)
Distinct-stream workspace test pass pass

Kernel performance is unchanged by the layout fix (it normalizes once per
call). The vendored split rule matches dphnAI/nf12 exactly.

Documentation

docs/nf12-hip-device-workspace.md gains the flow diagram and the before/after
table; README.md links it as the activation-layout reference.

Three fixes from dphnAI/nf12 that the vendored RDNA4 kernels had not picked up.
Only the HIP sources change; the torch binding and the C ABI are untouched.

1. pick_splits split K four ways on any shape with at least 128 column blocks,
   which includes launches already 6-7 waves deep. There the FP32 partial plane
   (7-28 MB written and read again) costs more than the extra CTAs buy. A/B on
   gfx1201, same binary otherwise:

     4096x28672  m=16  333.6 -> 310.2  (-7.0%)
     4096x28672  m=32  362.4 -> 321.7  (-11.2%)
     4096x28672  m=64  417.2 -> 317.9  (-23.8%)
     5120x25600  m=16  363.3 -> 375.8  (+3.4%)
     5120x25600  m=32  388.1 -> 382.0  (-1.6%)
     5120x25600  m=64  433.9 -> 385.2  (-11.2%)

   Against dense BF16, 4096x28672 m=64 goes 0.96x -> 1.28x and 5120x25600 m=64
   1.04x -> 1.21x, so neither is below parity at m=16/32/64 any more. One cell
   loses 3.4% and still runs at 1.15x. 8192x57344 keeps its two-way split: it is
   14 waves deep but the split still wins there at m=128.

   Those shapes now need no split-K scratch: seven of the forty benchmark cells
   split K, down from thirteen.

2. wmma_available() cached one process-wide bool captured from whichever device
   was current on the first call. On a host exposing both gfx1201 and gfx1250
   the second device inherits the first one's answer and is sent down a
   matrix-core route it cannot run. Cached per device index now, with an atomic
   slot so concurrent host threads stay safe.

3. The HIP entry points only checked n % 16. A k that is not a multiple of 64
   was truncated by k / kSuperAtomCols, so encoding a 256x96 weight produced a
   matrix covering 64 of the caller's 96 columns and the GEMM then read back as
   garbage. encode_analyze/encode/decode/unpack_bf16t/linear_fused/linear_wmma
   now reject the same bad geometry the torch binding already rejects.

Verified on R9700 (gfx1201): nf12 suites 240 passed, 1 skipped; workspace query
now returns 0 for both wide shapes; 4096x28672 m=64 measures 1.28x BF16.
The 6 test_rocm_kernel_contracts::test_rocm_device_contract[NF12ADLinear]
failures are pre-existing on upstream/main and unrelated (they assert
SUPPORTS_DEVICES against the ROCM_KERNELS list).
`linear_dispatch` indexed rows of a contiguous `[m, k]` matrix on every
route but only checked that layout for the fused small-M branch. A 3-D
activation therefore lost its leading dimensions (`[2, 8, 256]` came back as
`[16, 256]`), and a sliced activation (`storage[:m, :k]` of a wider
allocation) silently read the wrong rows: at M=16 the direct op produced
3562/4096 out-of-tolerance elements.

Normalize once at entry (`x2 = x.contiguous().reshape({m, k})`), use `x2` for
the fused kernel, the WMMA kernel and the GEMM operand, and reshape every
return to `x.sizes()` with the last dimension replaced by N. The route
decision no longer requires a 2-D contiguous input, so a legal torch layout
takes the same fast path as a contiguous one.

Documented in `docs/nf12-hip-device-workspace.md` with the new flow and a
before/after table. New tests cover the 3-D round trip, a padded row slice
against `F.linear`, and the `NF12ADLinear` module shape.
Mirrors the RDNA4 kernel fixes from dphnAI/nf12:

* routed WMMA clamps a tail tile to the expert's valid row interval, not the
  gather allocation capacity (SPEC 9.2 leaves the dropped tail unspecified)
* the bf16t twin runs the same `(tiles, splits, m_blocks)` plan as the nf12
  route, so SPEC 6.2 equality is bitwise rather than tolerance-close
* both weight sources gate on the cached per-device WMMA capability
* `nf12_ad_encode*` validates `workspace_bytes` before any device write
* `moe_grouped_operands` returns after publishing the ends when `gather` is
  null, and the launch status is read once
* `pick_splits` keeps four splits only for mid-length K on a wide grid
  (5120x25600 m=16) and one split for m>=128 when the grid already fills a
  wave
The class ships a ROCm kernel but was missing from `ROCM_KERNELS`, which
failed the coverage test plus six device-contract cases (7 failures).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant