Skip to content

[OPUS]fix opus_gemm mono version m align assert error - #3382

Merged
valarLip merged 50 commits into
mainfrom
blyu/opus_gemm
May 28, 2026
Merged

valarLip merged 50 commits into
mainfrom
blyu/opus_gemm

Conversation

@demonsan

Copy link
Copy Markdown
Contributor

Release the restriction of opus_gemm mono kernel. Now only N and K should be aligned due to performance issue.

@demonsan
demonsan requested a review from a team May 28, 2026 03:49
@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: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 3382 --add-label <label>

blyu and others added 28 commits May 27, 2026 23:45
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)
Signed-off-by: demonsan <[email protected]>
(cherry picked from commit f549720)
Introduces the shape-driven user API gemm_a16w16_opus. Internals:
- Private tuned CSV lookup via aiter/ops/opus/common.py (lru_cache).
- Optional AITER_OPUS_LOG_UNTUNED=1 writes misses to opus-private
  untuned CSV (schema matches gptoss_bf16_untuned_gemm.csv so the
  tuner can feed on it directly).
- Explicit kernelId= stays available for tuner / debug / solMap
  integrations but is no longer the primary user surface.
- New op_tests/test_opus_a16w16_lookup.py iterates the tuned CSV and
  verifies each (solidx, splitK) launches correctly (212/212 PASS).
Opus env is self-contained: AITER_OPUS_A16W16_TUNED_CSV /
AITER_OPUS_A16W16_UNTUNED_CSV / AITER_OPUS_LOG_UNTUNED. No change to
aiter/jit/core.py's AITER_CONFIGS (reserved for aiter-global config).

(cherry picked from commit a019d1e)
Mirrors the two-level pattern already used by csrc/ck_gemm_a8w8/gemm_a8w8.cu:
- gen_instances.py --tune_file bakes opus_gemm_a16w16_tuned.csv entries
  into opus_gemm_lookup.h at JIT time. Two per-CTYPE macros
  (GENERATE_OPUS_LOOKUP_TABLE_BF16 / _FP32) because splitk kids are
  only emitted as <fp32_t>; BF16 map still contains splitk entries but
  instantiates splitk<fp32_t> (reduce kernel casts Y to bf16 at
  runtime). FP32 map omits splitk entirely (launcher requires bf16 Y).
- opus_gemm.cu: opus_dispatch_a16w16<CDataType> first queries the
  lookup map, then falls through to opus_a16w16_heuristic_dispatch
  if-else tree. Heuristic picks splitk kids for M<=128 (splitk's
  host-side auto-clamp makes it alignment-tolerant) and traditional
  a16w16 tile 9 for large aligned shapes.
CSV edits require AITER_REBUILD=1 to propagate into the C++ lookup.
Python-side lookup (aiter/ops/opus/common.py, previous commit) remains
the dynamic path for shape-driven user API.

(cherry picked from commit e9c5901)
…surface

Removes aiter.ops.opus.deepgemm — the legacy aggregate
deepgemm_opus entry is gone. Each opus dtype family now owns its own
Python entry module; a16w16 lives in aiter.ops.opus.gemm_op_a16w16 and
holds its own private bf16 fallback binding (_opus_gemm_bf16_dispatch)
for the gemm_a16w16_opus CSV-miss path. The legacy shim
aiter.ops.deepgemm also drops the deepgemm_opus re-export; its
top-level deepgemm() selector keeps honoring AITER_DEEPGEMM_BACKEND=opus
via a private internal binding.
Renames op_tests/test_opus_deepgemm.py to test_opus_a16w16_gemm.py and
rewrites it to exercise gemm_a16w16_opus (drops a8w8 / a8w8_scale
branches which tested the old aggregate entry; those dtypes get their
own tests when their opus Python modules land).

(cherry picked from commit 1e94e84)
Single comprehensive README at aiter/ops/opus/README.md
covering Quick Start, dispatch architecture (Python lookup + C++
two-level fallback), tuning workflow, API reference, testing,
environment variables, internals, and troubleshooting.
csrc/opus_gemm/README.md is a stub pointing here.

(cherry picked from commit 8792254)
Signed-off-by: demonsan <[email protected]>
(cherry picked from commit 47566ca)
Make output dtype a first-class axis across the opus a16w16 pipeline so
the same (M, N, K) can pick a different kernel for bf16 vs fp32 Y.

Reduce kernel
- Split splitk_reduce_kernel<VEC, BLOCK, D_OUT> out of the a16w16 splitk
  pipeline header into the new include/pipeline/splitk_reduce.cuh; the
  reduce kernel is now templated on D_OUT (default __bf16) and uses
  STEP = 16 / sizeof(D_OUT) so bf16 keeps its 2x dwordx4 fast path while
  fp32 is 4x dwordx4 (Option C). Tail / N-edge handling unchanged.

Heuristic dispatch
- Extract opus_a16w16_heuristic_dispatch<CDataType> + the
  OpusA16W16NoscaleKernel typedef into the new
  include/opus_gemm_heuristic_dispatch.cuh and merge the bf16/fp32
  specializations into a single template body now that splitk works for
  both Y dtypes.

Codegen
- _gen_flatmm_splitk_instance picks the reduce kernel D_OUT at launch
  time based on Y.dtype() (bf16 or fp32) and accepts both via
  TORCH_CHECK; main kernel D_C is still locked to fp32_t (workspace).
- get_tune_dict keys winners on (M, N, K, outdtype_str) and
  gen_lookup_dict buckets each row into the BF16 or FP32 macro by
  outdtype. C++ runtime maps for the same shape can now resolve to
  distinct kernels per Y dtype; legacy CSVs without an outdtype column
  default to bf16 and only populate the BF16 map (no behavior change).

Tuner
- Promote dtype + outdtype into self.keys (4 -> 6) so same-shape rows
  with different output dtypes coexist instead of overwriting each
  other on update_tunedf. result_to_df / calculate read dtype/outdtype
  straight from the 6-tuple key and pick the right per-element bpe
  for tflops/bw.
- Add --dtype / --outdtype CLI options (with per-row CSV override),
  reference matmul cast / mp_tuner ref_args propagated to match Y dtype
  to avoid 'BFloat16 did not match Float' under checkAllclose.

Other
- opus_gemm.cu drops the splitk Y-must-be-bf16 TORCH_CHECK; both Y
  dtypes go through the same dispatcher.
- gemm_a16w16_opus removes the splitk+fp32 fallthrough; tuned winners
  are honored regardless of Y dtype.
- Tuned CSV: drop 3 stale rows referencing disabled non-splitk flatmm
  kids 100..115 (Python lookup_tuned would otherwise return them and
  raise 'Kernel id ... not found' at launch).
- op_tests/test_opus_a16w16_tune.py promoted into the repo and updated
  to exercise both bf16 and fp32 splitk paths.

Made-with: Cursor
(cherry picked from commit 2214d51)
Signed-off-by: demonsan <[email protected]>
(cherry picked from commit 3a0acfb)
Signed-off-by: demonsan <[email protected]>
(cherry picked from commit d1dc944)
- Move all module-level imports to the top of the file so the
  `OPUS_A16W16_TUNED_CSV` / `_AITER_VERBOSE` constant assignments no
  longer fall between import statements (E402).
- Drop the unused `stream = torch.cuda.current_stream()` local in
  `_opus_run_perftest` (F841); the function uses
  `torch.cuda.current_stream()` directly at the call sites.

Made-with: Cursor
(cherry picked from commit 4132bcc)
Run psf/black 26.3.1 on the opus-affected Python files so the
repository's `Check Code Style with Black` CI job passes. No semantic
change -- this is purely whitespace / line-wrapping per black defaults.

Made-with: Cursor
(cherry picked from commit 5e0b3ad)
Wire opus_gemm to a per-arch dispatch model so non-gfx950 callers fail
fast with a clear "pipeline TBD for this arch" message and multi-arch
wheels (e.g. GPU_ARCHS='gfx942;gfx950') still build cleanly. Three
defense layers, no behavior change on gfx950:

* Python import-time: aiter/ops/opus/_arch.py exposes a reusable
  _check_arch(supported, ...) helper. aiter/ops/opus/__init__.py calls
  it with {"gfx950"}; non-supported devices raise ImportError before
  the JIT module is touched. Detection prefers GPU_ARCHS env, falls
  back to rocminfo via aiter.jit.utils.chip_info.get_gfx_runtime, and
  silently skips on CPU-only hosts so the host-side dispatcher catches
  it later.

* Host C++ runtime: opus_gemm.cu now contains arch routers that switch
  on opus_get_gfx_arch() (cached hipGetDeviceProperties + gcnArchName
  prefix match in include/opus_gemm_arch.cuh). The gfx950 branch
  delegates to opus_dispatch_a16w16_gfx950<T> /
  opus_a16w16_tune_dispatch_gfx950<T> (in include/gfx950/...); other
  archs fall through to TORCH_CHECK with the full gcnArchName + device
  id. The fp8 a8w8 path keeps a direct gfx950 TORCH_CHECK because it
  doesn't yet flow through the arch router.

* Device compile-time: every __global__ in include/gfx950/ wraps the
  kernel body in #if defined(__gfx950__) so non-gfx950 device passes
  in multi-arch wheels emit an empty stub instead of failing on
  gfx950-only intrinsics (MFMA-32x32x16, ds_read_b64_tr, 160 KiB LDS).

To make the per-arch model scale, all gfx950-specific files were moved
from csrc/opus_gemm/include/pipeline/ (and the heuristic dispatcher)
to csrc/opus_gemm/include/gfx950/ with an _gfx950 suffix on every file
and on every traits / kargs struct. The cross-arch traits umbrella
opus_gemm_common.cuh now forwards to gfx950/ and is the natural place
to add gfx<NEW>/ headers when a future arch lands. gen_instances.py
follows the same convention via its PIPELINE_HEADER_MAP /
TRAITS_NAME_MAP / KARGS_NAME_MAP tables. The launcher symbol names
(e.g. opus_gemm_512x256x256x64_2x4_16x16x32_0x0x0) keep their existing
form since their tile / MFMA encodings are already gfx950-valid.

Validated on demon_test:
  * gfx950 single-arch full rebuild: 36.1s, lookup 336/336, tune
    17/17, gemm CLI passed (err=0, ~10.5us / 6.4 TFLOPs at
    M=128,N=256,K=1024).
  * Multi-arch (GPU_ARCHS='gfx942;gfx950') full rebuild: 51.1s, both
    --offload-arch values reach hipcc, .so loads on gfx950 and
    produces correct results.

csrc/opus_gemm/README.md gains a 9-step "Adding a new arch" guide
covering the enum, per-arch headers, common.cuh umbrella, opus_gemm.cu
routers, gen_instances.py codegen tables, the Python guard set, tuning
data, multi-arch wheel device-pass guards, and the validation
workflow.

Made-with: Cursor
(cherry picked from commit 8988ce9)
`module_deepgemm_opus` clean rebuild on the dev container drops from
~48s to ~22s (3-trial average, 128-core demon_test, ROCm 7.2.2,
MAX_JOBS=102) with no functional regression: tune test 30/30 +
lookup test 338/338 still pass.

Compile-time wall (3 trials, AITER_REBUILD=1, cleared build dir):

  Pre-split baseline:                       49.2 / 47.2 / 48.9s -> 48.4s
  Host/device pass split (intermediate):    31.8 / 34.2 / 31.6s -> 32.5s
  Fused host TU + per-kid device.cu (this): 22.5 / 22.0 / 22.4s -> 22.3s
  Saving vs. baseline:                                          -26.1s (-54%)

Critical path before:  ~26s (each instance.cpp parses <torch/all.h>
                       AND runs device codegen serially in one hipcc).
Critical path after:   ~14s (one fused host TU parses torch ONCE for
                       all 38 launchers; 38 tiny device.cu's finish
                       in ~2s each in parallel under MAX_JOBS=102).

What changed
------------

1. csrc/opus_gemm/gen_instances.py -- restructured codegen:
   * impl/{name}.cuh: kid-local Traits aliases + launcher body, three
     guard combinations to skip torch on the device pass / RTC TUs and
     to swap the pipeline header for a traits-only forward decl when
     OPUS_FUSED_HOST_TU is set (sidesteps the ODR clash between
     same-named layout helpers in different pipeline headers).
   * instances/all_instances_host.cu (NEW, one per module): defines
     OPUS_FUSED_HOST_TU, includes <torch/extension.h> ONCE, includes
     every kid's .cuh, instantiates all 38 launchers. Wrapped in
     #ifndef __HIP_DEVICE_COMPILE__ so device pass is empty (~0.4s).
   * instances/{name}_C{dtype}.device.cu (NEW, one per kid+dtype):
     pulls the full pipeline header and instantiates
     `template __global__ void kernel<...>`. Compiled with
     -D__HIPCC_RTC__ so the host pass takes the lean branch (no
     torch, no full HIP runtime, ~0.5s) while the device pass runs
     real GPU codegen (~1.5s).

   The fused host TU's <<<...>>> calls produce undefined
   __device_stub__ references; -fno-gpu-rdc is fine because the
   linker pairs each host stub to the matching device.cu's explicit
   instantiation via fat-binary segment merge.

2. aiter/jit framework -- new per-file flag plumbing:
   * cpp_extension.py: _write_ninja_file accepts an optional
     extra_cuda_cflags_per_source dict and emits per-build
     `cuda_post_cflags = $cuda_post_cflags <extra>` overrides on
     matching ninja `build` lines (fnmatch on absolute / basename).
   * core.py: build_module forwards a new flags_extra_hip_per_source
     option from optCompilerConfig.json down through _jit_compile.
   * optCompilerConfig.json: module_deepgemm_opus uses
     `flags_extra_hip_per_source: {"*.device.cu": ["-D__HIPCC_RTC__"]}`
     to apply RTC mode only to kernel-only TUs without breaking the
     dispatcher / pybind TUs that depend on
     __clang_hip_runtime_wrapper.h via ck_tile + pybind11.

3. csrc/include/opus/hip_minimal.hpp -- extended into a dual-pass
   replacement for <hip/hip_runtime.h>:
   * device-pass replicas of threadIdx / blockIdx / blockDim /
     gridDim, backed by __builtin_amdgcn_* and matching the HIP
     runtime's `extern const __device__ __attribute__((weak))` ABI;
   * __forceinline__ / __noinline__ macro fallbacks.

4. csrc/opus_gemm/include/opus_gemm_utils.cuh -- pass-aware include:
   <opus/hip_minimal.hpp> on __HIP_DEVICE_COMPILE__ OR __HIPCC_RTC__,
   full <hip/hip_runtime.h> + <hip/hip_bf16.h> + <hip/hip_fp8.h>
   otherwise.

5. csrc/opus_gemm/opus_gemm.cu and csrc/pybind/opus_gemm_pybind.cu --
   entire file wrapped in #ifndef __HIP_DEVICE_COMPILE__. Both are
   pure host code (no __global__, no <<<>>>) so the device pass had
   nothing to do; this drops their device pass from 12.5-15s to
   ~0.4s each.

6. csrc/opus_gemm/include/gfx950/splitk_reduce_gfx950.cuh -- explicit
   <cstdint> include now that the device pass no longer pulls
   <hip/hip_runtime.h> (which transitively provided uint16_t /
   uint32_t).

7. aiter/ops/opus/README.md -- new sections 7.6 (Compile-time
   techniques) and 7.7 (Future compile-time work) document the
   numbers, the per-TU breakdown, the architectural rationale
   behind every guard combination, and an analysis of remaining
   wins (PCH for the fused host TU's torch parse, narrower torch
   include, opus.hpp split, ccache, etc.).

(cherry picked from commit c0b542d)
Builds on the previous "fused host TU + per-file RTC flag" commit
(48s -> 22s) by stripping `<torch/all.h>` + `<ATen/...>` out of the
opus_gemm dispatch graph and codegen-emitted launchers, mirroring the
refactor in PR #2932 (`csrc/kernels/quant_kernels.cu` /
`csrc/include/quant.h`). End-to-end goes 22.3s -> 19.4s on the dev
container, total -29.0s (-60%) vs. the original 48.4s baseline.

Compile-time wall (3 trials, AITER_REBUILD=1, cleared build dir,
128-core demon_test, ROCm 7.2.2, MAX_JOBS=102):

  Pre-split baseline:                           48.4s
  Host/device pass split:                       32.5s
  Fused host TU + per-kid device.cu:            22.3s
  + torch removal (this commit):                19.4s  (19.5 / 19.5 / 19.2)
  Saving vs. baseline:                                 -29.0s (-60%)

Functional regression: tune test 30/30 + lookup test 338/338 still
pass.

Critical-path TU (the fused `all_instances_host.cu`):
                                       host pass   device pass   wall
  with torch (previous commit):           ~11.7s        ~0.4s    ~12s
  torch-free (this commit):               ~7s           ~0.4s    ~8s

What changed
------------

1. csrc/opus_gemm/include/opus_gemm.h -- entry-point signatures take
   `aiter_tensor_t&` (POD, defined in csrc/include/aiter_tensor.h)
   instead of `torch::Tensor&`, return `void` instead of
   `torch::Tensor`. The header costs ~200 preprocessed lines instead
   of ~50K from `<torch/all.h>` + `<torch/extension.h>`.

2. csrc/opus_gemm/include/opus_gemm_arch.cuh and
   csrc/opus_gemm/include/gfx950/opus_gemm_arch_gfx950.cuh --
   `TORCH_CHECK` -> `AITER_CHECK`, drop `<c10/util/Exception.h>` for
   `aiter_hip_common.h`.

3. csrc/opus_gemm/include/gfx950/opus_gemm_heuristic_dispatch_gfx950.cuh
   -- `OpusA16W16NoscaleKernel` is now
   `std::function<void(aiter_tensor_t&, ...)>`, drops the
   `<torch/extension.h>` include. Every dispatch map entry along the
   gfx950 path is now torch-free.

4. csrc/opus_gemm/opus_gemm.cu -- both entry points (`opus_gemm`,
   `opus_gemm_a16w16_tune`) take `aiter_tensor_t`, use `AiterDtype`
   enum (`AITER_DTYPE_bf16` / `_fp32` / `_fp8`) instead of
   `at::ScalarType::*` / `torch_fp8`, return `void`. `AITER_CHECK`
   with variadic args replaces the `TORCH_CHECK` calls. `bf16_t` /
   `fp32_t` come from `opus_gemm_utils.cuh` directly now (no
   `py_itfs_common.h`).

5. csrc/opus_gemm/gen_instances.py -- the codegen-emitted launcher
   templates use `aiter_tensor_t&`, the bias validator uses
   `AITER_CHECK` plus the PyTorch-compatible accessors that
   `aiter_tensor_t` exposes (`is_contiguous()`, `dtype()`, `dim()`,
   `size()`). `at::hip::getCurrentHIPStreamMasqueradingAsCUDA().stream()`
   becomes `aiter::getCurrentHIPStream()` (thread-local pure-HIP
   manager from `aiter_stream.h`). The fused
   `all_instances_host.cu` includes `aiter_tensor.h` +
   `aiter_stream.h` instead of `<torch/extension.h>` +
   `<ATen/hip/HIPContext.h>`. The manifest header
   (`opus_gemm_manifest.h`) drops `<torch/extension.h>` for
   `aiter_tensor.h`.

6. splitk launcher's fp32 workspace -- `torch::empty(...
   TensorOptions().dtype(kFloat32).device(Y.device()))` is replaced
   by `hipMallocAsync(&ptr, ws_bytes, stream)` paired with a
   `hipFreeAsync(ptr, stream)` queued AFTER the reduce kernel on
   the same stream. Same stream-ordered lifetime semantics as the
   original PyTorch caching-allocator pattern, just without the
   torch dependency.

7. csrc/pybind/opus_gemm_pybind.cu -- adds `AITER_SET_STREAM_PYBIND`
   so Python can call `module._set_current_hip_stream(...)`.

8. aiter/ops/opus/gemm_op_a16w16.py --
   `@compile_ops("module_deepgemm_opus", develop=True)` on both
   `_opus_gemm_a16w16_tune_raw` and `_opus_gemm_bf16_dispatch`.
   `develop=True` makes the JIT wrapper (a) inject the current
   torch CUDA stream into the C++ `aiter::getCurrentHIPStream`
   thread-local before each call and (b) auto-convert any
   `torch.Tensor` arg to the pybind-registered `aiter_tensor_t` via
   `aiter.utility.dtypes.torch_to_aiter_pybind`. Since the C++
   side now returns `void`, `opus_gemm_a16w16_tune` keeps its
   `return Y` contract by returning the in-place tensor itself.

Why this saves ~3s on top of the previous fusion commit
-------------------------------------------------------

The previous commit's critical path was the fused host TU's
`<torch/all.h>` + `<ATen/...>` parse (~11.7s on a 437K-line
preprocessed input). After this commit, the fused TU's preprocessed
input drops to ~110K lines (no libtorch / ATen / pybind11 /
hipblas / hipsolver), and the frontend cost falls to ~7s. The
device pass on the fused TU was already empty (#ifndef
__HIP_DEVICE_COMPILE__), and the per-kid `*.device.cu`'s never
included torch in the first place (they were already on the lean
__HIPCC_RTC__ path), so the device side of the build is unchanged.

(cherry picked from commit 9e4ed32)
…rray lookup

Two compounding host-pass optimizations on the dispatcher TU, dropping
module_deepgemm_opus full rebuild from 19.4s -> 14.0s (3-trial avg on
demon_test, 128-core, ROCm 7.2.2). Critical path is now the slowest
single device.cu's GPU codegen (~8.5s), not host parse anymore.

Round 1: dispatcher TU was still pulling <torch/all.h> + the full
<ATen/...> stack via a stale `#include "py_itfs_common.h"` in
opus_gemm_arch_gfx950.cuh. Replaced with the torch-free
opus_gemm_utils.cuh, which provides the same bf16_t / fp32_t aliases.
Drops dispatcher TU preprocessed input from 401K lines to 154K, host
pass FE 11.0s -> 1.5s, single-TU wall 13.1s -> 3.2s.

Round 2: lookup tables used to be std::unordered_map<tuple<int,int,int>,
std::function<...>, IntTupleHash>, populated at first call via a
runtime initializer-list. The hashtable + std::function + lambda init
combo alone added ~1s of frontend / template instantiation per
dispatcher TU on top of round 1. Replaced with:

  - `OpusA16W16NoscaleKernel = void (*)(...)`  (was: std::function)
  - `static constexpr OpusA16W16RuntimeEntry kLookup[] = { ... }`
    sorted lex on (M, N, K), looked up via std::lower_bound.
  - `static constexpr OpusA16W16TuneEntry kTune[] = { ... }`
    sorted by kid, same lookup pattern.
  - codegen (gen_instances.py) emits sorted entries directly into
    macros that expand to plain `{ key, &kernel<CTYPE> }` initializer
    rows, no map/function template machinery involved.

Drops dispatcher host pass another 2.69s -> 1.43s (-47%).

Combined this round: -5.4s wall (-28%). Vs original 48.4s baseline:
-34.4s (-71%) total across all five compile-time optimization rounds.

Functional: op_tests/test_opus_a16w16_tune.py 30/30 still passes,
op_tests/test_opus_a16w16_lookup.py 338/338 still passes. Lookup
semantics are identical -- same (M,N,K) keys, same kernel functions,
same heuristic fallback path. The only behavior change is faster
first-call dispatch (no heap allocation of std::function, no hash
table construction, just a static array binary search).

Files: csrc/opus_gemm/include/gfx950/opus_gemm_arch_gfx950.cuh   - lookup rewrite
  csrc/opus_gemm/include/gfx950/opus_gemm_heuristic_dispatch_gfx950.cuh
                                                            - kernel typedef -> fnptr
  csrc/opus_gemm/opus_gemm.cu                               - a8w8 kernel typedefs -> fnptr
  csrc/opus_gemm/gen_instances.py                           - sorted-entry codegen
  aiter/ops/opus/README.md                                  - §7.6 / §7.7 update
Made-with: Cursor
(cherry picked from commit 217094b)
…s forensics

Two changes; one drops CPU work, the other documents why end-to-end
wall has hit a hardware-imposed floor.

== A. splitk_reduce_kernel: shared TU instead of duplicated per-kid ==

Each splitk kid's launcher dispatches to one of 4 splitk_reduce_kernel
specialisations (D_OUT bf16/fp32 x HAS_BIAS true/false). gen_instances.py
used to append all 4 instantiations to every splitk kid's device.cu, so
the 23 splitk TUs each compiled the 4 reduce kernels redundantly. The
linker deduped the resulting weak symbols, but each TU still paid the
full RA + ISA-emit cost (~0.3-0.5s wall + ~30-50KB ISA per TU x 23 TUs
= ~9s of duplicated CPU work).

This commit moves the 4 reduce instantiations out of every splitk kid's
device.cu into a single new instances/splitk_reduce.device.cu emitted by
the new gen_instances.py:_emit_splitk_reduce_tu() codegen helper. Each
splitk kid's device.cu now carries only its own main-kernel
instantiation, ~50% smaller and ~7-15% faster per TU.

End-to-end wall is unchanged (14.4s vs 14.0s previous, within noise) on
the test host because the slowest single TU (splitk_64x96x64_wgpcu1) is
still bottleneck-bound at ~8s by its own main-kernel codegen and ninja
schedules everything else around it. The win is in CPU work avoided:
~9s of duplicated reduce codegen across all splitk TUs reduces to ~0.3s
in the dedicated TU. On hardware with smaller MAX_JOBS or under load,
this shows up as a real wall-time win.

Functional: op_tests/test_opus_a16w16_tune.py 30/30 still passes,
op_tests/test_opus_a16w16_lookup.py 338/338 still passes.

== B. -mllvm flag sweep: measured negative ==

We tested whether the aiter-global -mllvm flags inherited by every
device pass were responsible for the slowest TU's wall. Earlier
speculation pointed at -amdgpu-early-inline-all=true plus
-amdgpu-function-calls=false (which together force every call to
inline into one mega-function for the RA).

Five build configurations measured against 24 dsv3+gptoss bf16
shapes via opus_gemm_tune.py:

  baseline: all 6 -mllvm flags on   build 18.1s, perf reference
  -amdgpu-early-inline-all=false    build 17.9s, perf +0.24%
  -amdgpu-function-calls=true       build 17.8s, perf -0.10%
  --amdgpu-mfma-vgpr-form=false     build 18.3s, perf +0.04%
  all three off                     build 17.9s, perf +0.06%

Build wall and perf differences are within measurement noise. Also
tried -O1, --amdgpu-igrouplp-exact-solver=0,
-greedy-regalloc-eviction-max-iterations=2 (last one rejected by
ROCm 7.2.2 LLVM as unknown). None reduced the slowest TU's wall by
more than noise. Conclusion: the Greedy RA Evict cost on the
critical-path kid is fundamental to the IR's register pressure and
not gated by any user-tunable -mllvm flag in this LLVM revision.
The five global flags should stay because they help perf elsewhere
in aiter.

== C. SGPR spill forensics (new README §7.6.1) ==

Documented the why-it-takes-8s analysis on
flatmm_splitk_64x96x64_wgpcu1<fp32_t>:

  - 8.29s total device pass:
      MCG    6.94s (84%)
      FE     0.66s ( 8%)
      OPT    0.61s ( 7%)
      IR-gen 0.09s ( 1%)
  - MCG breakdown:
      Greedy Register Allocator: 5.74s (77% of total)
        Evict sub-pass:           5.22s (99% of RA)
      Machine Sched:             0.56s
      ~150 other passes:         ~0.45s
  - Resulting kernel metadata:
      ISA size:           388 KB    (vs ~8 KB for non-splitk kids)
      vgpr_count:         423
      agpr_count:         167
      sgpr_count:         106
      sgpr_spill_count:   8931
      private_segment:    24704 bytes
      group_segment:      144 KB
      pfk:                7
      WG_PER_CU:          1

Root cause traced to the K-loop's `slot = issue_k % pfk` runtime
indexing: GFX9 has no "load VGPR by runtime index" instruction, so
LLVM expands every register-tile access into a 7-way s_cmp_eq +
s_cselect_b64 + v_cndmask_b32 select tree. Across ~192 register
tile elements that produces ~12k s_cselect_b64 + ~12k s_cmp_eq
instructions, every one of which creates a vcc (SGPR pair) live
range. SGPR pressure exceeds the gfx950 ~100 physical SGPR cap, so
LLVM spills via v_writelane_b32 to 4 reserved VGPRs (v252..v255).
17956 v_writelane/v_readlane instructions in the asm, four whole
VGPRs reserved as 64-lane SGPR scratch, and a 24KB scratch frame.

The fix is structural (kernel rewrite to hand-unroll slot dispatch),
not a -mllvm knob. Documented in README §7.7 as item 3.

Files: csrc/opus_gemm/gen_instances.py        - new _emit_splitk_reduce_tu
  aiter/ops/opus/README.md               - §7.6 round 6 added,
                                           §7.6.1 device forensics,
                                           §7.7 -mllvm sweep result
Made-with: Cursor
(cherry picked from commit e9cb887)
… spill

Adds `#pragma unroll` to the five `for (I = 0; I < EXPAND_K * EXPAND_M *
EXPAND_N; ...)` outer loops in `csrc/include/opus/tiled_mma_adaptor`'s
`operator()` and `step_k`, plus the inner `for (j = 0; j < a_len; ...)`
extract / insert loops in the `vector_t`-overload paths. Trip counts
are all constexpr so the unroll is purely a hint to clang's heuristic.

== Why this matters ==

For small tiles (e.g. 2x2x2 = 8 outer iters on non-splitk a16w16) clang
unrolled the loop spontaneously. For larger tiles (e.g.
4x6x2 = 48 outer iters x mma_a_len=4 inner = 192 reads against
vtype_a / vtype_b / vtype_c) the heuristic gave up and the loop ran at
runtime. GFX9 has no "load VGPR by runtime index" instruction, so each
`s_a[j] = a[i_a + j]` compiled to an N-way s_cmp_eq + s_cselect_b64 +
v_cndmask_b32 select tree. Each s_cselect_b64 produced a vcc (SGPR
pair) live range, blowing past gfx950's ~100 physical SGPR cap and
forcing LLVM to spill SGPRs to VGPR lanes (v_writelane_b32) and recurse
through Greedy RA's Evict policy thousands of times.

== Numbers (slowest splitk kid pre-fix) ==

  Metric              Before     After     Change
  Slowest TU wall     7.7s       1.3s      -83%
  ISA size            388 KB     27 KB     -93%
  s_cselect_b64       12,098     2         -99.98%
  v_writelane_b32     17,956     0         -100%
  sgpr_spill_count    8,931      0         -100%
  sgpr_count          106        46        -57%
  vgpr_count          423        310       -27%
  agpr_count          167        54        -68%
  private_segment     24,704 B   0         -100%
  ASM total lines     69,426     1,958     -97%

== End-to-end build wall (3-trial avg, demon_test, MAX_JOBS=102) ==

  Before round 7: 14.4s (14.0 / 14.7 / 14.4)
  After round 7:  11.1s (11.1 / 11.3 / 11.0)
  Saving:         -3.3s (-23%)
  vs. baseline:   -37.3s (-77%)

The new critical path is opus_gemm_pybind.cu at 4.7s (mostly pybind11 +
libtorch parse). All device TUs now finish in 1.5s or less.

== Functional + perf ==

  test_opus_a16w16_tune.py: 30/30 passed
  test_opus_a16w16_lookup.py: 338/338 passed

  Perf benchmark on 24-shape mix from dsv3_bf16_untuned_gemm.csv +
  gptoss_bf16_tuned_gemm.csv, tuned via opus_gemm_tune.py, comparing
  best-kernel us per shape vs the pre-round-7 build:

    total us:       1054.2 (before)  ->  1057.1 (after)  +0.27%
    geomean ratio:  +0.37% per shape

  Within measurement noise (5-warmup, 20-iter timing).

== Scope ==

`opus.hpp` is shared by opus_attn / opus_fmm / opus_gemm and any other
kernel that goes through tiled_mma_adaptor. Smaller tile configs that
already unrolled spontaneously are unaffected -- they unroll the same
way they did before, just under the explicit pragma instead of the
heuristic. Larger tile configs that previously didn't unroll
(currently only opus_gemm's splitk family hits the threshold) now
consistently unroll, eliminating the SGPR spill blow-up wherever it
would have appeared.

Files: csrc/include/opus/opus.hpp           - 5 #pragma unroll on outer loops,
                                         3 #pragma unroll on inner loops
                                         in vector_t paths
  aiter/ops/opus/README.md             - §7.6 round 7 added with
                                         before/after metrics, §7.6.1
                                         updated to reflect fix, §7.7
                                         item 3 closed
Made-with: Cursor
(cherry picked from commit 25f224f)
Signed-off-by: demonsan <[email protected]>
(cherry picked from commit 917da0b)
The splitk launcher used to allocate its fp32 workspace via
`hipMallocAsync(stream)` + matching `hipFreeAsync(stream)` after the
reduce kernel (introduced in the torch-removal round). On ROCm 7.2.2
this pair is not a graph-capturable no-op: every hipgraph replay
re-runs the alloc/free host-side, costing ~120us / replay (vs ~30us
of actual kernel work) for a 5x graph-mode slowdown.

The eager-mode tuner pays the alloc/free cost on every iter too,
distorting splitk's measured perf so much that the tuner picks
split-barrier kids for shapes where splitk would actually win:

  Tuner output on dsv3 + gptoss thin shapes (24 representative):
    Before this fix: 0/24 splitk wins, total 1057us, all picks were
                    split-barrier kid 6/8 at ~22-67us per shape.
    After:           24/24 splitk wins, total 258us (4.1x faster),
                    all picks are flatmm_splitk_256x32x32x{64,128}
                    at 7-36us per shape.

  Per-shape examples (us, lower is better):
    M=1 N=128  K=2880:  50.5  ->  7.5  (-85%)
    M=1 N=2880 K=2048:  21.0  ->  7.5  (-64%)
    M=1 N=3072 K=1536:  17.4  ->  6.9  (-60%)
    M=1 N=7168 K=2048:  23.4  ->  8.7  (-63%)
    M=32 N=2560 K=2880: 51.8  ->  8.1  (-84%)

== Fix ==

Replace `hipMallocAsync` / `hipFreeAsync` with a thread_local cache
in the splitk launcher. First call does a one-shot `hipMalloc`,
subsequent calls reuse the cached pointer. The cache grows on demand
in 4 MiB chunks to absorb shape variations without churning. Inside
HIP graph capture the grow path is forbidden (hipMalloc /
hipDeviceSynchronize / hipFree are stream-capture-illegal); we check
hipStreamIsCapturing and AITER_CHECK with a clear error pointing the
caller at the standard "warm up once eagerly before capture" pattern.

== Graph compatibility ==

  Before: graph splitk took 161us / replay (vs 31us eager) due to the
          hipMallocAsync overhead being baked into every replay.
  After:  graph splitk takes 8us / replay (4x faster than eager
          because the kernel-launch overhead is amortized across the
          captured loop).

  op_tests/check_opus_splitk_graph.py covers two splitk shapes under
  full capture + replay; both now pass cleanly. The test's perftest
  decorator does the eager warmup before capture, satisfying the
  cache-prewarm requirement.

== Functional ==

  test_opus_a16w16_tune.py: 30/30
  test_opus_a16w16_lookup.py: 338/338
  check_opus_splitk_graph.py: both shapes complete

  Build wall: 11.0s avg (3-trial), unchanged from previous commit.

== Memory ==

  Cache lives until process exit (no destructor; thread_local with
  hipMalloc'd pointer). For a typical opus user the workspace caps
  out at ~4-32 MiB once the largest seen shape has been processed,
  which is small relative to PyTorch's caching allocator footprint.
  No leak in practice -- thread teardown runs the static destructors
  on the wsCachedPtr in normal exit. We accept "ptr held to
  process exit" rather than emit a hipFree at thread teardown
  because (a) it's the same lifetime model as PyTorch's CUDA
  caching allocator and (b) hipFree at teardown is fragile when
  the runtime is mid-shutdown.

Files: csrc/opus_gemm/gen_instances.py  - splitk launcher: thread_local
                                     workspace cache instead of
                                     hipMallocAsync per call
Made-with: Cursor
(cherry picked from commit ede232b)
…_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)
demonsan and others added 20 commits May 27, 2026 23:45
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]>
Drop the M%B_M==0 hard-assert in the generated mono-tile launcher; the
kernel body already uses ceil tile counts internally and the M-axis
buffer descriptor (size `(m-row)*stride`) clamps OOB rows at the matrix
edge. Update the host grid to ceil tile count so the tail M tile is
covered. Empirically verified across all 5 mono kids (1400..1404) with
M offsets {-1,+1,+B_M/2,+B_M+1,+2B_M+3,+3B_M-5}: 35/35 PASS, max_abs
<= 0.25.

N stays asserted with a more precise message: g_c is row-contiguous so
an N-tail column write spills into the next row and is not caught by
the flat-byte buffer descriptor (empirically ~95%% mismatch on any N+1).
Unlocking N would require switching to store_if with a per-issue column
predicate (as a8w8_noscale / flatmm / persistent already do), which
adds a per-store cmp and is deferred for performance reasons.

K stays asserted (kernel body has no K-tail mask).

Co-Authored-By: Claude Opus 4 <[email protected]>
@demonsan
demonsan requested a review from valarLip May 28, 2026 04:56

@demonsan demonsan left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

n,k will use other instances cover

demonsan and others added 2 commits May 28, 2026 01:41
tuned_gemm.get_padded_m keys CSV lookup on padded_M, so a mono-tile
winner tuned on padded_M can surface for an actual M that B_M does
not divide. The kernel handles M-tail via the bounded gmem desc
(41e2d48), so M-misalign is fine -- but N/K-misalign still aborts
the launcher (no N/K-tail mask).

Add mono_kid_shape_ok(kid, N, K) in opus/common.py (B_M intentionally
skipped; non-mono kids short-circuit to True) and gate the call in
opus_gemm_a16w16_tune: on mismatch, log a warning and reroute to the
bf16 heuristic dispatch (which never returns a mono kid), instead of
letting the launcher AITER_CHECK abort the process.

Change confined to opus; tuned_gemm untouched.

Co-Authored-By: Claude Opus 4 <[email protected]>
Captured HIP graphs baked the raw workspace pointer into kargs, so a later
eager call that grew the thread_local cache hipFree'd the old buffer and
left every prior-captured graph with a dangling ptr — observed as a
"memory access fault, write to read-only page" on first replay after grow.

Add a tiny opus_splitk_ws_handle{ptr, bytes} POD; the launcher allocates
one in host-coherent memory (hipHostMalloc) and only the slot contents
change on grow. Main + reduce kernels deref the slot at entry. Captured
graphs hold the stable slot address, so post-capture grow is safe.

Co-Authored-By: Claude Opus 4 <[email protected]>
@valarLip
valarLip merged commit 1991770 into main May 28, 2026
18 checks passed
@valarLip
valarLip deleted the blyu/opus_gemm branch May 28, 2026 09:50
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.

2 participants