Skip to content

[HIP] [JIT] [Perf] aiter.add/sub/mul/div: flat vector kernels and host-scalar suppor - #8463

Open
ClementLinCF wants to merge 4 commits into
mainfrom
binary-flat-fast-path
Open

ClementLinCF wants to merge 4 commits into
mainfrom
binary-flat-fast-path

Conversation

@ClementLinCF

Copy link
Copy Markdown
Contributor

Summary

Adds a flat 16-byte-vector fast path for same-shape contiguous aiter.add/sub/mul, and lets aiter.add/sub/mul/div (and the in-place forms) take a Python scalar as other through a new binary_scalar binding. Both paths are enabled on gfx942 and gfx950 only. The binary modules are also built without denormal flushing, so subnormal results now match torch.

Motivation

  • aiter.mul(x, 0.5) raised, so callers passed the scale as a 1-element tensor and went through the broadcast path (16.09 µs for bf16 [16,96,576] on MI300X).
  • Same-shape bf16 add on [256,7168] took 27.06 µs on MI300X, while copying the same bytes takes about 4 µs.
  • Denormal flushing made results differ from torch for tiny values.

Changes

  • csrc/include/binary_operator.cuh: flat tensor-tensor and host-scalar kernels (one 16 B vector per thread, Opus buffer loads/stores, fp32 math). Same-shape contiguous inputs try the flat kernel first; anything else runs the existing kernels unchanged.
  • New binary_scalar binding in every generated binary module (generate_binaryop.py, aiter_operator.h, rocm_ops.hpp). Scalar div runs as mul by the reciprocal, as torch does.
  • aiter/ops/aiter_operator.py: host-scalar wrappers; unsupported inputs fall back to torch.
  • aiter/jit/optCompilerConfig.json: -fno-gpu-flush-denormals-to-zero for module_aiter_operator.
  • op_tests/test_aiter_add.py: rewritten so it fails on mismatches.

Performance (if applicable)

bf16, cold graph mode (rotating buffer of at least 1 GiB, LLC flush before each replay, median of 15 replays). Before is upstream b5b4bf9, where the scale has to be a 1-element tensor.

Hardware Workload/configuration Before After Change
MI300X add [256,7168] + [256,7168] 27.06 µs 4.03 µs 6.7×
MI300X mul [16,96,576] × scalar 16.09 µs 2.12 µs 7.6×
MI300X mul [256,96,576] × scalar 30.47 µs 14.97 µs 2.0×
MI300X mul_ [256,96,576] × scalar 36.91 µs 21.05 µs 1.75×
  • MI300X: about 1.4× to 7.6× faster than before across the measured shapes, and 1.02× to 1.22× faster than the fastest existing backend (torch eager, torch.compile or Triton).
  • MI355X: numbers against b5b4bf9 and the other backends will be added.
  • Slower cases: in a 1-D size sweep on MI300X, add is 0.91× of torch at 8 MiB. Eager host-scalar calls on tiny tensors pay extra host overhead (bf16 [1,7168]: about 19.6 µs vs 9.2 µs through torch on MI300X, 14.4 µs vs 5.6 µs on MI355X). Graph mode is not affected.

Testing

  • Unit tests added or updated
  • Performance benchmarks run
  • Tested on MI250X
  • Tested on MI300X
  • Tested on MI355X

Documentation

  • Docstrings updated
  • User guide updated
  • Performance guide updated
  • No documentation change is needed, with the reason stated below

Dependencies

  • No new third-party dependencies added
  • New dependencies are listed and justified below

Breaking Changes

No API changes. Behavior changes:

  • Subnormal results are no longer flushed to zero, so they match torch. The JIT cache doesn't track compile flags, so existing module_aiter_{add,sub,mul,div}_* builds keep flushing until they are rebuilt.
  • A Python scalar other now works instead of raising, and a CPU other tensor falls back to torch.

PR Self-Review

Reviewed revision

8279edb

Behavior and intent

Same-shape contiguous add/sub/mul with one dtype (fp32/fp16/bf16), 16 B-aligned pointers and a size that is a multiple of 16 B (under 2 GiB) now run the flat kernel on gfx942/gfx950. Everything else (div, mixed dtypes, broadcast, strided, misaligned, other archs) keeps the existing kernels. A Python int/float other with a contiguous fp32/fp16/bf16 input runs binary_scalar in eager mode; other host-scalar cases (bool, other dtypes, odd-sized, strided or misaligned inputs, other archs, torch.compile) fall back to torch.

Validation and unverified scope

python3 op_tests/test_aiter_add.py and python3 op_tests/test_aiter_add.py -d bf16 fp16 fp32 passed on MI300X and MI355X. The test's profiler checks confirm the flat kernels run exactly where expected. CUDA graph replay and torch.compile(fullgraph=True) were also checked with a separate script: results match and there are no graph breaks. Not tested: MI250X and other archs (the new paths are gated off there). Upstream CI has not run yet.

PR-specific question

  • Arch: binary_flat_arch_supported() (gfx942/gfx950, cached per device) in C++, with a matching per-device check in Python.
  • Dtype: fp32/fp16/bf16 only, one dtype for inputs and output. Tensor-tensor div and mixed dtypes are excluded at compile time.
  • Shape: same-shape contiguous operands (or a contiguous input for the scalar path), 16 B-aligned pointers, nbytes % 16 == 0 and nbytes < 2^31.
  • Invariant: C++ launches a flat kernel only after all of these checks pass; otherwise it returns false and the existing kernel or torch runs. The Python pre-check only saves an allocation.

Changed op tests

op_tests/test_aiter_add.py now compares bit-exactly against torch and fails on mismatches (before, it only printed checkAllclose). It keeps the existing 23 shape/stride cases for add/sub/mul/div, and adds flat-path boundary sizes (with a profiler check that the flat kernel ran), host-scalar cases (0.5, ±0, ±inf, nan, subnormal, bool, in place) and subnormal-result cases. No other op test covers host scalars, flat-path selection or subnormal results; test_aiter_addInp.py only times add_.

…smatch

Move the argument parsing and the sweep into main() under a __main__
guard, so the module can be imported. The existing 23 input/other
shape and stride pairs and their flags are kept; -d/--dtype and --op
add dtype and operator sweeps. --op defaults to add, sub, mul and div.
-d defaults to bf16 only, because every dtype JIT-builds four more
modules within CI's time limit; pass -d bf16 fp16 fp32 for the full
sweep.

Each case builds inputs with both signs, +-0, +-inf and nan, with
magnitudes of at least 1e-3 so that no fp32 result is denormal (aiter
flushes fp32 denormals, torch does not). It compares the aiter result
with torch bit for bit, sign of zero included and any nan matching any
nan. The test now fails on a mismatch; before, it printed torch.equal
and always passed. Timing uses run_perftest and the results end in one
markdown table.
…us operands

Same-shape contiguous operands of one dtype (bf16, fp16 or fp32) now run
operator_flat_kernel when the output is a whole number of 16-byte
vectors below 2 GiB and all three pointers are 16-byte aligned: one
vector per thread through Opus buffer loads and stores
(opus::make_gmem with load_vector_nbytes / store_vector_nbytes), fp32
math and one rounding to the output type. Out-of-range vectors of the
last block are dropped by the buffer descriptor, so there is no
per-lane bounds check.

On gfx942/gfx950 the buffer cache-policy bits are compiled in: sc1
stores below 1 MiB of output, and streaming (nt loads, sc0 nt stores)
from 1 MiB on. Other archs build the kernel with default policy bits.
The kernel runs on gfx950 and gfx942, where the policies were
measured; binary_flat_arch_supported() caches that check per device.
Every other arch, div, mixed dtypes and ineligible sizes keep the
existing kernels.

op_tests/test_aiter_add.py gains test_same_shape: output sizes of 16 B,
1 MiB - 16 B, 1 MiB, 1 MiB + 16 B, 2 MiB and 1 MiB + 2 B, a misaligned
view and a partial last block, out of place and in place, compared with
torch bit for bit. One profiled call per case asserts which kernel ran:
operator_flat_kernel with the expected streaming flag exactly when the
case is eligible, and no flat kernel otherwise.
The profiler occasionally records no device kernel at all; the case
then re-profiles the same op on new operands of the same layout, made
outside the profile, after a short pause, up to 3 times, and logs a
warning for each re-profile. A profile that has device kernels but not
the expected one fails at once.
…binding

aiter.add/sub/mul/div and their in-place forms accept a Python int or
float as other; before, they raised. Each per-op, per-dtype binary
module gains one generated binding,

  bool binary_scalar(aiter_tensor_t& input, int op, double other,
                     aiter_tensor_t& output)

declared in aiter_operator.h and registered with the other binary ops.
op is one of BINARY_SCALAR_ADD, BINARY_SCALAR_SUB and BINARY_SCALAR_MUL,
named constants in aiter_operator.h, with the same values as
_BINARY_SCALAR_ADD / _SUB / _MUL in aiter/ops/aiter_operator.py; the
generated dispatch compares op with them. It returns false unless op is
the module's add, sub or mul and input is on a GPU; otherwise it
dispatches on input's dtype to binary_scalar_process with
static_cast<float>(other), which rounds to nearest even and gives +-inf
on overflow. Python has one matching stub, _binary_scalar_kernel(input,
op, other, output), mapped to the (input.dtype, input.dtype) module of
op's name; a value with no name selects no known module, so its build
fails, as an unknown op name's does. The wrappers pass the scalar as a
Python float.

The generated binary_op_dispatch now returns false for a CPU other
tensor, so a CPU tensor never reaches a GPU kernel and the call falls
back to torch; before, a CPU other was dispatched to the GPU kernels
with a host pointer.

operator_flat_scalar_kernel computes one 16-byte vector per thread with
Opus buffer loads and stores, fp32 math and one rounding; on
gfx942/gfx950 its loads are nt and its stores sc1. On gfx942 it
streams instead (sc0 nt stores, as the same-shape kernel's streaming
variant) from 1.25 MiB of output when the output is the input and from
2.5 MiB otherwise, where sc1 stores were measured to fall behind;
binary_flat_scalar_streams() decides that, looking up the device
only from 1.25 MiB, the smallest threshold. Like the
same-shape kernel it runs on gfx950 and gfx942, for a contiguous,
16-byte aligned input that is a whole number of 16-byte vectors below
2 GiB. Everything else
falls back to torch: other archs, other sizes and dtypes, non-contiguous
or misaligned inputs, bool scalars (sub keeps torch's own error) and
ints beyond the double range. Before it allocates an output, the
wrapper checks every condition binary_scalar_process puts on the input
(dtype, contiguity, 16-byte alignment, a whole number of 16-byte
vectors below 2 GiB, device arch), so an input the C++ would reject
goes to torch without an allocation or a binding call; an eager
binding call costs more than torch's own call. The C++ checks stay
authoritative. On first use the wrapper records whether every visible
device is in the same arch list as the C++ gate
binary_flat_arch_supported(), which stays authoritative; on a node where
they all are, that one flag is the check, otherwise _flat_arch_ok()
caches the answer per device index. Both reuse
aiter.ops.asm.asm_utils.get_gfx_from_device, imported on first use, so
importing aiter.ops.aiter_operator queries no device.

div multiplies by the reciprocal, as torch does for a CPU scalar
divisor: fp32(1.0 / double(s)) from torch 2.10 on and 1.0f / fp32(s)
before, chosen with is_torch_equal_or_newer; 1 / +-0 is +-inf. The
binding gets the reciprocal with op BINARY_SCALAR_MUL; a torch fallback
gets the original scalar. mul(x, 1) returns a new tensor, as torch does;
mul_(x, 1) on a floating-point input launches nothing and returns x.
Under torch.compile the wrappers call torch directly, because the
wrapper branches on the binding's result; that keeps the graph whole.

The binary modules are built with aiter's default
-fgpu-flush-denormals-to-zero, so the flat paths flush subnormal
inputs, scalars and results to signed zero, where torch keeps
subnormals.

op_tests/test_aiter_add.py gains test_host_scalar: shapes [256, 7168],
[3, 5], [1, 1] and [0] with scalars 0.5, 3, -2.5, 1, +-0, +-inf, nan,
1e-30, 1e-39, +-1e-40, 1e39, 3.4028235e38 and True, out of place and in
place, compared bit for bit with torch, or with torch's exception. The
flat-kernel cases that involve a subnormal fp32 scalar or result
compare with a flush-to-zero reference instead. For mul by 1
(x * 1 == x exactly), x itself is accepted as well as torch's result:
torch on gfx942 gives +0.0 for an fp16 -0.0 * 1. It checks that
mul(x, 1) is a new tensor, that inputs are unchanged, and that
operator_flat_scalar_kernel runs exactly when the case is eligible,
with the streaming variant exactly where binary_flat_scalar_streams()
picks it (SCALAR_STREAM_FROM; bf16 mul cases at 1.25 MiB - 16 B and
1.25 MiB in place and 2.5 MiB - 16 B and 2.5 MiB out of place check
both sides of gfx942's thresholds),
re-profiling like test_same_shape when the profiler records no device
kernel at all.
The binary modules (module_aiter_operator's configuration, which every
module_aiter_<op>_<dtypes> uses) now build with
-fno-gpu-flush-denormals-to-zero instead of aiter's default
-fgpu-flush-denormals-to-zero. With the flush, subnormal fp32 inputs,
scalars and results became signed zero where torch keeps them:
aiter.mul(x, 1e-39) and aiter.div(x, 1e39) gave 0 in bf16 and fp32 and
NaN at x = +-inf, and the older tensor-tensor kernels lost subnormal
results the same way. Without it the results match torch eager bit for
bit, for subnormal inputs, scalars and results, including in the older
kernels.

Only the configuration changes. aiter sorts and de-duplicates a
module's HIP flags, which puts -fno-gpu-flush-denormals-to-zero after
the default -fgpu-flush-denormals-to-zero, and clang honours the last
of the pair; module_sparse_mla_fp8 already relies on this.
test_subnormal_result fails if the flush ever wins. No other module
changes.

The add, sub and mul kernels keep the same instructions; only the fp32
denormal mode in their kernel descriptors changes. The older div
kernels, which do a real fp32 divide, lose the denormal-mode toggles
around each divide expansion.

Binary modules the JIT has already built keep flushing until they are
rebuilt: the JIT cache does not record compile flags, so a built module
is reused as it is. Remove its .so and build directory to pick this up.

op_tests/test_aiter_add.py: test_host_scalar compares its subnormal
cases (1e-39, +-1e-40, div by 1e39 and 3.4028235e38) with torch
directly; the flush-to-zero reference is removed. test_subnormal_result
adds tensor-tensor mul and div with a normal numerator and every result
below the dtype's smallest normal (bf16 and fp32, fp16 as a control),
in place and out of place. Its shapes reach the contiguous kernels
(operator_element_kernel or operator_contiguous_kernel_naive, and for
mul on gfx950 and gfx942 the flat kernel), an odd-sized contiguous
case (operator_contiguous_big_tile_kernel), the broadcast kernels
(operator_bcast_tile_kernel, operator_bcast_scalar_unroll_vectorize_naive)
and the transpose tile kernel (operator_tn_big_tile_kernel, with a
transposed second operand). Each case checks that an aiter kernel ran,
compares with torch bit for bit, and reports the kernel's time and
bandwidth.
@ClementLinCF
ClementLinCF requested review from a team and a balanced review from Copilot November 23, 2026 02:22
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the Radeon R9700 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

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

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

@github-actions github-actions Bot changed the title [Perf] aiter.add/sub/mul/div: flat vector kernels and host-scalar suppor [HIP] [JIT] [Perf] aiter.add/sub/mul/div: flat vector kernels and host-scalar suppor Nov 23, 2026

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.

🟡 Changes recommended

Missing output-device validation can dispatch a GPU kernel with a host pointer or an output on another GPU, while stale cached modules and overly restrictive eligibility gating introduce additional failures.

3 open issues
What changed in this PR

This PR accelerates AITER’s elementwise binary operators with flat vector kernels and adds Python scalar operands, while preserving torch fallbacks for unsupported inputs.

Changes:

  • Adds 16-byte-vector tensor and scalar kernels gated to gfx942/gfx950.
  • Extends wrappers and generated bindings for host scalars, including reciprocal-based division.
  • Disables denormal flushing for binary modules and expands tests with strict numerical and kernel-selection checks.
File Description
op_tests/​test_aiter_add.py Adds strict comparisons, scalar cases, boundary checks, and subnormal tests.
csrc/​kernels/​generate_binaryop.py Generates scalar dispatch and rejects CPU tensor operands.
csrc/​include/​rocm_ops.hpp Exposes the binary_scalar binding.
csrc/​include/​binary_operator.cuh Implements flat vector kernels and guarded launch paths.
csrc/​include/​aiter_operator.h Declares scalar operation constants and binding interface.
aiter/​ops/​aiter_operator.py Adds scalar wrappers, eligibility checks, and torch fallbacks.
aiter/​jit/​optCompilerConfig.json Disables denormal flushing for binary operator builds.

Review effort: Balanced

Comment on lines +287 to +288
if (!input.is_gpu())
return false;
def _binary_scalar_module_args(op: int, dtype: torch.dtype) -> dict[str, Any]:
# an unknown value names no known op's module, so its build fails as an unknown op name's does
probe = torch.empty(0, dtype=dtype)
return cmdGenFunc(_BINARY_SCALAR_OPS.get(op, str(op)), probe, probe)
Comment on lines +2305 to +2308
if(output.dtype() == input.dtype() && output.is_contiguous() &&
aiter::binary_flat_launch<Operation, _T0, _T1>(
buf_a, buf_b, buf_c, (int64_t)output.numel(), stream))
return;

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants