Skip to content

[OPUS]bf16 opus gemm support - #2945

Merged
valarLip merged 48 commits into
mainfrom
blyu/opus_gemm
May 27, 2026
Merged

valarLip merged 48 commits into
mainfrom
blyu/opus_gemm

Conversation

@demonsan

Copy link
Copy Markdown
Contributor

Motivation

a16w16 opus gemm support.

Technical Details

1.support bf16 gemm with bf16/fp32 output and bias input.
2.performance is similar to the asm/flydsl implementations
3.current not support odd K
4.support heuristic invoke for untunned shape and csv lookup for tunned shape.

detailed info can be found in README.md

@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
ci:sglang SGLang integration tests
ci:atom ATOM benchmark (DeepSeek-R1 + GPT-OSS)
ci:vllm vLLM benchmark
ci:all All of the above

Add labels via the sidebar or gh pr edit 2945 --add-label <label>

@demonsan
demonsan marked this pull request as ready for review April 29, 2026 01:31
@demonsan
demonsan requested a review from a team April 29, 2026 01:31
@demonsan

Copy link
Copy Markdown
Contributor Author

gfx942 should be disabled. working on it...

Comment thread csrc/include/opus/hip_minimal.hpp Resolved
Comment thread csrc/include/opus/opus.hpp Resolved
@demonsan demonsan changed the title Blyu/opus gemm [OPUS]bf16 opus gemm support May 6, 2026
@demonsan
demonsan force-pushed the blyu/opus_gemm branch 6 times, most recently from d650b18 to 9e871fa Compare May 13, 2026 07:37
@demonsan
demonsan force-pushed the blyu/opus_gemm branch 2 times, most recently from 0775e5f to a0cd03d Compare May 20, 2026 11:52
@demonsan
demonsan force-pushed the blyu/opus_gemm branch 3 times, most recently from 7bf94f0 to ebe2c66 Compare May 27, 2026 05:39
blyu and others added 7 commits May 27, 2026 16:44
Signed-off-by: blyu <[email protected]>
(cherry picked from commit 0758429)
Signed-off-by: blyu <[email protected]>
(cherry picked from commit ae61819)
Signed-off-by: blyu <[email protected]>
(cherry picked from commit 224de19)
Signed-off-by: blyu <[email protected]>
(cherry picked from commit 75125b8)
Signed-off-by: binglue.lyu <[email protected]>
(cherry picked from commit 686dd51)
Signed-off-by: demonsan <[email protected]>
(cherry picked from commit 77fb359)
demonsan and others added 22 commits May 27, 2026 16:44
Module-level companion to opus-kernel-best-practice (kernel-author skill
authored by carlus). Covers JIT build wall optimization for aiter
modules bundling N opus kernel TUs + dispatcher + pybind into one .so.

Patterns documented were developed taking module_deepgemm_opus from
48.4s -> 11.1s end-to-end rebuild (-77%):

  Section 0  Diagnose Before Optimizing (4 bash recipes:
             3-trial wall, per-TU ranking, per-pass timing,
             preprocessed input size)
  Section 1  Host/Device Pass Split in Launcher Headers
             (__HIP_DEVICE_COMPILE__ + __HIPCC_RTC__ guard)
  Section 2  Fused Host TU + Per-File -D__HIPCC_RTC__
  Section 3  Torch Removal in Launchers
             (torch::Tensor -> aiter_tensor_t)
  Section 4  Dispatcher / Pybind TU Torch Removal
             (find leaking #include)
  Section 5  Flat-Array Lookup Tables
             (unordered_map<std::function> -> lower_bound)
  Section 6  Dedicated TU for Shared Sub-Kernels
  Section 7  Workspace Cache (Optional, only when section 3
             leaves a per-call hipMallocAsync)

Each section has a slow/fast code contrast (matching Carlus's skill
style), a "when NOT to apply" note where relevant, and minimum
reproducible commands.

Anti-patterns + Summary Table at the end. Includes a "Verified
ineffective on module_deepgemm_opus, current ROCm" sub-table for
common -mllvm flags so future readers don't repeat that experiment.

Scope is explicit at the top: this skill is module-level (host pass
parsing, TU count, dispatcher cost). Single-TU device-pass MCG
issues (template explosion in static_for, runtime indices into
vector_t, single-kernel SGPR spill) are routed to
opus-kernel-best-practice.

Files: .claude/skills/opus-module-build-optimization/SKILL.md  - 283 lines
Made-with: Cursor
(cherry picked from commit ff05e5d)
…_minimal.hpp

Revert the threadIdx / blockIdx / blockDim / gridDim "magic global"
replicas added to hip_minimal.hpp during the round-2 fused-host-TU
work. opus.hpp already exposes opus::thread_id_x() / opus::block_id_x()
/ opus::block_size_x() / opus::grid_size_x() etc. (one-line
__builtin_amdgcn_* wrappers) which are the canonical opus-side spelling
for these intrinsics. Reusing them avoids ABI-style tricks (`extern
const __device__ __attribute__((weak))` + __declspec(property) trick)
in hip_minimal.hpp that duplicate functionality opus.hpp already owns.

Changes:
  hip_minimal.hpp                       -66 lines: drop the four magic
                                        global structs + extern decls.
                                        Keep __forceinline__ /
                                        __noinline__ macro fallbacks
                                        (used by opus_gemm_utils.cuh
                                        and not provided by opus.hpp).
                                        Tighten attribute fallback
                                        block to a compact column-aligned
                                        format matching opus.hpp style.

  opus_gemm_pipeline_a16w16_gfx950.cuh   threadIdx.x  -> opus::thread_id_x()
  opus_gemm_pipeline_a8w8_scale.cuh      blockIdx.x   -> opus::block_id_x()
  opus_gemm_pipeline_a8w8_noscale.cuh    blockIdx.y   -> opus::block_id_y()
                                        blockIdx.z   -> opus::block_id_z()
                                        gridDim.x    -> grid_size_x() / block_size_x()
                                        (matches the spelling already
                                        used by flatmm_splitk_gfx950.cuh)

  README.md  §"What the codegen actually emits"  reflects the new
                                                hip_minimal.hpp scope.

Build wall (3-trial avg, demon_test, MAX_JOBS=102):
  before: 11.1s
  after:   9.3s   (-16% on top of the previous round)
  vs 48.4s baseline: -81%

Functional: test_opus_a16w16_tune.py:    30/30 passed
  test_opus_a16w16_lookup.py:  338/338 passed
Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 5c88ff7b078011f079121cbf6f896fcef45356f3)
Drop two opus a16w16 regression scripts that have outlived their
purpose:

* op_tests/test_opus_a16w16_lookup.py — iterated every row in the
  tuned CSV and launched via the id-based opus_gemm_a16w16_tune
  binding. The same coverage is reachable today by feeding a CSV
  through op_tests/test_opus_a16w16_gemm.py --csv_file (which goes
  through the user-facing gemm_a16w16_opus -> CSV lookup -> launcher
  path).
* op_tests/test_opus_a16w16_tune.py — per-kid smoke at
  kid-appropriate min-K. Still useful when bringing up a new kid, but
  no longer part of the standing regression set; revisit ad-hoc when
  needed.

Also remove op_tests/check_opus_splitk_graph.py (untracked HIP-graph
smoke that lived only locally) and clean up every doc / comment
reference to the three deleted files.

After this change the only opus a16w16 regression entry point is
op_tests/test_opus_a16w16_gemm.py, which:

  * supports single-shape smoke (default M=256 N=512 K=256 batch=8 or
    -m/-n/-k/-b overrides), and
  * supports CSV sweep via --csv_file (any (M, N, K, batch) shapes
    file).

Verified inside demon_test on gfx950:

  GPU_ARCHS=gfx950 python op_tests/test_opus_a16w16_gemm.py
    -> b=8 m=256 n=512 k=256 allclose passed, err=0
  GPU_ARCHS=gfx950 python op_tests/test_opus_a16w16_gemm.py \
    -m 128 -n 256 -k 1024 -b 1
    -> b=1 m=128 n=256 k=1024 allclose passed, err=0

Doc updates:

  * aiter/ops/opus/README.md §3.2 / §5 / §8 troubleshoot / §9 file map
    rewritten to reference only the gemm test.
  * csrc/opus_gemm/README.md §9 Validation rewritten.
  * csrc/opus_gemm/opus_gemm_common.py kid-211 comment redirected to
    the gemm test (drive the kid through gemm_a16w16_opus by adding
    the relevant shape to the tuned CSV).
  * op_tests/test_opus_a16w16_gemm.py module docstring updated to
    describe the post-cleanup role.

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 1f7dd2be090389ec48cbed22e9505bdd5623d8c3)
The previous arch guard raised ImportError at import time on
non-gfx950 devices. Because aiter/__init__.py imports opus inside a
broad try/except (line 84, `from .ops.opus import *`) that catches
ImportError and stops loading the rest of the block, this single
ImportError silently disabled the 30+ unrelated ops imported after
opus (aiter_operator, attention, custom, custom_all_reduce, moe_op,
moe_sorting, moe_sorting_opus, pos_encoding, cache, rmsnorm,
communication, rope, topk, topk_plain, mha, gradlib,
trans_ragged_layout, sample, fused_qk_norm_*, fused_qk_rmsnorm_*,
groupnorm, mhc, causal_conv1d, fused_split_gdr_update, mla, ...) and
ended with the misleading "ROCm/HIP JIT runtime not available"
warning. Users on a non-gfx950 box would see "import aiter" succeed
but attribute lookups fail across nearly the whole library.

Two changes fix the cascade and keep the gfx950-only enforcement at
the call site:

* aiter/ops/opus/_arch.py: split the probe into _detect_arch (never
  raises; returns (ok, detected_arch)) and a thin _check_arch wrapper
  that still raises ImportError for any caller that prefers hard
  failure. Existing detection order (GPU_ARCHS env -> rocminfo ->
  debug log + treat as unknown) is preserved.

* aiter/ops/opus/__init__.py: switch to _detect_arch. On a supported
  arch, behave exactly as before. On an unsupported / unknown arch,
  emit a single RuntimeWarning at import time and replace
  gemm_a16w16_opus / opus_gemm_a16w16_tune with stubs that raise a
  clean RuntimeError on call (RuntimeError, not ImportError, so it
  never trips the same try/except in aiter/__init__.py). The stub
  message includes the detected arch and the existing hint.

Defense in depth:

* aiter/__init__.py: wrap `from .ops.opus import *` in its own
  try/except so a hypothetical future regression in opus that *did*
  raise here would only disable opus, not silently skip every
  subsequent import.

Test side:

* op_tests/test_opus_a16w16_gemm.py: probe arch up front via
  _detect_arch (so it follows the same GPU_ARCHS env / rocminfo
  precedence as the package itself) and sys.exit(0) with a single
  "[skip] ... requires gfx950 (detected '<arch>')" line on
  unsupported devices.

Validated inside demon_test:

  1. gfx950 import + smoke: gemm_a16w16_opus is the real callable;
     test_opus_a16w16_gemm.py default smoke and -m 128 -n 256 -k 1024
     -b 1 both pass with err=0.
  2. Mocked gfx942 (mock.patch on get_gfx_runtime): import aiter
     succeeds; top-level aiter symbol count is 66, identical to the
     gfx950 run, proving the cascade is gone. opus.gemm_a16w16_opus
     is a stub; one RuntimeWarning fires at import.
  3. Calling gemm_a16w16_opus(...) on the stub raises RuntimeError
     with both the detected arch ('gfx942') and the gfx950 hint.
  4. GPU_ARCHS=gfx942 python op_tests/test_opus_a16w16_gemm.py emits
     the skip line and exits 0.

Doc updates: aiter/ops/opus/README.md constraints row and
csrc/opus_gemm/README.md "Adding a new arch" Python guard section
rewritten to describe the warn+stub semantics and the non-raising
_detect_arch helper. The in-source three-layer comment in
csrc/opus_gemm/include/gfx950/opus_gemm_traits_a16w16_gfx950.cuh is
updated to match.

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 9425f7f09e3af3aca944ca1b9c16c0a84ecae611)
Format only; no logic change.

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 6483affdd5edc87d2ab69f67f9d6162b226ec40b)
GemmTuner.py: opus as libtype="opus" alongside asm/triton/flydsl etc.
Imports kid catalog + pre-filters from opus_gemm_tune.py (not copied).

tuned_gemm.py: opus dispatch branch in gemm_a16w16() runtime path.
When tuned CSV has libtype=opus, calls opus_gemm_a16w16_tune with
the solidx/splitK from config. Lazy import; non-gfx950 falls through.

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit e21f8ee1af72c54da2ac0f19f2ac9ecc28e04aed)
…feature

Align with F.linear / GemmTuner convention. OOB bias loads are
handled by buffer rsrc num_records (hardware returns 0).

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 1506ae515a138c8700af48d65da656faecfaf411)
Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 23e5674ce5f042af8c77d62be1079b538e917e1a)
The buffer-resource num_records for g_a/g_b was sized from (m-row)*stride_a
and (n-col)*stride_b, but the base ptr was already shifted forward by
k_start = split_id * iters_full * B_K. For splits with split_id > 0 this
left the rsrc covering bytes past the real tensor end. When the input
happened to sit right before an unmapped page (caching-allocator
boundary), buffer_load on a tail iteration triggered a VM fault even
though the access is otherwise OOB-return-0 safe.

Repro (M=4, N=128, K=2880, bias=True, kid=202, splitK=2): fault address
matched inp.end exactly. Subtracting k_start*sizeof(D) from num_records
keeps the rsrc inside the allocation and removes the fault. End-to-end
sweep on gptoss_bf16_untuned_gemm.csv (57 shapes) now passes with
err_ratio=0 across the board.

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 05f0eb753a08934fab3df8ff51fe3598dc7f09cd)
Add a `HAS_OOB` template parameter (default true) to split-barrier,
splitk, and reduce kernel traits/templates. When false, `if constexpr`
strips all tail checks (mask_va_tail, store_if pred, reduce N-tail)
to produce leaner ISA for tile-aligned shapes.

Key changes:
- Traits: HAS_OOB_ added to opus_gemm_a16w16_traits_gfx950 and
  opus_flatmm_splitk_traits_gfx950.
- Split-barrier: store_c dispatches store vs store_if on HAS_OOB.
- Splitk main: mask_va_tail wrapped in if constexpr HAS_OOB.
- Reduce: HAS_OOB_ template param; OOB tail path upgraded from
  per-element scalar store to switch(valid) + ST8/ST4/ST2/ST1
  cascade (ref: gemm_mxfp_a8w8_1d1d.hpp pattern).
- Kid registry: non-OOB variants auto-generated at kid+1000 offset
  (e.g. 200->1200, 4->1004) with `_nooob` name suffix.
- Codegen: traits alias, reduce launch, forward-decl, and explicit
  instantiations all carry the 6th HAS_OOB template arg.
- Dispatcher: heuristic prefers _nooob kid when shape is tile-aligned;
  _kid_rejects_shape rejects non-OOB kids on non-aligned shapes;
  opus_gemm.cu kid range helpers extended to cover +1000 offset.
- Tuner: candidate_splitK expanded from {0,2,4,8,16,32} to [0..16]
  dense probing for finer splitK tuning.

Verified: JIT builds in 9.9s (60 a16w16 kids); 11-case correctness
test (aligned/non-aligned x OOB/non-OOB x bias) all pass vs F.linear.

Co-authored-by: Cursor <[email protected]>
- HipKittens Algorithm 1 tile mapping (W=8, C=32) for L2+LLC reuse
- CACHECTL_A/B traits params with 3 auto-generated variants per kid
- Up to +41% on large M shapes (dsv4 bf16, N=2048, K=7168)

Co-authored-by: Cursor <[email protected]>
Drop opus-private CSV (configs/opus_gemm_a16w16_tuned.csv) and autolog;
read aiter/configs/bf16_tuned_gemm.csv with libtype=='opus' filter.

Co-authored-by: Cursor <[email protected]>
gen_instances.py emits only kids hit by CSV (libtype=='opus') + sidecar
+ heuristic defaults. Sidecar at $bd_dir/compiled_kids_opus.json
survives clear_build so tuner can grow it incrementally.

Co-authored-by: Cursor <[email protected]>
Heuristic dispatch returns integer kid (resolved via tune lookup) so
subset compile drops unreferenced launchers without link errors. opus_gemm.cu propagates has_bias for bias-aware kid routing.

Co-authored-by: Cursor <[email protected]>
opus_gemm_tune.py: candidate_kids_for_shape, candidate_splitK,
kid_rejects_shape (4 GiB workspace + kspl WIP + per-pipeline),
_ensure_kids_compiled (sidecar grow + sync rebuild).
gradlib/GemmTuner.py: run_opus_gemm_bf16 with cached fp32-ref
max_delta gate (once per kid/shape, not per iter).

Co-authored-by: Cursor <[email protected]>
Port of gemm_a16w16_8wave_mouter.cc: each WG handles m_per_wg tile_m
x 1 tile_n with N-fast XCD swizzle keeping the A tile L2-resident
across 8 tile_n stripes per m_grp. Kid range [300, 316) (4 tile x 4
cpol) + nooob mirrors at [1300, 1316).

Co-authored-by: Cursor <[email protected]>
Add the mono-tile BF16 a16w16 family (5 kids, 1400..1404). Mono-tile uses a
single MMA accumulator across the full B_M x B_N tile per K iter (no
quad-subtile / no split barrier), 8 waves, MFMA 16x16x32.

The family is intrinsically non-OOB (launcher enforces tile-divisibility on
M/N/K) and does not support bias or splitK, so kids land directly in the
[1400, 1500) band with no base/nooob mirror split -- this is the first opus
family that does not follow the +1000 nooob-mirror convention.

  * Pipeline header ported from upstream yk_gcn reference (kernel body
    byte-for-byte identical; only kargs struct and helper namespace renamed
    to avoid ODR clash).
  * Traits + kargs merged into the existing
    opus_gemm_traits_a16w16_gfx950.cuh (not a separate file).
  * gen_instances.py: new TRAITS_HEADER_MAP entry + host-side validator
    (_validate_a16w16_mono_tile) mirroring the traits static_asserts.
  * opus_gemm.cu: kid-range helpers (OPUS_MONO_TILE_KID_{MIN,MAX},
    opus_kid_is_mono_tile) and bias-support gate update.
  * opus_gemm_tune.py: kid_rejects_shape early-out for non-aligned shapes
    (M%B_M / N%B_N / K%B_K / N%16).
  * opus_gemm_common.py: kernel list, NON_SPLITK_KIDS membership, and a
    comment documenting why B_K=128 tiles are excluded (LDS over budget
    until the pipeline drops B from 3-slot to 2-slot).
…aslt)

Tuned with libtype=asm,flydsl,opus,torch,skinny,triton on gfx950 (mp=4).
kimi: 40 shapes, dsv4: 350 shapes. Untuned manifests included.

Co-Authored-By: Claude Opus 4 <[email protected]>
Co-Authored-By: Claude Opus 4 <[email protected]>
CI's import-time merge raised RuntimeError on 48 duplicate rows (24 shapes
shared between kimi_bf16_tuned_gemm.csv and dsv3/dsv4/kimik2/llama70B).
For each duplicate, write the lowest-us row into the non-kimi CSV and
drop it from kimi:
  dsv3:    1 row upgraded
  dsv4:    8 rows upgraded
  kimik2:  3 rows upgraded
  llama70B:1 row upgraded
  kimi:   40 -> 16 (unique shapes only)
Row counts in non-kimi files unchanged; only contents of overlapping rows.

Co-Authored-By: Claude Opus 4 <[email protected]>
@demonsan
demonsan removed the request for review from carlushuang May 27, 2026 08:45
@valarLip
valarLip merged commit 2981058 into main May 27, 2026
37 of 38 checks passed
@valarLip
valarLip deleted the blyu/opus_gemm branch May 27, 2026 13:02
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.

3 participants