Skip to content

[quant] refactor hip kernels - #2932

Merged
amd-ruitang3 merged 2 commits into
mainfrom
quant_hip_kl_refactor
Apr 28, 2026
Merged

amd-ruitang3 merged 2 commits into
mainfrom
quant_hip_kl_refactor

Conversation

@amd-ruitang3

@amd-ruitang3 amd-ruitang3 commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

remove torch dependency.

Technical Details

Test Plan

Test Result

The build duration dropped from 47.5 seconds to 16.9 seconds.
The .so file size dropped slightly from 1.9M to 1.8M, caused by Torch-related content in aiter_opus_plus.h. We will try to remove it once all kernels have been refactored.

Submission Checklist

@amd-ruitang3
amd-ruitang3 requested review from a team and Copilot April 28, 2026 05:21
@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 2932 --add-label <label>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Refactors the quantization HIP kernels and bindings to remove direct torch::Tensor/ATen dependencies by switching to the internal aiter_tensor_t + thread-local HIP stream mechanism, aligning quant with the existing “torch-free” kernel patterns.

Changes:

  • Update quant kernels/header to use aiter_tensor_t, HipDeviceGuard, and aiter::getCurrentHIPStream() instead of ATen/Torch APIs.
  • Add/extend torch-free dispatch utilities in aiter_dispatch.h (*_rmTorch macros) and tweak AITER_CHECK formatting.
  • Switch Python quant op wrappers to @compile_ops(..., develop=True) and expose _set_current_hip_stream in the quant pybind module.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
csrc/pybind/quant_pybind.cu Registers _set_current_hip_stream so develop-mode wrappers can set the TLS HIP stream for quant ops.
csrc/kernels/quant_kernels.cu Converts quant entrypoints to aiter_tensor_t, torch-free dispatch, and TLS stream usage; replaces TORCH_CHECK with AITER_CHECK.
csrc/kernels/activation_kernels.cu Switches to the new *_rmTorch dispatch + vec-size macros for torch-free dispatching.
csrc/include/quant.h Updates public quant function declarations to use aiter_tensor_t and std::optional<aiter_tensor_t>.
csrc/include/aiter_hip_common.h Adjusts AITER_CHECK/check_fail formatting and supports empty __VA_ARGS__.
csrc/include/aiter_dispatch.h Adds torch-free dtype dispatch + vec-size dispatch macros and dtype→C++ type mapping.
aiter/ops/quant.py Enables develop=True for quant ops so tensors are converted to pybind aiter_tensor_t and stream is set before calls.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread csrc/kernels/quant_kernels.cu Resolved
Comment thread csrc/kernels/quant_kernels.cu Resolved
Comment thread csrc/kernels/quant_kernels.cu Resolved
Comment thread csrc/kernels/quant_kernels.cu Resolved
Comment thread csrc/kernels/quant_kernels.cu Resolved
@amd-ruitang3
amd-ruitang3 merged commit c1c65e6 into main Apr 28, 2026
39 of 42 checks passed
@amd-ruitang3
amd-ruitang3 deleted the quant_hip_kl_refactor branch April 28, 2026 15:24
demonsan added a commit that referenced this pull request Apr 29, 2026
* CI: surface runner-config mapping in AMD CI job monitor (#2711)

* Update runner-config.yml

* CI: surface runner-config mapping in AMD CI job monitor

Load GPU architecture and count from runner-config.yml so the runner fleet summary shows the configured inventory for each label. Trigger the monitor workflow when runner mappings change and install PyYAML for the runner report job.

* CI: auto-update split test FILE_TIMES (#2709)

Co-authored-by: gyohuangxin <[email protected]>
Co-authored-by: Xin Huang <[email protected]>

* CI: add standalone OPUS test workflow (#2716)

Add a dedicated GitHub Actions workflow for op_tests/opus so OPUS validation runs independently on MI35X and MI325 runners without being mixed into the main Aiter test shards.

* add signature and refine lru cache (#2710)

Co-authored-by: solin <[email protected]>

* CI: separate Aiter Test concurrency for push and schedule (#2718)

Split main-branch concurrency by event type so scheduled runs do not block push-triggered validation when a long queued job keeps the nightly workflow open.

* fix split module jit and retune (#2719)

* [TRITON] Prevent NUM_KSPLIT from reducing K dim below GROUP_K (#2661)

* CI: Enable Deepseek ATOM tests on MI35X (#2667)

* CI: Enable Deepseek ATOM tests on MI35X

* CI: Use /models cache for MI35X ATOM DeepSeek test

Route the MI35X DeepSeek job to the runner-local /models cache so it avoids downloading into /run, and make the output artifact name unique now that two DeepSeek variants run in the same workflow.

* CI: Mount /models into MI35X ATOM test container

Pass the runner's shared /models cache into atom_aiter_test so MI35X DeepSeek jobs can use the mounted model path.

* feat: _flash_attn_forward add out args (#2648)

* Replace CK/CK_TILE in MLA Reduce and Metadata Kernel with OPUS (#2717)

* replace ck with opus

* fix compile issue

* fix waterfall and use buffer inst for lse.

* Replace ck with opus for mla metadata.

* Add dim=512 fp32 case for wave32

* docs: add ISA-level kernel optimization guide (#2708)

* docs: add ISA-level kernel optimization guide using LLVM tools

Step-by-step guide covering the full LLVM-based workflow for
inspecting, modifying, and recompiling AITER GPU kernel ISA:
disassemble, extract reassemblable .s, round-trip recompile with
binary-identical .text verification, and profile with rocprofv3.

Includes Python extraction script handling branch label word-offset
addressing, llvm-objcopy section swap for preserving kernel metadata,
and rocprofv3 kernel-trace + ATT profiling instructions.

* docs: add ISA optimization code examples and Dockerfile

Runnable companion to the ISA kernel optimization guide:
- extract_asm.py: standalone ASM extraction with CLI interface
- analyze_kernel.py: instruction mix analysis and rocprofv3 profile parser
- roundtrip.sh: end-to-end disassemble/extract/recompile/verify script
- Dockerfile: ROCm 7.2.1 dev environment with all tools pre-installed
  including ATT trace decoder built from source

* style: fix black formatting and ruff lint in ISA optimization examples

- Rename loop var 'l' to 'ln' to fix E741 (ambiguous variable name)
- Remove extraneous f-prefix on strings without placeholders (F541)
- Apply black auto-formatting

* style: fix black formatting for CI compatibility

- Add blank line between module docstring and imports (E302)
- Collapse multiline f-string call arguments

---------

Co-authored-by: Peng Sun <[email protected]>

* Add run_config and compare in tuner (#2375)

* Add run_config/compare support to GemmTuner (bf16)

- Add config_env_name, _clear_op_caches(), and run_config() to GemmTuner
  so --run_config and --compare flags work for bf16 GEMM tuning
- Update bubbly-exploring-turtle.md plan doc to reflect the full
  implementation including --compare, config_env_name, cache clearing,
  and post-tune config switching architecture

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* Add --run_config and --compare benchmark support to all tuners

Add infrastructure in base_tuner.py for production operator benchmarking:
- --run_config: benchmark only, no tuning
- --compare: pre-tune benchmark, tune, post-tune benchmark with comparison table
- Config env switching and cache clearing for post-tune benchmarks

Implement run_config() and _clear_op_caches() in all CK-based tuners:
gemm_a8w8, gemm_a8w8_bpreshuffle, gemm_a8w8_blockscale,
gemm_a8w8_blockscale_bpreshuffle, gemm_a4w4_blockscale,
gemm_moe_2stages, batched_gemm_a8w8, batched_gemm_bf16

* Revert unintended composable_kernel submodule change

* Fix review comments and remove intermediate plan docs

- Save/restore AITER_REBUILD original value instead of hardcoding 0
- Use defensive strip() for mixed-type object columns in _read_csv
- Remove docs/bubbly-exploring-turtle.md and docs/run_config_benchmark.md
  (consolidated into csrc/.claude/add_run_config_to_tuner.md)

* update ref rtol,atol

* Fix tuner cache invalidation, run_config preshuffle, and compare workflow

- Fix _clear_op_caches for all tuners: properly clear lru_cache and
  internal dict/attribute caches (a4w4, a8w8 variants, fmoe) so
  post-tune benchmarks use freshly tuned configs instead of stale ones.
- Fix fmoe run_config: preshuffle weights before calling fused_moe to
  match production layout (tuner always tunes with bpreshuffle=True),
  preventing preshuffle_on/off module mismatch and 99%+ error.
- Add defensive warning in fused_moe get_2stage_cfgs when tuned config
  is found but is_shuffled=False.
- Fix run_config to read shapes from tuned CSV and set config env var.
- Fix --compare workflow: run post-tune benchmark before tune_summary
  to avoid summary errors blocking verification.
- Fix base_tuner _set_config_env_for_run_config return value.
- Use print instead of logger.info for benchmark tables.

* fix format

* fix format

* update readme

* fix lint error

* fix lint

* update csv only when perf improves

* format

* fix lint

* revert format for some files

* clarify compare and gated update flow

Make --compare keep a candidate csv and require --update_improved before writing back tuned results so the CLI stays explicit and easier to extend.

Made-with: Cursor

* fix flydsl GemmTuner review issues

Trigger FlyDSL package validation before importing tuning kernels and align the FlyDSL bias cast order with the runtime path to avoid unintended dtype promotion.

Made-with: Cursor

* update

* revert claude md

* update shape_grouped

* fix format

* fix bug

* fix lint error

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>

* Revert "fix(car): craph capture err (#2638)" (#2735)

This reverts commit 5759ee2943b5326dec23910135381b426ff65196.

* [TRITON] Swiglu and reduce refactor (#2583)

* Move swiglu to a util file + add optional residual flag

* refactor reduce and make it compatible with >65k tokens

* Update aiter/ops/triton/_triton_kernels/moe/reduce.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

---------

Co-authored-by: Lukasz Burzawa <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* [aiter] type hints mismatch (#2728)

* fix: silence false warning in fmha_fwd_v3 when use_asm_v3 is disabled (#2744)

When `use_asm_v3` is `false`, `fmha_fwd_v3()` correctly returns `-1` to
fall back to the CK path, but it also emits a misleading "unsupported
condition in fwd_v3!!!" warning. This is not an unsupported condition —
the caller intentionally opted out of v3.

Separate the `use_asm_v3` check into an early return without a warning,
so the `AITER_LOG_WARNING` only fires for genuinely unsupported parameter
combinations (wrong head dims, unsupported dtypes, bias, dropout, wrong
arch).

Made-with: Cursor

* Add FlyDSL GEMM AOT precompile support (#2741)

* feat(aot): add MoE FlyDSL AOT pre-compilation module

Co-Authored-By: Claude Opus 4 <[email protected]>
Signed-off-by: zhiding512 <[email protected]>

* refactor(aot): remove --stage flag from MoE AOT module

Co-Authored-By: Claude Opus 4 <[email protected]>
Signed-off-by: zhiding512 <[email protected]>

* reformat

* feat(aot): integrate FlyDSL MoE AOT precompilation into setup.py

Move moe.py into aiter/aot/flydsl/, support multiple CSV configs,
simplify compile_one_config to use COMPILE_ONLY=1 env var, and add
MoE AOT pre-compilation step to the package build in setup.py.

Co-Authored-By: Claude Opus 4 <[email protected]>
Signed-off-by: zhimding <[email protected]>

* feat(aot): FlyDSL MoE AOT with COMPILE_ONLY dummy-tensor precompilation

Rework FlyDSL MoE AOT to use COMPILE_ONLY=1 with dummy tensors instead
of run_kernel, removing all HIP op dependencies (moe_sorting,
shuffle_weight, etc.) from the precompilation path.

Changes:
- Replace _run_kernel with _precompile_to_cache using torch.zeros
  dummy tensors and COMPILE_ONLY=1 for pkl cache generation
- Add sys.modules bridging in setup.py so aiter.jit.core reuses the
  same module instance loaded via sys.path
- Auto-detect bundled flydsl_cache in aiter/__init__.py and set
  FLYDSL_RUNTIME_CACHE_DIR
- Add KeyError to aiter/__init__.py exception handler for robustness
- Support multiple CSV configs (dsv3 + kimik2)
- Remove run_kernel parameter and test_bad_tile logic

Signed-off-by: zhimding <[email protected]>

* update flydsl

* update flydsl

* adapt hgemm

* fix black

* add flydsl gemm aot precompile support

---------

Signed-off-by: zhiding512 <[email protected]>
Signed-off-by: zhimding <[email protected]>
Co-authored-by: Claude Opus 4 <[email protected]>

* gather support qk_nope_head_dim != v_head_dim (#2739)

* gather support qk_nope_head_dim != v_head_dim

* fix 192 pad

* feat: add/retune BF16 GEMM configs with FlyDSL backend for 6 models (#2733)

* feat: add/retune BF16 GEMM configs with FlyDSL backend for 6 models

Tuned on MI355X (gfx950) with all backends competing (ASM, hipBLASLt,
Triton, FlyDSL). New tuned configs for Llama 70B, Llama 405B, Qwen 32B.
Re-tuned existing configs for GPT-OSS, DSV3, Kimi-K2 to include FlyDSL.

Backend wins across 708 total shapes:
- hipBLASLt: 472 (66.7%)
- ASM: 131 (18.5%)
- FlyDSL: 70 (9.9%)
- Triton: 7 (1.0%)
- Mixed/other: 28 (4.0%)

* feat: retune BF16 GEMM without hipBLASLt, add GLM-5 and 3 new models

Re-tuned all BF16 GEMM configs on MI355X (gfx950) with --libtype
asm,triton,flydsl (no hipBLASLt). Added GLM-5 (88 shapes from CI log)
and new configs for Llama 70B, Llama 405B, Qwen 32B.

Backend wins across 796 total shapes (7 models):
- ASM: 437 (54.9%)
- FlyDSL: 224 (28.1%)
- Triton: 135 (17.0%)

Per-model breakdown:
- GPT-OSS (57): asm=54, triton=3 (bias=True, no FlyDSL support)
- DSV3 (58): flydsl=22, triton=18, asm=18
- Kimi-K2 (125): asm=77, flydsl=46, triton=2
- GLM-5 (88): asm=42, flydsl=30, triton=16
- Llama 70B (156): asm=84, flydsl=49, triton=23
- Llama 405B (156): asm=89, flydsl=43, triton=24
- Qwen 32B (156): asm=73, triton=49, flydsl=34

Tuning time without hipBLASLt: 4h total (long pole: 405B @ 4h)
vs with hipBLASLt: 10h+ total (long pole: 405B @ 8h+)

* Hoist introspection out of per-call ctype dispatch (#2742)

* Hoist inspect.signature/typing.get_type_hints out of per-call ctypes dispatch

These two introspection calls were recomputed on every invocation of
the ctypes caller closure (~79µs + ~91µs per call). Since the decorated
function's signature and type hints are immutable, compute them once at
decoration time and capture via closure.

Made-with: Cursor

* update ruff format

* update black format

---------

Co-authored-by: amd-ruitang3 <[email protected]>

* Make FlyDSL LDS checks architecture-aware and reduce tuner failure noise (#2732)

* Handle FlyDSL LDS limits and candidate failures

Use shared-memory-per-block queries to keep FlyDSL LDS checks architecture-aware, and surface candidate failures as concise runtime warnings so tuning can continue without noisy tracebacks.

Made-with: Cursor

* Keep tuner topk local per shape

Avoid mutating the shared topk value while post-processing one shape so later shape groups keep the intended candidate limit.

Made-with: Cursor

* fix lint

* Cache FlyDSL shared memory queries

Avoid repeated device property lookups while validating FlyDSL kernel configs by caching the default device selection and shared-memory-per-block queries.

Made-with: Cursor

* fix lint

* Update aiter/ops/flydsl/gemm_tune/flydsl_gemm_a8w8_bpreshuffle_common.py

Co-authored-by: Copilot <[email protected]>

* parse kernel name to select flydsl kernel

* fix black format error

* refine

---------

Co-authored-by: Copilot <[email protected]>
Co-authored-by: solin <[email protected]>

* 16x256 kernel (#2722)

Co-authored-by: Sergey Solo <[email protected]>

* rebase linear attn for new flydsl version (#2746)

* Replace unsafe uses of std::unordered_map with SynchronizedCache (#2221)

* Make AiterAsmKernel load hsaco on each GPU it is used on

* Replace unsafe uses of std::unordered_map with SynchronizedCache

* Fix Triton MoE GEMM shared memory exhaustion by reducing stage count (#2723)

* Fix Triton MoE GEMM shared memory exhaustion

- Reduce num_stages in kernel configs
- Lowered LDS usage to avoid shared memory OOR
- Fix triton.runtime.errors.OutOfResources errors in MoE GEMM kernels

* Fix: set num_stages=1 on gfx950 using get_arch() conditionally for gfx950 to ensure no bottlenecks for gfx942

* Add determinism for fused mul add test

* Format fused mul add test with black

* Annotate moe_sorting_dispatch_policy as int for fused_moe (#2639)

The type annotation bool was incorrect for moe_sorting_dispatch_policy, which
accepts int values. The @torch_compile_guard decorator uses these
annotations to generate PyTorch custom op schemas; with bool, PyTorch schema
enforcement casts any value to bool, so dispatch_policy=2 becomes bool(2)=True
(1), silently losing the intended policy. Using int allows callers to set
dispatch_policy=2 correctly.

Fixes: #2576

Signed-off-by: Tres Popp <[email protected]>
Co-authored-by: Tres Popp <[email protected]>

* fix moe splitk aot and jit (#2738)

* fix moe splitk aot and jit

* split moe aot to serveral libs base on tuned_moe configs

* update copyrights

* fix typo

* test shuffle as default and fix moe split jit

* Update quant.pyfix: add pack_dim to per_1x32_f4_quant for tl.dot_scaled RHS compatibility (#2704)

* Update quant.py

* Refactor per_1x32_f4_quant function signature

* Fix function definition formatting in quant.py

* Refactor per_1x32_f4_quant_for_dot_scaled definition

* Restore semantic.py to match main branch

* Flydsl align if else usage to be compatible with all versions (#2740)

* Add bf16 MLA decode kernel for gqa_ratio=64, qseqlen=1 (non-persistent) (#2729)

* Add bf16 MLA decode kernel for gqa_ratio=64, qseqlen=1 (non-persistent)

* black mla.py

* fix short kv len split error

* Support final LSE output in non-persistent MLA reduce kernel

* black mla.py

* ruff error

---------

Co-authored-by: minmengdie <[email protected]>

* CI: scope check signal artifact downloads to matching run (#2757)

Avoid repo-wide artifact searches in downstream workflows so check-signal can fetch the pre-checks signal without hitting the GitHub Actions API rate limit.

* feat: aiter whls nightly (#2514)

* feat: aiter whls nightly

* fix:

* CI: add docker username input for aiter release workflow (#2535)

* fix:

* fix: address review comments and improve nightly workflow
- Enable promote for PRs (devreleases) after tests pass
- Fix inputs context for schedule/PR events (use github.event.inputs)
- Add set -o pipefail to prevent tee masking test failures
- Add release_type validation in promote workflow
- Guard AWS credentials against fork PRs
- Remove S3 bucket details from summaries, show only index URLs
- Simplify dispatch inputs: single docker_image, python_version, gpu_archs
- Add build_py310/build_py312 controls to aiter-release workflow

* style: fix Black formatting in generate_summary.py

* fix: add tabulate dependency for test_activation.py in wheel tests

* feat: add ci:nightly label trigger with full pipeline including promote

- PR trigger via ci:nightly label runs Build → Test → Promote to nightlies
- release_type set to nightlies for labeled PRs (same as scheduled runs)
- Promotion no longer blocked for PRs, enables end-to-end validation

* fix: keys

* fix: requested

* fix: remove testcode

* Update: move generate_summary.py

---------

Co-authored-by: Xin Huang <[email protected]>

* CI: reduce retention for workflow artifacts (#2758)

Shorten retention periods for high-volume workflow artifacts so routine logs and shard metadata expire sooner while wheel artifacts remain available long enough for downstream consumers.

* CI: upgrade sglang downstream to v0.5.10 (#2753)

* CI: upgrade sglang downstream to v0.5.10 on MI35X/MI355

* CI: keep sglang v0.5.10 upgrade on MI325

* Update sglang_downstream.yaml

* CI: use isolated sglang workspace for downstream test

* fix(car): sglang prefill launch error kernel (#2745)

Signed-off-by: TennyWang1223 <[email protected]>
Co-authored-by: TennyWang1223 <[email protected]>

* Add unified attention support to bench_models (#2724)

Add sink and window support to mha handler

* Use AITER_CONFIGS for FlyDSL AOT defaults (#2756)

Align FlyDSL GEMM and MoE AOT precompile defaults with runtime config resolution, and update the FlyDSL dependency to the required version.


Made-with: Cursor

Signed-off-by: zhimding <[email protected]>

* fix fused_dynamic_mxfp4_quant_moe_sort_hip err in EP (#2759)

* Fix `test_moe_routing_sigmoid_top1_fused` reference implementation tie-breaking (#2750)

Replace `torch.topk` with `torch.argmax` + `torch.gather` in the reference
implementation. `torch.topk` doesn't guarantee stable indices for tied elements,
and its tie-breaking behaviour changed between ROCm 7.2.0 and 7.2.2, causing 10
tests to fail for `N=128`, where integer inputs produce many tied sigmoid
scores. `torch.argmax` always returns the first (leftmost) maximum, matching
`tl.argmax(..., tie_break_left=True)` in the Triton kernel.

* [fix](cache): add eps to avoid diving zero (#2763)

Co-authored-by: perzhang <[email protected]>

* [FlyDSL MOE] update a8w4 moe (#2726)

* update a8w4

* update gptoss csv

* update gptoss_fp4 prefill config

* update files format

* update fix with rws & update a8w4 kimi tune cfgs

* update

* update fix code style

* update code style

* fix ci

* revert fused_moe.py modifies

* revert a16w4

* add instances

* update ut & env var name

* rename files

* fix ci

* remove use_cfg

* remove tile m 16

---------

Co-authored-by: Lingpeng Jin <[email protected]>

* MI350 mla ps mode suppport nhead128,1 128,2 128,3 128,4 64,4 64,2 32,4 through kernel mla_a16w16_qh32_qseqlen4_gqaratio32_ps.co (#2727)

* MI350 mla ps mode suppport nhead128,1 128,2 128,3 128,4 64,4 64,2 32,4 through kernel hsa/gfx950/mla/mla_a16w16_qh32_qseqlen4_gqaratio32_ps.co

* del the useless code

* black error

* fix sparse test error

* update config (#2771)

* fix(ck_gemm): fix multi-arch build targeting and kernel dispatch across all CK GEMM modules (#2645)

* chip_info: add GFX_CU_NUM_MAP and get_build_targets()

* aiter/configs: migrate tuned GEMM CSVs to add gfx as first column

* csrc: fix gen_instances.py to filter by (gfx, cu_num) build targets

* aiter/ops: add gfx to runtime GEMM dispatch lookup keys

* aiter/utility: add gfx to GemmCommonTuner key and tune result output

* csrc, gradlib: add gfx to all GEMM tuner output keys

* op_tests: fix is_shape_tuned to filter by (gfx, cu_num)

* fix(configs): resolve model_configs merge conflicts and add gfx column

* op_tests: add CSV input, output saving, and stable iter counts to a8w8 GEMM test scripts

* fix(merge): resolve conflict in gemm_op_a4w4.py after main sync

The merge commit 6a18cd6e7 accidentally preserved conflict markers in
gemm_op_a4w4.py. Apply the gfx-aware dispatch fix (same pattern as
gemm_op_a8w8.py) — use (gfx, cu_num, M, N, K) key when the CSV has a
gfx column, fall back to (cu_num, M, N, K) for old CSVs.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(configs): add missing gfx column to dsv3 model_configs overrides

* op_tests: add bpreshuffle-csv entry point and skip_ck flag to test_gemm_a8w8

* op_tests: add gfx filter unit tests and repro CSVs for both GEMM modules

* fix(ck_gemm): key C++ dispatch map by (cu_num,M,N,K) to prevent multi-arch kernel collisions, share build_tune_dict helpers across all 9 CK GEMM modules

* op_tests/configs/gemm_codegen_gfx_filter.csv

* chip_info: split arch constants and env-only build targets into torch-free build_targets.py

* op_tests: fix repro CSV gfx942/304 kernels to be valid for M=1 and M=32

* chip_info: use bare import for build_targets to fix build context ModuleNotFoundErro

* docs: add gfx column to tuning CSV examples and update cu_num description in all 8 GEMM READMEs

* lint: apply black formatting and fix ruff violations in modified files

* lint: fix black/ruff violations in csrc gen_instances and gradlib

* fix(gemm_op_a8w8): eliminate StopIteration risk and use AITER_CONFIGS for defaults

* fix(chip_info): guard kernelId/kernelName lookups with .get() to avoid KeyError on malformed CSVs

* fix(base_tuner): add gfx legacy fallback to if branch of get_retune_gemm_list

* docs(test_gemm_codegen): fix comment reference for GFX_CU_NUM_MAP location

* fix(gemm_dispatch_utils): check HIP return codes in get_device_cu_num()

* fix(chip_info): add get_gfx_runtime() and fix GPU_ARCHS=native in get_build_targets()

* chore(configs): sync dsv3/kimik2 bf16 tuned gemm CSVs with main and add gfx column

* fix(op_tests): use get_gfx_runtime() in GEMM test files for correct arch detection

* fix(core): self-heal CSV dedup without requiring a re-run

* fix(chip_info): add shape and arch context to kernelId/kernelName skip warnings

* fix(chip_info): use logger.warning instead of print for kernel skip warnings

* style(chip_info): fix E402 import order after logger initialization

* fix(gemm_dispatch_utils): initialize device to -1 to clarify output-parameter intent

* test(test_gemm_codegen): fix Section 3 runtime dispatch tests to use live GPU

* fix(gemm_op_a8w8): remove duplicate get_gfx_runtime import

* docs(chip_info): fix build_tune_dict docstring for kernels_by_name fallback

* fix(gemm): extend C++ dispatch key with gfx arch string — (cu_num,M,N,K) → (gfx,cu_num,M,N,K)

* style(chip_info, test_gemm_codegen): apply black/ruff formatting

* feat: add PRETUNE_MODULES build flag to auto-tune GEMM shapes on live GPU

* feat(pretune): add run_tune_direct() and CLI for standalone retuning on installed aiter

* refactor(pretune): remove run_tune_direct wrapper, add input validation and dedup to CLI

* fix(pretune): suppress ruff F841/E402 false positives on eval-scope variable and path-dependent import

* refactor(pretune): extract _parse_module_list, fix silent skip of unsupported modules in setup.py path, add deduplication

* docs(pretune, setup, test_gemm_codegen): fix stale docstrings and add missing inline comments

* fix(pretune): write tuned results to source CSV, not ephemeral /tmp; add regression test

* setup.py: import pretune directly to avoid premature aiter package init

* pretune: add warmup API — check_tuning_coverage, warn_if_undertuned, warmup

* pretune: tune only missing model shapes in warmup(), not full CSV

* fix(pretune): remove vLLM-specific env var hint from warmup() warning

* revert: remove warmup API from pretune.py

* fix(tuners): clear module-level CSV caches in _clear_op_caches

* fix(build): add _parse_gpu_archs_env()

* fix(docs/tests): docstring accuracy, test coverage, and gfx-aware dedup

* fix(tests): route aiter logger to stdout in test_pretune to fix warning ordering

* fix(gemm_dispatch_utils): cache cu_num and gfx per device ID via SynchronizedCache

* tuning: use get_gfx_runtime() in tuner imports so live GPU arch is used instead of GPU_ARCHS env

* fix(configs): add missing gfx column to bf16 model_configs CSVs introduced during main merge

* raise error when having duplicate shape entries

* fix(configs): remove duplicate shape entries from a8w8_blockscale_bpreshuffle_tuned_gemm_qwen3.5_397b.csv

* resolve duplicated shapes

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Co-authored-by: Ying.Zhou2 <[email protected]>
Co-authored-by: Xin Huang <[email protected]>

* add triton fallback for mi455 gptoss & dsfp4 (#2657)

* add triton fallback for mi455 gptoss & dsfp4

* rm nk config

* fix rotary

* fix recompile issue (#2777)

* Fix fused_gemm_a8w8_blockscale_a16w16 unit test failures (#2766)

* Fix fused_gemm_a8w8_blockscale_a16w16 unit tests

* fix format with black

* remove guard and keeping num_stages as is - works

* walkaround invalid kernels in moe tunner (#2785)

* CI: auto-update split test FILE_TIMES (#2795)

* CI: auto-update split test FILE_TIMES

* chore: trigger pull_request checks

---------

Co-authored-by: gyohuangxin <[email protected]>
Co-authored-by: Xin Huang <[email protected]>

* [fix] remove glm5 triton tuned gemm (#2803)

* remove glm5 triton tuned gemm

* tuned

* add tuned bf16 gemm for qwen3next and qwen3.5 (#2799)

* add qwen3next qwen3.5 bf16 untuned gemm

Signed-off-by: ganyi <[email protected]>

* revert the bf16 template csv

Signed-off-by: ganyi <[email protected]>

---------

Signed-off-by: ganyi <[email protected]>

* [Perf][WIP]update qwen fmoe tuned configs (#2812)

* update qwen fmoe tuned configs

* fix typo

* CI: run SGLang downstream tests on MI355 (#2807)

* CI: run SGLang downstream tests on MI355

Switch the downstream workflow to the MI355 runner and mi35x image path so sglang exercises the gfx950 configuration instead of the MI325/mi30x path.

* Update sglang_downstream.yaml

* Update sglang_downstream.yaml

* CI: allow nightly check-signal to reuse Checks push runs (#2819)

Nightly Aiter Test runs look up pre-check signal artifacts by SHA, but the Checks workflow does not run with event=schedule. Skip the event filter for schedule-triggered workflows so nightly jobs can reuse the matching push-based Checks run instead of failing early in check-signal.

* [fix] fix compare error (#2805)

* fix compare error

* Apply suggestion from @Copilot

Co-authored-by: Copilot <[email protected]>

---------

Co-authored-by: Copilot <[email protected]>

* CI: log in to Docker before building aiter image (#2824)

Authenticate before the build so pulling the base image does not hit registry rate limits. Reuse the same Docker session for the later image push.

* [FLYDSL]: aiter flydsl if const_expr (#2776)

* [FLYDSL]: aiter flydsl if const_expr

* [FLYDSL]: black

* add tuner test suite (#2734)

* add tuner test suite

* Update op_tests/tuning_tests/test_mp_tuner_logic.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* add run_config  test

* fix tuned csv

* add missed test

* Update op_tests/tuning_tests/test_run_config.py

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fix format

* update test and  tuner

* fix format

* format

* update test

* format

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fix lse address compute (#2810)

* Add vcs_versioning as transitive dependency of setuptools_scm>=10 (#2834)

* Revert kimi2.5 fp4 tp4 moe tuned result on bs 32,64 (#2836)

* remove gemm tuning (#2838)

Signed-off-by: ganyi <[email protected]>

* disable import flydsl_gdr_decode (#2840)

* Xiaobing/gptoss small m (#2775)

* add small m hgemm

* update gptos config

* updata small_m_hgmm

* clear code

* code format

* fix code format

* remove moe_gemm_2stage.py change

* refact code

* recover 0 from SMALL_M_B_TO_LDS_WAVES_PER_EU_OPTIONS

* update gemm code

* refact code

---------

Co-authored-by: zhuyuhua-v <[email protected]>

* [CK_TILE] Fix bpreshuffle compile failure due to stale CShuffleEpilogueProblem arg (#2811)

* [fix] Remove stale TiledMMAPermuteN arg from CShuffleEpilogueProblem

* [fix] Remove stale TiledMMAPermuteN arg from blockscale CShuffleEpilogueProblem

* add static_assert for TiledMMAPermuteN in blockscale and moe_2stages

* update subproject commit for composable_kernel

* update flydsl version (#2802)

* update flydsl version
* fix version err

* CI: fix pre-check signal artifact lookup for PR reruns (#2848)

Resolve check-signal failures when labeled or rerun pull_request jobs get a new GitHub merge SHA. Download the checks-signal artifact from the matched Checks run instead of rebuilding the artifact name from the current workflow SHA.

* [Fix]fix moe tunner (#2831)

* CI: To fix prebuild image issue (#2847)

* Fix a8w8 flydsl tune (#2809)

* use flyc.compile
* add csv-driven mode covering mode_configs/configs a8w8_bpreshuffle csvs
Co-authored-by: solin <[email protected]>

* fix other lse addr compute issue (#2833)

* CI: align tuning test workflow with README (#2849)

* CI: add nightly tuning validation workflow

Split the PR #2734 tuning test plan into dedicated nightly CPU and GPU jobs, and make the CPU-only tuner infra tests importable without a ROCm runtime so the new validation workflow can run on ubuntu-latest.

* CI: align tuning test workflow with README

Redo the tuning test PR to match the README commands directly: keep the workflow manual-only, run the documented level01/tune_pipeline/run_config suites from a ROCm container, and drop the unrelated utility-layer changes from the PR scope.

* CI: switch tuning tests to MI35X runner

Run the manual tuning test workflow on the MI35X single-GPU runner and set GPU_ARCHS to gfx950 so the dispatched validation matches the requested hardware target.

* gqa ratio support in mha test (#2798)

* update

* update

* fix odd num head

* ci(release): add manylinux2_28+ROCm builder path with auditwheel gate (#2851)

Adds opt-in manylinux + ROCm wheel build path (use_manylinux=true) using pytorch/manylinux2_28-builder:rocm7.X images, with auditwheel repair + symbol-floor verification step. Default off so existing dispatches are unchanged. Fixes the libstdc++/glibc ABI mismatch tracked in #2843. Validated by test build #24761365935 — wheel passes manylinux_2_28 contract (GLIBCXX max 3.4.22, GLIBC max 2.28).

Co-authored-by: Peng Sun <[email protected]>

* add asm load kernel log (#2800)

* add asm load kernel log

* update according to review

* update log

* Update gfx942&gfx950 PA PS kernels and write stride_scale_page in asm_pa (#2796)

* clean code and reduce num_stages to 1 for large tile configs in fused_gemm_afp4wfp4_a16w16 to prevent LDS exhaustion with ASYNC_COPY (#2784)

* [TRITON] Add Gluon-optimized MoE Int8 SmoothQuant kernel for small K (#2441)

Move Gluon kernel to _gluon_kernels/gfx942/moe/ directory and refactor
K-dimension unrolling to use gl.static_range + tuple accumulation,
removing the UNROLL_TIMES <= 3 constraint. Raise Gluon dispatch
threshold to M >= 4096 for optimal performance.

Key optimizations:
- Manual LICM: A matrix, x_scale, and gammas pre-loaded outside N loop
- K-dimension loop fully unrolled via gl.static_range at AST level
- Explicit BlockedLayout + MFMA for optimal INT8 register usage
- SUB_BLOCK_SIZE_N=64 inner loop for large BLOCK_N

Co-authored-by: Claude Opus 4 <[email protected]>

* [TRITON] Reduce MHA UTs (#2612)

* Reduce tests for mha

* Remove single parametrized functions

* Remove single parametrized functions

* Lint

* Lint

* Address comments

* Fix UTs

* Address test failures

* Address test failures

* Address comments

* Fix CI failures

* Relax test_mha_with_sink bwd tolerance

---------

Co-authored-by: Xin Huang <[email protected]>
Co-authored-by: Lucas Santos <[email protected]>

* Add gfx942 Triton A8W8 blockscale GEMM configs for GLM-5 shapes for 70k in and 300 out (#2743)

Co-authored-by: root <[email protected]>

* docs: polish README with ecosystem, news, and performance highlights (#2859)

* docs: polish README with ecosystem, news, and performance highlights

- Replace GitHub-hosted image with local aiter_logo.png, center-aligned
- Add CI, Release, Docs, and GitHub stars badges
- Add News section with chronological blog posts and publications
- Add Ecosystem section with framework integration table (vLLM, SGLang,
  ATOM, JAX, and customer proprietary engines)
- Add performance highlights and supported hardware tables
- Refactor operators section to link to op_tests/ directory
- Polish description and feature list

docs: add aiter logo assets for README

* docs: add Opus section, MLA tutorial link, and fix release badge

- Add Opus lightweight C++ template section alongside FlyDSL and Iris
- Add MLA decode kernel tutorial to News section
- Change release badge to show version from shields.io, link to releases page

* docs: update badges and spacing in README header

- Remove stars badge, add last commit badge
- Add spacing between logo and badges

* docs: add v0.1.12.post1 release to News section

* docs: adjust spacing between logo and badges

* docs: widen spacing between logo and badges

* make rmsnorm quant fusion support gemma (#2853)

* gemma rmsnorm quant support

Signed-off-by: ganyi <[email protected]>

* change test

Signed-off-by: ganyi <[email protected]>

---------

Signed-off-by: ganyi <[email protected]>

* ci(release): add torch_pin + torch_index_url inputs for ABI-targeted release builds

The manylinux release path currently calls 'pip install torch' with no
version pin, picking up whatever wheel is latest on the auto-derived
download.pytorch.org/whl/rocmX.Y index at build time. That works for
nightlies but is fragile for tagged releases that need to be ABI-
compatible with a specific downstream container.

Concrete failure: AITER wheels built today against torch 2.11.0+rocm7.2
ImportError at runtime inside vllm/vllm-openai-rocm:v0.19.1, which
ships a custom torch 2.10 build. The 2.10 -> 2.11 transition changed
the c10::cuda::getCurrentCUDAStream masquerade alias surface; AITER
.so files (e.g. module_gemm_a8w8_blockscale.so) hit the missing
symbol when dlopened in the vllm container.

This change adds two optional, additive workflow inputs (workflow_dispatch
and workflow_call):

  - torch_pin: e.g. '2.10.0+rocm7.1'. Empty = latest (existing behavior).
  - torch_index_url: override the auto-derived index URL. Empty = legacy
    'https://download.pytorch.org/whl/rocmX.Y' from the builder image tag.

Default behavior is unchanged. When both inputs are empty the install
step runs exactly as today.

For v0.1.12.post2 release builds we will dispatch with:
  torch_pin=2.10.0+rocm7.1
  torch_index_url=https://download.pytorch.org/whl/rocm7.1

Validated end-to-end on a side branch: wheel built with these pins
loaded cleanly inside vllm/vllm-openai-rocm:v0.19.1 and ran DSR1
serving on both MI300X and MI355X.

Refs: #2843

* Revert "CI: run SGLang downstream tests on MI355" (#2873)

* Revert "CI: run SGLang downstream tests on MI355 (#2807)"

This reverts commit a3f54e3ce76b40177ac3f1ab53763ea8ee9d2bb9.

* Update sglang_downstream.yaml

* ci: rename aiter MI300X runners (#2872)

Replace the legacy aiter single- and multi-GPU runner labels with the linux-aiter-mi300x equivalents so CI jobs and runner metadata target the new MI300X fleet consistently.

* CI: raise atom-test accuracy step timeout to 90 minutes (#2876)

Align with longer ATOM server startup wait (45m) plus warmup and lm_eval.

* Add torch in gemm a16w16 tune (#2860)

* add torch,skinny gemm in bf16 gemm tuner

* fix format

* fix lint

* CI: run Triton workflow on MI35X only (#2871)

* CI: run Triton workflow on MI35X only

Remove the opt-in MI325 Triton path and its PR label guidance so the Triton workflow always runs on MI35X. Keep the PR welcome comment aligned with the simplified CI behavior.

* MLA PS mode support nhead8,2 in MI308 (#2852)

* MLA PS mode support nhead8,2 in MI308

* nhead8,2 through m16x1_16x4

* delete redundant kernel

* fix the comment

---------

Co-authored-by: Xu, Shengnan <[email protected]>

* Dev/aot fix (#2856)

---------

Co-authored-by: coderfeli <[email protected]>

* Update kimik2 FP4 tuned fMoE config (#2845)

* Update kimik2 FP4 tuned fMoE config with 256 CU tuning results

Made-with: Cursor

* Fix kernel names for kimik2 FP4 token=8 expert=385 topk=9 config entry

---------

Co-authored-by: okorzh-amd <[email protected]>

* Fix sliding window mtp (#2829)

* fix(pa): port sliding window mtp fixes to main

Reapply the sliding-window MTP decode, PS reduce, and KV_BLOCK_SIZE=1024 fixes on top of the latest main so the change can be reviewed and merged from a branch with shared history.

Made-with: Cursor

* fix fallback

* fix(pa): Use FlyDSL PS reduce for sliding-window MTP

Signed-off-by: fsx950223 <[email protected]>
Made-with: Cursor

* fix(pa): Move Gluon decode imports to module top

Signed-off-by: fsx950223 <[email protected]>
Made-with: Cursor

* fix regression

---------

Signed-off-by: fsx950223 <[email protected]>

* [DO NOT MERGE] CI TESTS (#2894)

* CI: Temporarily running the build jobs on linux-aiter-mi300x-1 due to network issues (#2895)

* CI: Fix Aiter installation issues in sglang downstream test (#2897)

* CI: add opt-in MI300X Triton jobs for PRs and main (#2883)

Keep MI35X as the default Triton PR path, add ci:triton-300x to start extra MI300X jobs on PRs, and run both architectures on main. Update the PR welcome comment to document the new label and main-branch behavior.

* Revert "CI: Temporarily running the aiter build on linux-aiter-mi300x-1 due to network issues." (#2899)

* Revert "[DO NOT MERGE] CI TESTS (#2894)"

This reverts commit 0f059acf89220ecbf52919e20798e7e86fb3acbb.

* Update vllm_benchmark.yaml

* add optimized prefill gdn kernels for qwen3_5 (#2686)

* add optimized prefill gdn kernels for qwen3_5

* refine code style

* add ssm_state vk_layout kernels for vllm support

* add default turnoff for triton autotune

* Introduce asm fmoe kernels that do not require bf16->fp8 quantization (#2262)

* Introduce asm fmoe kernels that do not require bf16->fp8 quantization

* Update quantization division precision to be closer to IEEE correctness

* Add transpose_scale flag

* Update kernels with fixed s_waitcnt

* Add 16x128 kernel merged with quantization

* Remove legacy code

* Remove one more redundant line

* Revert changes to sub_X_cnt calulations for fmoe asm

* Update the tuner to support x_bf16 kernel

* Update pandas interface

* Fix formatting

* Generate config with the new tuner

* Update base tuner to support merging csv files without strict column matching

* Fix formatting

* Fix core.py to handle columns merge

* Fix formatting

---------

Co-authored-by: Sergey Solo <[email protected]>

* Revert "Fix sliding window mtp (#2829)" (#2909)

This reverts commit 6b8ce4ec3423441ad0a2f072d50f498ac711714c.

Co-authored-by: perzhang <[email protected]>

* fix(fmha): support >4GB KV cache in batch prefill via runtime dispatch (#2893)

* test: expand test_batch_prefill_large_kvcache for >4GB KV cache overflow

Rewrite test_batch_prefill_large_kvcache to validate the per-tile SRD
rebase fix for >4GB KV caches across all page sizes, dtypes, and
attention configurations:

- Add page_size=1 and 16 (page_size < kN0, exercises rebase path)
- Add GQA (16, 8) in addition to MHA (8, 8)
- Add causal masking with CK-compatible attn_mask for SDPA reference
- Use full KV cache (4.5GB) with pages spanning the overflow boundary
- Use torch SDPA as reference (memory-efficient backend, no score
  matrix materialization)
- Add scatter_pages parameter (False only; True for future
  global_load_lds flat addressing)
- Add GPU memory check to skip configs that exceed HBM capacity

Test matrix: 24 cases (3 page_sizes × 2 dtypes × 2 causal × 2 GQA × 1 scatter)

* test: add GPU sync after CK kernel in large_kvcache test

Add torch.cuda.synchronize() after CK kernel launch in
test_batch_prefill_large_kvcache to ensure all async GPU work
completes before memory is freed between tests.

Without this sync, repeated allocate/free cycles of large KV cache
buffers (~20GB) with mixed dtype (bf16→fp8) can trigger GPU page
faults when the HIP memory allocator reuses virtual addresses that
are still referenced by pending async GPU work. The fault manifests
as VM_L2_PROTECTION_FAULT at address 0x0 (NULL), causing GPU reset
and kernel soft lockup.

* feat(fmha): runtime dispatch for >4GB KV cache in batch prefill

Add use_64bit_load to batch prefill traits and runtime overflow detection.
When page_block_size < 128 and max_page_byte_offset > INT32_MAX, dispatch
to the flat 64-bit load kernel variant for correctness.

Also add vectorized KV layout coverage to test_batch_prefill_large_kvcache.

* fix: remove unused k_vector_size variable in large_kvcache test

* fix(mha): improve batch_prefill TORCH_CHECK error message for >4GB KV cache

Include page_size, num_pages, and dtype in the error message when kernel
dispatch fails. Add hint about CDNA3+ GPU requirement when KV cache
exceeds 4GB with page_size < 128.

* test: update scatter_pages comment in large_kvcache test

The comment incorrectly stated scatter_pages=True was "expected to FAIL".
This is no longer true — the flat 64-bit load path handles scattered
pages correctly. Update to describe the test's purpose instead.

* fix(mha): widen batch_prefill 64-bit threshold to total KV bytes

The previous check used (num_total_pages - 1) * batch_stride * element_size
which measures the last-page base offset, missing within-page offsets and
producing an off-by-one at exactly INT32_MAX (the largest representable
SRD voffset). Switch to total KV cache footprint (num_total_pages *
batch_stride * element_size > INT32_MAX) so within-page reads on the last
page are covered, and drop the redundant num_total_pages > 1 guard since
single-page configs trivially fit in 32 bits.

Also unify wording: 4GB → 2GB (INT32_MAX byte offset for SRD voffset),
matching CK's TwoGB convention. The actual hardware bound has always been
2GB; the prior comments were imprecise.

Found during batch prefill template dispatch review.

* docs(mha): unify >2GB wording in batch_prefill error and test

The 4GB number in the TORCH_CHECK error message and the test comment was
imprecise — the actual SRD voffset bound is 2GB (INT32_MAX). Update both
to match the threshold check and CK's TwoGB convention.

Found during batch prefill template dispatch review.

* refactor(mha): drop wrapper-side use_64bit_load; let CK dispatcher decide

The wrapper hardcoded kN0_min = 128 to compute the >2GB KV cache
predicate, which leaked CK tile config into aiter and would silently
break if a new arm with bn0 != 128 were added. The CK auto-generated
dispatcher now decides per-arm using its own compile-time bn0 and
per-dtype kElementBytes, so the wrapper just forwards args.

Remove the `use_64bit_load` runtime field from `mha_batch_prefill_traits`,
the parameter from `get_mha_batch_prefill_traits()`, and the entire
predicate computation block from the dispatcher call site. Bumps CK
submodule to pull in the matching codegen change.

* chore(mha): bump CK + update wrapper wording for kUseGlobalLoad rename

Bumps 3rdparty/composable_kernel to dd8d293ea (refactor(fmha): batch
prefill review polish — assert helper + setter guards) which builds on
the prior 99a3ca9af kUseGlobalLoad rename.

Wrapper-side updates to match:

* csrc/cpp_itfs/mha_fwd_batch_prefill.cu: rename "64-bit-load" wording
  in the per-arm dispatcher comment to "kUseGlobalLoad" so the wrapper
  comment matches the CK-side identifier. Also drops the trailing
  `false /* skip_min_seqlen_q */` argument from the
  get_mha_batch_prefill_traits call to match the upstream CK API
  signature change.

* csrc/py_itfs_ck/mha_batch_prefill_kernels.cu: change the >2GB error
  message from "page_size < 128" to "page_size < kN0" so the diagnostic
  tracks the tile-size constant rather than a magic number.

* op_tests/test_batch_prefill.py (test_batch_prefill_large_kvcache):
  three documentation enhancements with no behavior change —
  - explain why qo_len caps at 128 (causal) / 1024 (non-causal): the
    causal cap is a math-backend cliff for the SDPA reference, not a
    kernel limit;
  - explain that the +256 padding on kv_page_indices is a batch_prefill
    ABI requirement (kernel may speculatively read up to bn0=256
    entries past the last valid page index);
  - expand the torch.cuda.synchronize comment to call out the
    misattribution failure mode and GPU-reset cascade risk.

* test(fmha): parametrize test_batch_prefill_large_kvcache over batch_size {1, 4}

Adds multi-batch coverage to the >2GB KV cache regression test.

The previous single-batch coverage left the kernel's per-sequence SRD
rebase path unexercised: with cu_seqlens_q=[0, qo_len] and kv_indptr=
[0, num_blocks], the kernel never walks the indptr to reposition K/V
SRDs across batch boundaries. After the kUseGlobalLoad rename and the
new positive static_assert(kUseGlobalLoad_) calls in update_physical_pages
and set_page_stride_elements, we want a regression that catches any
boundary-crossing SRD bug -- the failure mode no single-batch test can
detect (one batch correct, others wrong).

batch_size=4 partitions the >2GB page pool across 4 sequences (last
sequence absorbs the remainder), exercising 3 cross-batch SRD transitions.
The SDPA reference is computed per-batch and concatenated; per-iteration
free + empty_cache keeps peak memory at one batch's worth.

Verified on:
  - gfx950 (smci355-gfx950, MI355X): 160 passed, 32 skipped
  - gfx942 (smc300x-clt, MI308X):    160 passed, 32 skipped

Skips are the existing vectorized + page_size=1 incompatibility
(3D tensor layout), now 16 per batch_size value.

---------

Co-authored-by: Xin Huang <[email protected]>

* Fix top_k_per_row_prefill err when batched_token_numm > 4096 (#2901)

* retune a8w8_blockscale_bpreshuffle_gemm for MI308 (#2896)

* revert gptoss tuned config (#2904)

---------

Co-authored-by: zhuyuhua-v <[email protected]>

* mHC: Optimize mhc_pre performance in small M (#2915)

* mHC: Optimize mhc_pre performance in small M (add tileN=16 on mhc_pre_gemm_sqrsum  && add splitk on mhc_pre_big_fuse)

* update test

* fix(mha_bwd): pass independent strides for do in _bwd_preprocess (#2808)

* fix(mha_bwd): pass independent strides for do in _bwd_preprocess

- adding independent `stride_do_b/h/m/k` parameters to `_bwd_preprocess`
  and addressing dO with them;
- passing `*do_strides` (already computed in the wrapper) alongside
  `*o_strides` when launching the preprocess kernel.

* pass independent strides for flash_attn_fused_backward kernel

* fix typo

* Fix batched_gemm_a8w8 correctness for ASYNC_COPY + gfx950 UT (#2867)

* [Triton]: Add MoE a16w4 (#2770)

* [Triton]: Add MoE a16w4

* Fix Black issue

* Removed x scales and improved arch checks in unit test

* Added benchmark

* Fixed PR review issues

* PR review comments fixes

---------

Co-authored-by: Rahul Batra <[email protected]>

* test(moe_2stage): add csv-driven mode covering model_configs fmoe csvs (#2825)

---------

Signed-off-by: zhimding <[email protected]>
Signed-off-by: zhimding <[email protected]>

* fix mhc device (#2916)

* CI: add standalone OPUS test workflow (#2928)

* CI: log in before starting OPUS test container

Authenticate with the Docker registry before `docker run` so OPUS test jobs can pull the image reliably across runners.

* CI: add docker login before ATOM base image pull (#2931)

* CI: add docker login before ATOM base image pull

Authenticate with the Docker registry before pulling the ATOM base image so the workflow can fetch the container reliably across runners.

* CI: Use build-only-aiter runner to build Triton wheels (#2934)

* fea(car): support custom group device (#2703)

* fea(car): support custom group device

Signed-off-by: TennyWang1223 <[email protected]>

* [fix]: test script code format

Signed-off-by: TennyWang1223 <[email protected]>

* fea(car): support multi communication groups entity

Signed-off-by: TennyWang1223 <[email protected]>

* fea(ag): support multi group allgather

Signed-off-by: TennyWang1223 <[email protected]>

* fix: test script format

Signed-off-by: TennyWang1223 <[email protected]>

* fea(car): add reduce_scatter interface

Signed-off-by: TennyWang1223 <[email protected]>

* fix(car): custom group config

Signed-off-by: TennyWang1223 <[email protected]>

* fix: custom comm group set method

Signed-off-by: root <[email protected]>

---------

Signed-off-by: TennyWang1223 <[email protected]>
Signed-off-by: root <[email protected]>
Co-authored-by: TennyWang1223 <[email protected]>
Co-authored-by: root <[email protected]>

* [FLYDSL]: update version to 0.1.5.dev504, fix bug in if-else dynamic grammer (#2935)

* [CK] Add StreamLLM sink token support for batch_prefill pipeline (#2794)

* [CK] Add StreamLLM sink token support for batch_prefill pipeline

Update CK submodule to ROCm/rocm-libraries#6479 (commit feea6be) which
makes kHasSink_ a real template parameter in fmha_fwd_batch_prefill_traits_,
enabling _sink/_nsink kernel variant codegen for batch_prefill.

AITER-side changes thread sink_size through the full call chain:

Python (aiter/ops/mha.py):
- Add sink_size: int = 0 to mha_batch_prefill_func, _mha_batch_prefill,
  mha_batch_prefill stub, and cmdGenFunc_mha_batch_prefill
- Use has_effective_sink = sink_size > 0 and (causal or has_window_mask)
  for _sink/_nsink module name selection, matching C++ mask logic

C++ interface (csrc/):
- mha_batch_prefill_traits: expose has_sink parameter (was hardcoded false)
- mha_fwd_batch_prefill.cu: derive has_sink = args.sink_size > 0
- mha_batch_prefill_kernels.cu: add int sink_size param, include it in
  mask_identify string, set args.sink_size = mask.sink, zero-initialize
  fmha_batch_prefill_args{} to avoid UB
- PyBind (rocm_ops.hpp) and declaration (torch/mha_batch_prefill.h):
  add sink_size positional parameter after window_size_right

Semantics clarified:
- sink_size: number of first KV tokens always attended (sink phase loop)
- sink_ptr[nhead]: fixed logit for a virtual sink token in softmax
  (null -> -inf, non-null -> user value); independent of sink_size
- window_size_left=L means k in [abs_q-L, abs_q] (L+1 tokens), verified
  via code derivation (block_masking.hpp) and discriminating tests

Verified:
- No-sink paths numerically correct vs torch reference (max_diff<0.004)
- sink_ptr virtual token semantics correct (max_diff<0.004)
- window=1024 + sink_size=4 + sink_ptr: max_diff=0.000488

* [test] Add StreamLLM sink token tests for batch_prefill

Add test_batch_prefill_sink pytest function and supporting helpers
to op_tests/test_batch_prefill.py:

- ref_masked_attention_with_sink: torch reference implementing
  sink semantics (first sink_size KV positions always valid,
  sink_ptr virtual token appended to softmax attention matrix)

- run_batch_prefill_sink: runs both reference and CK kernel,
  compares with get_tolerances() thresholds

- test_batch_prefill_sink: parametrized over:
    batch_size=[1,2], page_size=16, head_dim=128
    num_qo_heads/num_kv_heads=[(8,1),(4,4)] (GQA + MHA)
    qo_len=[32,128]
    (window_left, kv_len)=[(128,512),(1024,2048)]  <- real gap in both
    sink_size=[4,16]
    sink_ptr_value=[None, 0.0, 2.0]
    dtype=[bfloat16, float16]

Verified manually with batch=1 GQA 8/1 window=128 sink=4 ptr=2.0,
batch=2 MHA 4/4 window=1024 sink=16 ptr=None, and sink_ptr=0.0.

* [style] Black format op_tests/test_batch_prefill.py

* [fix] Address Copilot review on batch_prefill sink PR

- aiter/ops/mha.py: add missing sink_size parameter to
  mha_batch_prefill_fake_tensors so its signature matches the real
  mha_batch_prefill op; without this torch.compile / fake-tensor mode
  raises TypeError when invoking the op.

- op_tests/test_batch_prefill.py: vectorize the StreamLLM reference
  mask construction. The previous double Python loop did per-element
  assignment into a CUDA tensor, triggering O(seqlen_q * seqlen_k)
  GPU sync points (262144 at seqlen_k=2048) and would time out the
  parametrized tests. Replace with broadcasted index tensors and a
  single masked_fill_.

* [test] Wire StreamLLM sink scenarios into CI __main__ block

CI invokes test files via `python3 "$file"`, which only runs the
__main__ block; pytest functions like test_batch_prefill_sink were
therefore never exercised in CI.

Add a second __main__ block at the end of the file that runs
run_batch_prefill_sink over a small representative parameter sweep
(2 window/kv combos x 2 sink_ptr settings, sink_size=4, bf16). The
helpers are defined after the original __main__, so a separate
trailing __main__ block is the minimal-blast-radius way to keep
both invocations independent.

* [CK] Bump submodule to include StreamLLM sink for batch_prefill

Update CK submodule from 08792e0b3 to d22aafb48 to pull in
[CK][fmha] Add StreamLLM sink support to batch_prefill pipeline (#6479).

* Set RNG seed in Triton tests (#2921)

* [quant] refactor hip kernels (#2932)

---------

Signed-off-by: zhiding512 <[email protected]>
Signed-off-by: zhimding <[email protected]>
Signed-off-by: Tres Popp <[email protected]>
Signed-off-by: TennyWang1223 <[email protected]>
Signed-off-by: zhimding <[email protected]>
Signed-off-by: ganyi <[email protected]>
Signed-off-by: fsx950223 <[email protected]>
Signed-off-by: root <[email protected]>
Co-authored-by: Xin Huang <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: gyohuangxin <[email protected]>
Co-authored-by: BingYuan.Zhou <[email protected]>
Co-authored-by: solin <[email protected]>
Co-authored-by: lalala-sh <[email protected]>
Co-authored-by: Vinayak Gokhale <[email protected]>
Co-authored-by: RuibinCheung <[email protected]>
Co-authored-by: ruanjm <[email protected]>
Co-authored-by: Peng <[email protected]>
Co-authored-by: Peng Sun <[email protected]>
Co-authored-by: yzhou103 <[email protected]>
Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: TennyWang1223 <[email protected]>
Co-authored-by: Nicholas Susanto <[email protected]>
Co-authored-by: Lukasz Burzawa <[email protected]>
Co-authored-by: amd-ruitang3 <[email protected]>
Co-authored-by: Su Ann Chong <[email protected]>
Co-authored-by: Elton <[email protected]>
Co-authored-by: Jiayun <[email protected]>
Co-authored-by: Stig-Arne Grönroos <[email protected]>
Co-authored-by: amd-ruitang3 <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Sergey Solovyev <[email protected]>
Co-authored-by: Sergey Solo <[email protected]>
Co-authored-by: Yutao Xu <[email protected]>
Co-authored-by: Dragan Mladjenovic <[email protected]>
Co-authored-by: Nidal Danial <[email protected]>
Co-authored-by: Nico Holmberg <[email protected]>
Co-authored-by: Tres Popp <[email protected]>
Co-authored-by: GeisYaO <[email protected]>
Co-authored-by: Xudong Yuan <[email protected]>
Co-authored-by: fangche123 <[email protected]>
Co-authored-by: minmengdie <[email protected]>
Co-authored-by: Kiran Thumma <[email protected]>
Co-authored-by: TennyWang1223 <[email protected]>
Co-authored-by: lucas-santos-amd <[email protected]>
Co-authored-by: la <[email protected]>
Co-authored-by: Bruno Mazzotti <[email protected]>
Co-authored-by: PerryZhang01 <[email protected]>
Co-authored-by: perzhang <[email protected]>
Co-authored-by: Zzz9990 <[email protected]>
Co-authored-by: Lingpeng Jin <[email protected]>
Co-authored-by: eppaneamd <[email protected]>
Co-authored-by: HaonanWang98 <[email protected]>
Co-authored-by: Pleaplusone <[email protected]>
Co-authored-by: JaxChen29 <[email protected]>
Co-authored-by: Petr Kurapov <[email protected]>
Co-authored-by: XiaobingZhang <[email protected]>
Co-authored-by: zhuyuhua-v <[email protected]>
Co-authored-by: Yi DING <[email protected]>
Co-authored-by: Felix Li <[email protected]>
Co-authored-by: slippedJim <[email protected]>
Co-authored-by: jian.wu <[email protected]>
Co-authored-by: Pedram Ghazi <[email protected]>
Co-authored-by: root <[email protected]>
Co-authored-by: carlushuang <[email protected]>
Co-authored-by: Xu, Shengnan <[email protected]>
Co-authored-by: Oxana Korzh <[email protected]>
Co-authored-by: okorzh-amd <[email protected]>
Co-authored-by: who who who <[email protected]>
Co-authored-by: yijin <[email protected]>
Co-authored-by: Jeff Huang <[email protected]>
Co-authored-by: chuanbowang2026 <[email protected]>
Co-authored-by: rahulbatra85 <[email protected]>
Co-authored-by: Rahul Batra <[email protected]>
Co-authored-by: root <[email protected]>
Co-authored-by: Linjun-AMD <[email protected]>
demonsan added a commit that referenced this pull request Apr 30, 2026
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.
Liang-jianhao97 pushed a commit that referenced this pull request May 7, 2026
demonsan added a commit that referenced this pull request May 9, 2026
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)
demonsan added a commit that referenced this pull request May 18, 2026
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)
demonsan added a commit that referenced this pull request May 20, 2026
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)
demonsan added a commit that referenced this pull request May 25, 2026
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)
demonsan added a commit that referenced this pull request May 27, 2026
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)
valarLip pushed a commit that referenced this pull request May 27, 2026
* add opus gemm invoke support

Signed-off-by: blyu <[email protected]>
(cherry picked from commit 0758429e18b07de3ffb36a327e45c482af4c4542)

* fix wrong mma dispatch

Signed-off-by: blyu <[email protected]>
(cherry picked from commit ae6181962c1533046ee050560b139058bbeda0a5)

* optimize compile process and timing

Signed-off-by: blyu <[email protected]>
(cherry picked from commit 224de199c7113d16c0a45711ebadaa085346f5f6)

* add more bf16 opus gemm instance and support perf tune

Signed-off-by: blyu <[email protected]>
(cherry picked from commit 75125b80a2a44f8a44e75296297cccb657b0c97d)

* remove wrong instance and fix accuracy problem in pipeline

Signed-off-by: blyu <[email protected]>
(cherry picked from commit 490bfd3657fe0e932d5ae1942507f60c05878f2e)

* add more small tile size for bf16 gemm

Signed-off-by: binglue.lyu <[email protected]>
(cherry picked from commit 686dd5150fe5db76e7179e3030273aa0d5ba73fd)

* add a16w16 splitk kernel instance

Signed-off-by: demonsan <[email protected]>
(cherry picked from commit 77fb3599ef62b69bfd8595a0af4e44739a13a20c)

* refactor opus gemm invoke method

Signed-off-by: demonsan <[email protected]>
(cherry picked from commit f549720855df861c2368606e9e0bfb5129f0b62a)

* feat(opus): add gemm_a16w16_opus with CSV lookup + untuned shape autolog

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 a019d1eb9ded56739648a1f6c8928b03c58b46dc)

* feat(opus): runtime dispatch = CSV-baked lookup + heuristic fallback

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 e9c590172e94b6670deda599b29c02990de56961)

* refactor(opus): drop deepgemm aggregate entry, keep per-dtype Python 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 1e94e845ff551c1b40853bbfb68dd0ce0b4b74be)

* docs(opus): add a16w16 user-facing README

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 8792254519e7a2465679978563262d74b8abd3dc)

* update opus a16w16 gemm config

Signed-off-by: demonsan <[email protected]>
(cherry picked from commit 47566cab6a53ec3849132bba68324165d2bf4f52)

* feat(opus): outdtype-aware splitk reduce + tuner/codegen

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 2214d51134d4f8eeb3e0a716aaeb5172ea1e4144)

* disable 2d+batch>1 pattern input, must be 3D

Signed-off-by: demonsan <[email protected]>
(cherry picked from commit 3a0acfb1aef67bfbd071ffd74c964f25dfc3fd8b)

* support bf16 row bias and update readme

Signed-off-by: demonsan <[email protected]>
(cherry picked from commit d1dc94490e353c78a895a051da00cf3453467d68)

* fix(opus): resolve ruff lint errors in opus_gemm_tune

- 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 4132bcce4c184e8b746a3735b007bc9e4f7e2b75)

* chore(opus): black auto-format

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 5e0b3ad3500fe58f8491e01ab0b39e97e796903c)

* feat(opus): gfx950-only guard with per-arch dispatch scaffolding

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 8988ce94ab794e79431dafecd0345cae6de8d6ed)

* perf(opus): 54% faster JIT build via fused host TU + per-file RTC flag

`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 c0b542dc5693f62537b0b2edacc071e012e23956)

* perf(opus): -13% more JIT build via torch removal (PR #2932 pattern)

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 9e4ed3268c2f712c477f39883bdfb9ebf3572672)

* perf(opus): -28% more JIT build via dispatcher torch removal + flat-array 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 217094be3f853aeb90683ec54ec1907336d079ed)

* perf(opus): split splitk_reduce_kernel into dedicated TU + device-pass 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 e9cb887f7230672b95dcfa1a9f970c02db5298a3)

* perf(opus): unroll tiled_mma_adaptor MMA-tile loops to eliminate SGPR 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 25f224f17cb5fc922d8afaf62e354b3e87498e0a)

* add more instances

Signed-off-by: demonsan <[email protected]>
(cherry picked from commit 917da0bd78336475842f8aef7f0cbe0002f91ffb)

* fix(opus): cache splitk workspace to make hipgraph + tuner work

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 ede232bea8cfbda6586addc1eb6db6590b9290df)

* docs(skills): add opus-module-build-optimization skill

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 ff05e5dec0b2d59f81a3e354c7f1c40c8b8bcede)

* refactor(opus): use opus::*_id() wrappers in pipeline files; trim hip_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)

* chore(opus): keep only the gemm end-to-end test

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)

* fix(opus): warn-and-stub on non-gfx950 to stop import cascade

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)

* chore(opus): black auto-format

Format only; no logic change.

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 6483affdd5edc87d2ab69f67f9d6162b226ec40b)

* feat(opus): add opus as libtype backend in GemmTuner and tuned_gemm

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)

* fix(opus): change bias convention from [M] per-row to [N] per-output-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)

* chore(opus): black auto-format

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 23e5674ce5f042af8c77d62be1079b538e917e1a)

* fix(opus): shrink g_a/g_b num_records by k_start in flatmm_splitk

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)

* feat(opus): add HAS_OOB compile-time guard for tail boundary handling

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]>

* feat(opus): XCD swizzle + cache control for a16w16

- 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]>

* chore(opus): route tuned-CSV lookup through global aiter/configs/

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]>

* feat(opus): subset compile via CSV + sidecar

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]>

* feat(opus): heuristic returns kid; propagate has_bias

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]>

* feat(opus): gradlib tuner integration + safety gates

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]>

* feat(opus): persistent (M-outer + XCD swizzle) a16w16 pipeline

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]>

* chore(opus): drop kspl experimental pipeline

Co-authored-by: Cursor <[email protected]>

* fix(opus): lock sidecar+build, reset env+versioner to prevent mp tune races

Co-authored-by: Cursor <[email protected]>

* feat(opus): a16w16 mono-tile pipeline + traits + tuner integration

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).

* tune(gemm): add kimi bf16 + refresh dsv4 bf16 tuned configs (no hipblaslt)

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]>

* chore(opus): black auto-format

Co-Authored-By: Claude Opus 4 <[email protected]>

* tune(gemm): preempt bf16 dedup conflict by propagating kimi wins

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]>

---------

Signed-off-by: blyu <[email protected]>
Signed-off-by: blyu <[email protected]>
Signed-off-by: blyu <[email protected]>
Signed-off-by: binglue.lyu <[email protected]>
Signed-off-by: demonsan <[email protected]>
Co-authored-by: blyu <[email protected]>
Co-authored-by: blyu <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Claude Opus 4 <[email protected]>
demonsan added a commit that referenced this pull request May 28, 2026
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)
valarLip pushed a commit that referenced this pull request May 28, 2026
* add opus gemm invoke support

Signed-off-by: blyu <[email protected]>
(cherry picked from commit 0758429e18b07de3ffb36a327e45c482af4c4542)

* fix wrong mma dispatch

Signed-off-by: blyu <[email protected]>
(cherry picked from commit ae6181962c1533046ee050560b139058bbeda0a5)

* optimize compile process and timing

Signed-off-by: blyu <[email protected]>
(cherry picked from commit 224de199c7113d16c0a45711ebadaa085346f5f6)

* add more bf16 opus gemm instance and support perf tune

Signed-off-by: blyu <[email protected]>
(cherry picked from commit 75125b80a2a44f8a44e75296297cccb657b0c97d)

* remove wrong instance and fix accuracy problem in pipeline

Signed-off-by: blyu <[email protected]>
(cherry picked from commit 490bfd3657fe0e932d5ae1942507f60c05878f2e)

* add more small tile size for bf16 gemm

Signed-off-by: binglue.lyu <[email protected]>
(cherry picked from commit 686dd5150fe5db76e7179e3030273aa0d5ba73fd)

* add a16w16 splitk kernel instance

Signed-off-by: demonsan <[email protected]>
(cherry picked from commit 77fb3599ef62b69bfd8595a0af4e44739a13a20c)

* refactor opus gemm invoke method

Signed-off-by: demonsan <[email protected]>
(cherry picked from commit f549720855df861c2368606e9e0bfb5129f0b62a)

* feat(opus): add gemm_a16w16_opus with CSV lookup + untuned shape autolog

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 a019d1eb9ded56739648a1f6c8928b03c58b46dc)

* feat(opus): runtime dispatch = CSV-baked lookup + heuristic fallback

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 e9c590172e94b6670deda599b29c02990de56961)

* refactor(opus): drop deepgemm aggregate entry, keep per-dtype Python 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 1e94e845ff551c1b40853bbfb68dd0ce0b4b74be)

* docs(opus): add a16w16 user-facing README

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 8792254519e7a2465679978563262d74b8abd3dc)

* update opus a16w16 gemm config

Signed-off-by: demonsan <[email protected]>
(cherry picked from commit 47566cab6a53ec3849132bba68324165d2bf4f52)

* feat(opus): outdtype-aware splitk reduce + tuner/codegen

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 2214d51134d4f8eeb3e0a716aaeb5172ea1e4144)

* disable 2d+batch>1 pattern input, must be 3D

Signed-off-by: demonsan <[email protected]>
(cherry picked from commit 3a0acfb1aef67bfbd071ffd74c964f25dfc3fd8b)

* support bf16 row bias and update readme

Signed-off-by: demonsan <[email protected]>
(cherry picked from commit d1dc94490e353c78a895a051da00cf3453467d68)

* fix(opus): resolve ruff lint errors in opus_gemm_tune

- 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 4132bcce4c184e8b746a3735b007bc9e4f7e2b75)

* chore(opus): black auto-format

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 5e0b3ad3500fe58f8491e01ab0b39e97e796903c)

* feat(opus): gfx950-only guard with per-arch dispatch scaffolding

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 8988ce94ab794e79431dafecd0345cae6de8d6ed)

* perf(opus): 54% faster JIT build via fused host TU + per-file RTC flag

`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 c0b542dc5693f62537b0b2edacc071e012e23956)

* perf(opus): -13% more JIT build via torch removal (PR #2932 pattern)

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 9e4ed3268c2f712c477f39883bdfb9ebf3572672)

* perf(opus): -28% more JIT build via dispatcher torch removal + flat-array 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 217094be3f853aeb90683ec54ec1907336d079ed)

* perf(opus): split splitk_reduce_kernel into dedicated TU + device-pass 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 e9cb887f7230672b95dcfa1a9f970c02db5298a3)

* perf(opus): unroll tiled_mma_adaptor MMA-tile loops to eliminate SGPR 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 25f224f17cb5fc922d8afaf62e354b3e87498e0a)

* add more instances

Signed-off-by: demonsan <[email protected]>
(cherry picked from commit 917da0bd78336475842f8aef7f0cbe0002f91ffb)

* fix(opus): cache splitk workspace to make hipgraph + tuner work

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 ede232bea8cfbda6586addc1eb6db6590b9290df)

* refactor(opus): use opus::*_id() wrappers in pipeline files; trim hip_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)

* chore(opus): keep only the gemm end-to-end test

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)

* fix(opus): warn-and-stub on non-gfx950 to stop import cascade

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)

* chore(opus): black auto-format

Format only; no logic change.

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 6483affdd5edc87d2ab69f67f9d6162b226ec40b)

* feat(opus): add opus as libtype backend in GemmTuner and tuned_gemm

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)

* fix(opus): change bias convention from [M] per-row to [N] per-output-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)

* chore(opus): black auto-format

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 23e5674ce5f042af8c77d62be1079b538e917e1a)

* fix(opus): shrink g_a/g_b num_records by k_start in flatmm_splitk

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)

* feat(opus): add HAS_OOB compile-time guard for tail boundary handling

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]>

* feat(opus): XCD swizzle + cache control for a16w16

- 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]>

* chore(opus): route tuned-CSV lookup through global aiter/configs/

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]>

* feat(opus): subset compile via CSV + sidecar

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]>

* feat(opus): heuristic returns kid; propagate has_bias

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]>

* feat(opus): gradlib tuner integration + safety gates

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]>

* feat(opus): persistent (M-outer + XCD swizzle) a16w16 pipeline

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]>

* chore(opus): drop kspl experimental pipeline

Co-authored-by: Cursor <[email protected]>

* fix(opus): lock sidecar+build, reset env+versioner to prevent mp tune races

Co-authored-by: Cursor <[email protected]>

* feat(opus): a16w16 mono-tile pipeline + traits + tuner integration

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).

* tune(gemm): add kimi bf16 + refresh dsv4 bf16 tuned configs (no hipblaslt)

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]>

* chore(opus): black auto-format

Co-Authored-By: Claude Opus 4 <[email protected]>

* tune(gemm): preempt bf16 dedup conflict by propagating kimi wins

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]>

* feat(opus): allow M-unaligned shapes for mono-tile launcher

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]>

* fix(opus): reject mono kid when N/K unaligned, accept M-tail via padding

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
(41e2d482a), 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]>

* fix(opus): indirect splitk workspace ptr through a handle slot

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]>

---------

Signed-off-by: blyu <[email protected]>
Signed-off-by: blyu <[email protected]>
Signed-off-by: blyu <[email protected]>
Signed-off-by: binglue.lyu <[email protected]>
Signed-off-by: demonsan <[email protected]>
Co-authored-by: blyu <[email protected]>
Co-authored-by: blyu <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Claude Opus 4 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants