Repository navigation
[HIP] [JIT] [Perf] aiter.add/sub/mul/div: flat vector kernels and host-scalar suppor - #8463
ClementLinCF wants to merge 4 commits into
Conversation
…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.
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
There was a problem hiding this comment.
🟡 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
| 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) |
| 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; |


Summary
Adds a flat 16-byte-vector fast path for same-shape contiguous
aiter.add/sub/mul, and letsaiter.add/sub/mul/div(and the in-place forms) take a Python scalar asotherthrough a newbinary_scalarbinding. 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).addon[256,7168]took 27.06 µs on MI300X, while copying the same bytes takes about 4 µs.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.binary_scalarbinding in every generated binary module (generate_binaryop.py,aiter_operator.h,rocm_ops.hpp). Scalardivruns asmulby 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-zeroformodule_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.add[256,7168]+[256,7168]mul[16,96,576]× scalarmul[256,96,576]× scalarmul_[256,96,576]× scalarb5b4bf9and the other backends will be added.addis 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
Documentation
Dependencies
Breaking Changes
No API changes. Behavior changes:
module_aiter_{add,sub,mul,div}_*builds keep flushing until they are rebuilt.othernow works instead of raising, and a CPUothertensor falls back to torch.PR Self-Review
Reviewed revision
8279edb
Behavior and intent
Same-shape contiguous
add/sub/mulwith 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/floatotherwith a contiguous fp32/fp16/bf16 input runsbinary_scalarin 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.pyandpython3 op_tests/test_aiter_add.py -d bf16 fp16 fp32passed on MI300X and MI355X. The test's profiler checks confirm the flat kernels run exactly where expected. CUDA graph replay andtorch.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
binary_flat_arch_supported()(gfx942/gfx950, cached per device) in C++, with a matching per-device check in Python.divand mixed dtypes are excluded at compile time.nbytes % 16 == 0andnbytes < 2^31.Changed op tests
op_tests/test_aiter_add.pynow compares bit-exactly against torch and fails on mismatches (before, it only printedcheckAllclose). 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.pyonly timesadd_.