radiance 1.0.0

This commit is contained in:
Deadcode committed 2026-10-04 12:02:41 +02:00
commit ae74a8aebf
616 files changed
+338692

No files matched your search

+146
View File
@@ -0,0 +1,146 @@
# libavx -- the conventional op vocabulary in hand-written x86 SIMD, dispatched by CPU feature.
#
# ============================ THE BUILD IS THE DISPATCH ============================
#
# This file is not a list of sources. It is the mechanism that makes runtime dispatch SAFE, and
# every decision in it is load-bearing:
#
# THE KERNELS ARE COMPILED FOUR TIMES, once per ISA level, into four OBJECT libraries with
# different -m flags and AVX_LEVEL defined to 0/1/2/3. Same sources, four instruction streams.
# avx_vec.h wraps each level in its own inline namespace so the four sets of symbols do not
# collide -- which is not a nicety: without it the linker would pick one definition of
# avx::row_to_f32 for all four tables, and on a machine without AVX-512 the SCALAR path would
# execute AVX-512 and fault.
#
# THE DISPATCHER AND THE REGISTRY ARE COMPILED BASELINE, with no -m flags at all. They are what
# decides whether the other levels may run, so an instruction above the baseline in either of
# them faults before the decision is made. Note that this is a property of the FLAGS and not of
# the source: a compiler given -mavx512f may auto-vectorise anything, so "contains no intrinsics"
# is not the same claim.
#
# -march=native APPEARS NOWHERE. It is the obvious thing and it is wrong for a plugin: the .so is
# built on one machine, copied to others, and dlopened by an engine that has no idea what it was
# compiled for. A binary built with -march=native on a Zen 5 host SIGILLs on the first
# AVX-512 instruction anywhere older, before main, with no diagnostic.
#
# ============================ IN THE TREE, AND ALONE ============================
#
# The root CMakeLists adds this directory on every x86-64 build: these are the production host
# kernels, and a model whose placement puts an op on the host -- the n-gram embedding's gather,
# every step -- has no other kernel for it that the engine will serve on.
#
# It also builds ON ITS OWN, as any third party's plugin does: against an installed radiance,
# through find_package and the same rad_add_plugin -- `cmake -S libavx -B build-avx
# -DCMAKE_PREFIX_PATH=<radiance prefix>`. A box with no ROCm builds and checks it that way without
# the HIP probe and the whole core; the oracle the checker compares against is the installed
# reference library.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(libavx LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
# The harnesses land beside the plugin, in the build's $RADIANCE_HOME, where the loader ignores
# anything that is not a .so.
set(AVX_OUT_DIR ${RAD_PLUGIN_OUT}/kernels)
# ============================ the four ISA levels ============================
# Every kernel translation unit. avx_dispatch.cpp and avx_registry.cpp are NOT here -- they are
# baseline and belong to the plugin target itself.
set(AVX_KERNEL_SRC
avx_support.cpp
avx_table.cpp
avx_elementwise.cpp
avx_norm.cpp
avx_hc.cpp
avx_quant.cpp
avx_gemm.cpp
avx_attn.cpp
avx_moe.cpp
avx_gdn.cpp
avx_sample.cpp
avx_misc.cpp
)
# The flag sets, one per level. Written out rather than derived, because each one is a claim about
# what instructions the object may contain and a derived list hides that claim.
#
# 0 scalar nothing. x86-64 baseline, which is SSE2 -- the compiler will use it for scalar float
# and that is fine: SSE2 is in the base ISA and exists on every x86-64 that boots.
# 1 avx -mavx alone. NOT -mf16c and NOT -mfma: both are separate CPUID bits that arrived
# after AVX (Ivy Bridge and Haswell), and a level called `avx` that required them would
# fault on exactly the Sandy Bridge machines it exists for.
# 2 avx2 -mavx2 -mfma -mf16c. These three ship together on every part that has any of them.
# 3 avx512 F + BW + DQ + VL, which is what avx_dispatch.cpp checks for as a conjunction, plus
# the AVX2 set beneath it. Deliberately NOT avx512bf16 / avx512vnni: many AVX-512
# parts have neither, and neither is used (see avx_vec.h on why the bf16 convert is
# done with integer ops rather than vcvtneps2bf16).
set(AVX_FLAGS_0 "")
set(AVX_FLAGS_1 -mavx)
set(AVX_FLAGS_2 -mavx2 -mfma -mf16c)
set(AVX_FLAGS_3 -mavx512f -mavx512bw -mavx512dq -mavx512vl -mavx2 -mfma -mf16c)
find_package(OpenMP QUIET)
foreach(lvl RANGE 0 3)
add_library(avx_lvl${lvl} OBJECT ${AVX_KERNEL_SRC})
target_compile_definitions(avx_lvl${lvl} PRIVATE AVX_LEVEL=${lvl})
target_link_libraries(avx_lvl${lvl} PRIVATE radiance::abi)
target_include_directories(avx_lvl${lvl} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_compile_options(avx_lvl${lvl} PRIVATE ${AVX_FLAGS_${lvl}}
# CONTRACTION IS ALLOWED HERE AND THAT IS THE OPPOSITE OF libref'S RULE, stated so the
# difference is deliberate rather than inherited. libref passes -ffp-contract=off because it is
# the ORACLE: a reference that contracts disagrees with itself between compilers. libavx is a
# fast kernel checked against that oracle to a tolerance, and refusing FMA would throw away
# half the machine's floating-point throughput to chase a bit-exactness it already gives up by
# vectorising the reduction at all.
-ffp-contract=fast
# NO -ffast-math, and it is worth saying why given the above. Contraction changes the last ulp;
# -ffast-math changes what the code MEANS -- it lets the compiler assume no NaN and no signed
# zero, and this vocabulary is full of both (a masked logit is -inf, an attention row with no
# valid keys is a NaN the online softmax has to carry). The checker compares the finiteness
# pattern before it compares any number, exactly so that this cannot be smuggled in.
-fno-math-errno)
set_property(TARGET avx_lvl${lvl} PROPERTY POSITION_INDEPENDENT_CODE ON)
if(OpenMP_CXX_FOUND)
target_link_libraries(avx_lvl${lvl} PRIVATE OpenMP::OpenMP_CXX)
endif()
endforeach()
# ============================ the plugin ============================
# avx_ngram.cpp is baseline for the same reason as the other two, and for one more: it holds the
# embedding gather's row cache and its reader thread, and there must be ONE of each in the process
# whatever level runs -- compiled per level, each level would keep its own.
set(AVX_BASELINE_SRC avx_dispatch.cpp avx_registry.cpp avx_ngram.cpp)
rad_add_plugin(libavx kernels SOURCES ${AVX_BASELINE_SRC} INCLUDES ${CMAKE_CURRENT_SOURCE_DIR})
foreach(lvl RANGE 0 3)
target_link_libraries(libavx PRIVATE avx_lvl${lvl})
endforeach()
find_package(Threads REQUIRED)
target_link_libraries(libavx PRIVATE Threads::Threads)
if(OpenMP_CXX_FOUND)
target_link_libraries(libavx PRIVATE OpenMP::OpenMP_CXX)
else()
message(STATUS "libavx: no OpenMP -- the plugin will run single-threaded")
endif()
# ============================ the harnesses ============================
# They dlopen both plugins by path and link NEITHER. That is deliberate and it is what makes them
# usable in both builds and against a plugin built somewhere else entirely: the checker's whole
# claim is that it exercises the .so the engine would load, and a checker that statically linked
# the kernels would be exercising a different binary.
add_executable(rad-avx-check avx_check.cpp avx_check_rows.cpp avx_cases.cpp)
target_include_directories(rad-avx-check PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(rad-avx-check PRIVATE radiance::abi ${CMAKE_DL_LIBS} Threads::Threads)
set_target_properties(rad-avx-check PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${AVX_OUT_DIR})
add_executable(rad-avx-bench avx_bench.cpp avx_cases.cpp)
target_include_directories(rad-avx-bench PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(rad-avx-bench PRIVATE radiance::abi ${CMAKE_DL_LIBS})
set_target_properties(rad-avx-bench PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${AVX_OUT_DIR})
if(OpenMP_CXX_FOUND)
target_link_libraries(rad-avx-bench PRIVATE OpenMP::OpenMP_CXX)
endif()
+249
View File
@@ -0,0 +1,249 @@
# libavx
The conventional op vocabulary in hand-written x86 SIMD, runtime-dispatched by CPU feature.
A third kernel plugin beside `libref` and `libr4d`, for a domain whose only other implementation is
the reference one, which says in its own header that it is slow. Same seventy-five ops as libref,
same schemas, same answers to a tolerance — the difference is the instruction stream underneath.
cmake -S libavx -B build-avx -DCMAKE_PREFIX_PATH=<radiance prefix> && cmake --build build-avx -j4
K=build-avx/radiance_home/kernels; R=<radiance prefix>/share/radiance/kernels
$K/rad-avx-check --ref $R/libref.so --avx $K/libavx.so
$K/rad-avx-bench --ref $R/libref.so --avx $K/libavx.so --all
It builds on its own exactly as a third party's plugin does -- `find_package(radiance)` and the
same `rad_add_plugin` -- against an installed radiance, with no ROCm and no core build. A
full-tree build on x86-64 always builds it: it is where the engine's HOST kernels come from. libref is the
oracle and the engine refuses to serve on it, so an op the placement runs on the host — the n-gram
embedding's gather, every step — needs this plugin.
## The embedding gather
`embed_lookup_q` over an E4M3 table into bf16 is the one host op a GPU deployment runs: the
n-gram table is tens of gigabytes in the container's mapping and never on a card. Its rows come
through `avx_ngram.cpp`, compiled baseline so the process has one of each: a row cache shared by
every thread (2^19 rows, eight ways, CLOCK), an O_DIRECT read through io_uring for each miss, the
ranks dividing a call's misses rather than duplicating them, and a reader thread that fetches the
next prefill chunk's rows while the current one runs. The level's kernel decodes the rows: at
AVX-512 the call's 256-entry bf16 table sits in eight registers and four `vpermt2w` look up 32
codes; below it, one code at a time. The row's layout hook only checks the table's encoding —
E4M3 with one bf16 scale, or the checkpoint's plain bf16 — and asks for no re-layout, because the
gather reads the rows from the container file in the layout they are stored in.
`rad-avx-check` runs the op over a file-backed table with two ranks and the reader racing, at
every level, and compares every row with the file's bytes.
## The build is the dispatch
Every kernel source is compiled **four times** into four object libraries — scalar / AVX /
AVX2+FMA / AVX-512 — with `AVX_LEVEL` defined and the matching `-m` flags. `avx_vec.h` wraps each
level in its own inline namespace so the four symbol sets cannot collide; without that the linker
picks one definition of `avx::row_to_f32` for all four tables and the *scalar* path executes
AVX-512, which is a SIGILL from the fallback that exists to prevent SIGILLs.
`avx_dispatch.cpp` and `avx_registry.cpp` are compiled **baseline, with no `-m` flags**, because
they are what decides whether the others may run. That is a property of the flags and not of the
source: a compiler given `-mavx512f` may auto-vectorise anything, so "contains no intrinsics" is
not the same claim. `-march=native` appears nowhere.
Detection is `__builtin_cpu_supports`, not raw CPUID, because the OS has a say — a CPU may
enumerate AVX-512 while the kernel has left the ZMM state disabled, and using it then faults.
AVX-512 is checked as the conjunction F + BW + DQ + VL, all four of which the kernels use.
`avx_isa_force()` is an exported symbol, not an environment variable, so the checker can sweep all
four levels and the engine can never reach it.
## Coverage
75 of 75 ops. Every op `libref` implements, `libavx` implements; `rad-avx-check` fails if that
stops being true, and reports a row that returns `RAD_E_UNSUPPORTED` separately from one that is
absent — a row that declines is worse than no row, because the selector resolves to it and the step
fails at issue rather than at declare.
Two things are deliberately narrower than libref and say so at the call site:
- **`all_reduce` / `all_gather` serve world size 1** and refuse anything wider by name. libref's
real implementation is a rendezvous over shared mutable state with a barrier and a generation
counter, and there is exactly one of it per process; two kernel plugins each carrying their own
would be two rendezvous groups for one world, and which one a rank joined would depend on which
plugin won selection. libref sits below this plugin in the hierarchy, so a tensor-parallel host
deployment resolves the collectives there and everything else here.
- **The rows carry no `opd_shape`.** libref publishes one for the whole conventional vocabulary and
the ABI says an op inside `docs/OPS.md` is describable even when the kernel under test is not.
A second copy would be a second set of judgement calls about the same ops.
## Correctness
`rad-avx-check` opens both plugins with `dlopen` and links neither — the claim is about the `.so`
the engine would load. It checks four things in order: schema agreement (the loader's own
`schema_same`, run before any arithmetic, because the loader refuses the *whole* plugin on one
disagreement), coverage, the numbers, and every ISA level.
233 checked, 233 passed, 0 failed, 0 declined, 4 skipped, 0 missing.
worst rel_l2 = 3.556e-04 [rmsnorm M=3 n=645 bf16 wadd=1]
hand-built: 22 checked, 0 failed
at every level, against `rad-kbench`'s tolerance table (the worst case at AVX2 is silu_mul's
4.038e-04 rather than rmsnorm's). Every conversion is
additionally proven **exhaustively** — all 256 or 65536 bit patterns of each narrow format, in both
directions, bit-identical to libref including NaN, subnormals and negative zero. That sweep is not
redundant with the geometry table: a draw of normals reaches none of those patterns, so a
conversion can be wrong by octaves at the bottom of its range while every geometry still passes.
**The four skipped cases are limits of libref's descriptions, not of libavx.**
`sample_merge_topk`'s shape hook returns `RAD_E_UNSUPPORTED` unconditionally, so it publishes no
description at all. `gemm_nt_q_bias` at `fp8a16` is declined by name (the bias form takes `a_scale`
as required and fp8a16 has none). `ngram_ids` describes `vocab_sizes` as normal-filled i64, which
its own launch then refuses because a vocabulary size must be positive — so that op cannot be
checked cold until libref's hook describes it as an index fill with a positive range.
A cold description cannot reach every form of every op, and the **hand-built cases** are the rest:
operand views and index patterns a description does not draw, and the forms an optional operand
selects. `dflash_select`'s are the sharpest example: a description draws its codebooks as weights,
at 0.02, where the pairwise term is a thousandth of the unary score and never decides a pick — so
the walk is checked cold and the form it computes is checked by hand, with unit-scale codebooks, once
with `hp` and once without.
## The measurement platform
The numbers below are one thread on a **Ryzen 9 9950X3D** (Zen 5, 16 cores, 128 MiB L3), taken with
`rad-avx-bench --peak` rather than quoted from a data sheet. All four ISA levels execute natively on
that part, so all four are measured and none is inferred. Re-run the commands above to get the
figures for another one; the ratios are what the rest of this document reasons about.
FMA scalar 29.3 GFLOP/s triad L1 129 GB/s (48 KiB)
FMA avx 135.0 GFLOP/s triad L2 157 GB/s (1.5 MiB)
FMA avx2 175.0 GFLOP/s triad DRAM 42 GB/s (768 MiB)
FMA avx512 351.4 GFLOP/s
The avx2 and avx512 figures are exactly 2 FMA/cycle at 8 and 16 lanes; avx (no FMA) reaches 4
vector FP ops/cycle on Zen 5's four FP pipes. The triad counts three arrays — two read, one
written — and does not count a read-for-ownership the compiler may have elided.
## Conversion, MB/s of source bytes
`rad-avx-bench --cvt`, through the plugin's own `cast`.
| pair | scalar | avx | avx2 | avx512 | libref |
|---|---|---|---|---|---|
| f32 → bf16 | 17885 | 31739 | 40436 | 78707 | 1725 |
| bf16 → f32 | 28598 | 23382 | 34531 | 40154 | 990 |
| f32 → f16 | 1245 | 1246 | 138027 | 159337 | 670 |
| f16 → f32 | 2706 | 2706 | 34122 | 39493 | 717 |
| f32 → fp8_e4m3 | 1102 | 1165 | 20619 | 26463 | 623 |
| fp8_e4m3 → f32 | 4512 | 4486 | 8294 | 12545 | 360 |
| f32 → i8 | 4247 | 10699 | 99319 | 164889 | 1071 |
| i8 → f32 | 12088 | 11182 | 17324 | 20526 | 384 |
f16 is software below AVX2 because F16C is its own CPUID bit that arrived one generation after
AVX — a level called `avx` that required it would fault on the machines it exists for.
## Per op, at model shapes
`rad-avx-bench`, microseconds per launch, median of 7 reps, **one thread**, cache-warm. Geometry is
a ~1.5B dense model: n_embd 2048, n_ff 5632, n_vocab 32000, 16 heads of 128. M = 1 is decode, 64 a
speculative verify window, 512 a prefill chunk.
| op | geometry | libref | scalar | avx | avx2 | avx512 | rate (avx512) |
|---|---|---|---|---|---|---|---|
| gemm_nt | M=1 N=2048 K=2048 | 1589 | 537 | 345 | 282 | **241** | 34.8 GFLOP/s |
| gemm_nt | M=64 N=2048 K=2048 | 101770 | 30355 | 6958 | 3846 | **2860** | 187.7 GFLOP/s |
| gemm_nt | M=512 N=2048 K=2048 | 816412 | 242612 | 55778 | 30745 | **22870** | 187.8 GFLOP/s |
| gemm_nt | M=512 N=5632 K=2048 | 2244318 | 672900 | 156165 | 87061 | **65176** | 181.2 GFLOP/s |
| logits_gemm | M=1 32000×2048 | 25055 | 8861 | 6808 | 6866 | **5525** | 23.7 GB/s |
| rmsnorm | M=512 n=2048 | 2351 | 433 | 248 | 200 | **87** | 48.2 GB/s |
| silu_mul | M=512 n=5632 | 9971 | 5426 | 1874 | 1281 | **740** | 23.4 GB/s |
| softmax | M=512 n=2048 | 3236 | 2618 | 475 | 306 | **204** | 41.0 GB/s |
| quant_act_fp8 | M=512 n=2048 g=128 | 7745 | 5254 | 4767 | 344 | **251** | 12.5 GB/s |
| had_quant_act_i8 | M=512 n=2048 g=128 | 7362 | 3633 | 731 | 367 | **261** | 12.1 GB/s |
| sample_argmax | M=1 n_vocab=32000 | 23.7 | 14.3 | 2.02 | 2.02 | **1.15** | 111 GB/s |
| sample_topk | M=1 n_vocab=32000 | 2287 | 1067 | 174 | 139 | **77** | |
| attn_paged | q_len=1 hd=128 gqa=4 ctx=2048 | 6.73 | 1.53 | 1.18 | 1.11 | **0.93** | |
**How to read this.** The libref column is a statement about libref, which is a scalar loop with a
per-element dtype switch and says so in its own header; the ratio is what says an op is wired at
all. The rate column against the ceilings above is the statement about libavx:
- `gemm_nt` at prefill reaches **188 GFLOP/s against a 351 GFLOP/s ceiling — 54%**.
- `sample_argmax` reaches **111 GB/s against a 129 GB/s L1 ceiling — 86%**; it is a single pass
over the logits and is essentially at the memory system.
- `softmax` at 41 GB/s and `logits_gemm` at 24 GB/s are **DRAM-bound, not flop-bound** —
`logits_gemm`'s weight is 128 MiB in bf16 and fits in no cache, so whatever the flop count says
it is a memory benchmark wearing a GEMM's name, and 24 against a 42 GB/s single-thread triad is
the honest way to read it.
- `silu_mul` at 23 GB/s and `rmsnorm` at 48 GB/s are the two that have room left.
These are **single-thread** numbers throughout. The plugin parallelises over the outer dimension
with OpenMP above a work threshold; the bench pins one thread because that is what ranks a kernel
change, and a 32-thread number would be measuring the memory controller.
## Why the code is shaped the way it is
Each choice below is measured rather than reasoned about, and the ones that did not pay are recorded
beside the code, because a null result is worth as much as a win.
**The register block is swept, not reasoned about** (`gemm_nt` bf16, M=512 N=2048 K=2048):
AVX-512, 32 ZMM 4x4 23.2 ms 4x6 22.1 (chosen) 6x4 24.2 8x4 23.8 8x2 35.2 12x2 34.1
AVX2/AVX, 16 YMM 3x3 34.4 ms 2x6 30.7 (chosen) 2x5 31.9 2x4 34.8 3x4 58.4 4x3 58.1
Two things in that table matter more than the choice. The **cliff**: 3×4 and 4×3 at AVX2 are 58 ms
against 31–34 around them, because 12 accumulators plus 3–4 A vectors plus one B is 16–17 live in a
16-register file, and the spill lands *inside* the k loop. And **wider in N beat wider in M at equal
arithmetic intensity** — 2×6 and 3×3 both load 8 vectors, for 12 and 9 FMAs, intensity 1.5 either
way, and 2×6 is 11% faster. Nothing about the flop count predicts that.
**NULL RESULT — cache-blocking the A panel is worth 6% on this part**, not the several-fold the
traffic argument predicts. Swept: 128 KiB 26.0 ms, 256 KiB 23.4, 1 MiB 24.0, 4 MiB 25.4, 16 MiB
25.4, unblocked 25.0; and at M=64 blocking is *worse* (2.91 against 2.85). The reason is the part:
128 MiB of L3, so the traffic the blocking removes is served at L3 speed and not DRAM's. Kept,
because it is never much worse and is the real fix on a part with 8 MiB of L3 — but it is worth six
percent where there is this much cache, not the several-fold the traffic argument suggests.
**NULL RESULT — the fp8 decode table gather loses to scalar.** Every fp8 byte is one of 256 floats,
so a lookup is exact and obvious; `vpgatherdd` measured 3268 MB/s at AVX2 and 3815 at AVX-512
against **4512 scalar**. A gather issues one cache line per lane however small the table is.
The decode is a branchless exponent reconstruction instead: 8294 and 12545 MB/s, 2.5× and 3.3×.
**A "fast path" whose epilogue is a per-element branch is not a fast path.** Computing sixteen lanes
of an fp8 encode with vector integer arithmetic and then spilling them to a stack array to run a
scalar loop testing one mask bit each costs roughly twice what the vector form does: on a normalised
activation the mask is all-ones every time, so that loop runs on exactly the path it was written to
avoid. The encode finishes in vector registers.
**An unvectorised level is not a half-speed level.** A level that falls through to the ABI's scalar
converter for a conversion costs an order of magnitude more than the vector form, not the 2× its
width would suggest — so every conversion is written at AVX2 as well as at AVX-512, and AVX2 is the
level most machines in the world run.
**A fallback that loses to the thing it falls back from is not a fallback.** The top-R selection's
two-pass form (vector max, then find the index) pays only because the first pass is vector work; at
the scalar level it is strictly two passes where a single-pass loop does one, and it measures slower
than libref's. The scalar level therefore uses the single-pass loop. The confirmation pass is
vectorised at every level for the same reason: scalar, it reads n/2 elements on average and is most
of what `sample_argmax` costs.
**A ceiling has to be compiled at the level it describes.** A peak loop compiled baseline measures
SSE2 whatever level it is nominally for, and every kernel looks excellent against a ceiling an order
of magnitude too low — so the peak kernels live in the plugin and are compiled per level like every
other kernel here. The accumulator count matters as much as the flags: sixteen accumulators plus two
constants is eighteen live vectors and spills a 16-register file, which costs more than the FMA
saves, so the AVX and AVX2 peaks use ten.
## Layout
avx_isa.h the ISA levels and AVX_OP_LIST -- the only place the op set is written
avx_vec.h the vector abstraction and the dtype conversions; compiled 4x
avx_common.h libref's addressing contract, the scratch arena, the threading rule
avx_dispatch.cpp BASELINE: CPUID, the level tables, the thunks, the fp8 table
avx_registry.cpp BASELINE: the schemas (libref's, slot for slot) and the kernel rows
avx_ngram.cpp BASELINE: the embedding gather's row cache, direct reads and reader
avx_rows.h the gather's two halves: the row source and the per-level decode
avx_support.cpp the generic row, the reductions, the top-R step; compiled 4x
avx_had.h the Hadamard rotation, the fp8 group, the fp8 fusions' shared epilogue
avx_{elementwise,norm,hc,quant,gemm,attn,moe,gdn,sample,misc}.cpp the kernels; compiled 4x
avx_harness.h plugin loading, the operand draw, the geometry table -- shared by both tools
avx_cases.cpp the geometries; one table so the check and the bench cannot disagree
avx_check.cpp rad-avx-check
avx_check_rows.cpp rad-avx-check's file-backed embed_lookup_q case
avx_bench.cpp rad-avx-bench
+974
View File
@@ -0,0 +1,974 @@
/* avx_attn.cpp -- paged attention, dense attention, the KV write, and the two rotary forms.
*
* ============================== THE PAGED LAYOUT ==============================
*
* kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] K then V inside a slot
*
* libr4d's, stated once for the whole project in libref/ref_ops.h, obeyed here. A flat slot index
* s decomposes as block = s / block_size, offset = s % block_size; `block_table[seq, i]` holds the
* block id of the sequence's i-th block and `slot_mapping[token]` the flat slot a token writes to.
*
* ============================== THE MASK ==============================
*
* `seqused[s]` is the sequence's TOTAL key count INCLUDING this step's query tokens, so query row
* i of a q_len-row step sits at absolute position seqused[s] - q_len + i. That is what makes one
* kernel serve a decode (q_len 1), a speculative verify (q_len <= 64) and a prefill chunk (q_len
* in the thousands) with no second length parameter.
*
* causal = 1 key j is visible when j <= pos
* causal = 0 key j is visible when j < seqused[s]
* window > 0 causal: additionally pos - j < window; non-causal: |pos - j| < window, the
* two-sided reading libr4d's h128 kernel documents.
*
* ============================== ONE PASS OVER THE CACHE, NOT TWO ==============================
*
* This is the one place where this plugin deliberately computes the softmax in a DIFFERENT ORDER
* from the oracle, and it is worth being explicit about the trade.
*
* libref makes two passes over the whole context: one to find the maximum score, one to
* exponentiate and accumulate -- and it RECOMPUTES every dot product in the second pass, because
* keeping them would need a buffer the size of the context and "the reference has time it does not
* have memory". At a 128K context that is two full sweeps of the KV cache and twice the dot
* products, and the KV cache is the largest thing a decode step touches.
*
* Here the softmax is ONLINE and tiled, the flash-attention arrangement: keys are taken in tiles,
* a tile's scores are computed once, the running maximum is updated at the tile boundary and the
* accumulator rescaled by exp(m_old - m_new) when it moves. One pass, one dot product per key, and
* the memory is one tile of scores rather than one context of them.
*
* WHAT IT COSTS: the rescalings round. The result is mathematically identical -- the final running
* maximum IS the global maximum, and every weight ends up as exp(s_j - m_final) -- but the
* intermediate multiplications are extra roundings that libref does not perform, so this cannot be
* bit-exact against it and does not claim to be. It lands at ~1e-7 relative against a tolerance of
* 1e-4 (f32) / 2e-2 (bf16). Every other numerical choice in this file is exact by construction:
*
* THE DESCALES ARE APPLIED PER ELEMENT, NOT TO THE DOT. libref computes
* `dot += q[d] * (k[d] * kds)`, which is not the same f32 number as `dot(q, k) * kds`. The K row
* is therefore scaled by `kds` as it is widened, which reproduces the reference's arithmetic
* exactly rather than to a tolerance. Same for V and `vds`.
*
* AN EMPTY WINDOW IS A ZERO ROW, NOT A NaN. A softmax over no visible key has no defined answer
* and zero is what every kernel in this project produces. The checker compares the finiteness
* pattern before any norm, so getting this wrong is a hard failure rather than a tolerance
* question -- which is the right treatment.
*/
#include "avx_vec.h"
#include "avx_common.h"
using namespace avx;
/* The widest head this accumulates in one frame. MLA's 576 is the widest in circulation and
* libr4d's widest is 256, so 1024 is headroom rather than a limit anyone meets; above it the op
* says RAD_E_UNSUPPORTED by name instead of overflowing. Same number as libref's, so the two
* refuse the same calls. */
enum { AVX_HD_MAX = 1024 };
/* Keys per online-softmax tile. Sized so a tile of scores and the key rows behind it stay in L1
* beside the query head and the accumulator: at head_dim 128 that is 64 keys x 128 floats = 32 KiB
* of K plus the same of V, which is the working set a Zen-class L1 holds. It is a constant rather
* than a tunable because the cost curve is flat between 32 and 128 -- what matters is that it is
* not 1 (a rescale per key) and not the whole context (libref's memory problem). */
enum { AVX_KV_TILE = 64 };
struct KVView {
const RadTensor* t;
int64_t sb, sh, so, sd; /* strides: block, kv head, slot offset, element */
int64_t head_dim;
};
static KVView kv_view(const RadTensor* c, int64_t head_dim, int64_t block_size, int64_t kv_heads) {
KVView v{};
v.t = c;
v.head_dim = head_dim;
if (c->rank == 4) {
v.sb = c->stride[0]; v.sh = c->stride[1]; v.so = c->stride[2]; v.sd = c->stride[3];
} else {
v.sd = 1;
v.so = 2 * head_dim;
v.sh = block_size * v.so;
v.sb = kv_heads * v.sh;
}
return v;
}
/* A head of an operand, widened into f32 and optionally scaled as it goes -- which is what makes
* the descale exact against libref rather than close (see the header). */
static inline const float* head_f32(const RadTensor* t, int64_t base, int64_t ds, int64_t n,
float mul, float* scr) {
if (ds == 1) {
if (mul == 1.0f) return row_f32_in(t->dtype, byte_at(t->data, t->dtype, base), scr, n);
row_to_f32(t->dtype, byte_at(t->data, t->dtype, base), scr, n);
} else {
for (int64_t d = 0; d < n; ++d) scr[d] = ldt(t, base + d * ds);
}
if (mul != 1.0f) {
const vf vm = vf_set1(mul);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) vf_storeu(scr + i, vf_mul(vf_loadu(scr + i), vm));
for (; i < n; ++i) scr[i] *= mul;
}
return scr;
}
/* A dot product with four accumulators, which is what covers the FMA latency. Shared by both
* attention forms and by nothing else, so it lives here rather than in the header. */
static inline float dotf(const float* a, const float* b, int64_t n) {
vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero();
int64_t i = 0;
for (; i + 4 * VF_N <= n; i += 4 * VF_N) {
a0 = vf_fma(vf_loadu(a + i), vf_loadu(b + i), a0);
a1 = vf_fma(vf_loadu(a + i + VF_N), vf_loadu(b + i + VF_N), a1);
a2 = vf_fma(vf_loadu(a + i + 2 * VF_N), vf_loadu(b + i + 2 * VF_N), a2);
a3 = vf_fma(vf_loadu(a + i + 3 * VF_N), vf_loadu(b + i + 3 * VF_N), a3);
}
for (; i + VF_N <= n; i += VF_N) a0 = vf_fma(vf_loadu(a + i), vf_loadu(b + i), a0);
float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3)));
for (; i < n; ++i) s += a[i] * b[i];
return s;
}
/* acc += w * v, vectorised. */
static inline void axpy(float* acc, const float* v, float w, int64_t n) {
const vf vw = vf_set1(w);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N)
vf_storeu(acc + i, vf_fma(vw, vf_loadu(v + i), vf_loadu(acc + i)));
for (; i < n; ++i) acc[i] += w * v[i];
}
/* ------------------------------------------------------------------ attn_paged */
/* Prefill form, taken when the queries are uniform (!cus) and long (q_len >= 32): the
* whole context is shared across q_len rows, so widening K/V per q-row (the decode form in
* AVX_KERNEL below) re-converts the context q_len times -- 512x over at the bench shape.
* Each (seq, kv-head, q-block) unit widens the context ONCE into panels and runs its rows
* off them. The per-row math is unchanged -- dots ascending, the online softmax with the
* same rescale points, the same scalar exps -- so rows match the decode form bit for bit;
* only the loads move. q-blocks of 64 keep the units many for the engine's thread pool.
* Ragged (cus) inputs stay on the decode form, whatever their lengths. */
static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream stream) {
const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[7];
const RadTensor* kdes = rad_arg_in(a, 4);
const RadTensor* vdes = rad_arg_in(a, 5);
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
const int64_t gqa = p_int(a, "gqa", 1);
const int64_t block_size = p_int(a, "block_size", kv->rank == 4 ? kv->shape[2] : 0);
const int causal = (int)p_int(a, "causal", 1);
const int64_t window = p_int(a, "window", 0);
if (head_dim <= 0 || gqa <= 0 || block_size <= 0) return RAD_E_SHAPE;
if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
const int64_t kv_heads = kv->rank == 4 ? kv->shape[1] : 0;
if (kv_heads <= 0) return RAD_E_SHAPE;
const int64_t q_heads = gqa * kv_heads;
const int64_t n_seq = numel(su);
/* THE QUERY LENGTH IS PER SEQUENCE. The operand holds every sequence's rows back to back, so
* its row count is n_seq * q_len; taking the whole of it as one sequence's length puts
* sequence s at rows s * rows and writes every sequence after the first past `out`. */
const int64_t rows = numel(q) / (q_heads * head_dim);
if (n_seq <= 0 || rows <= 0 || rows % n_seq != 0) return RAD_E_SHAPE;
const int64_t q_len = rows / n_seq;
const int64_t max_blocks = bt->rank >= 2 ? bt->shape[bt->rank - 1] : numel(bt) / n_seq;
const int64_t bt_rs = bt->rank >= 2 ? bt->stride[bt->rank - 2] : max_blocks;
const int64_t bt_cs = bt->rank >= 2 ? bt->stride[bt->rank - 1] : 1;
const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
/* Read as [rows, q_heads, head_dim] at whatever rank they arrived, libref's reading: a rank-2
* q is a column slice whose row stride is its own (avx_common.h: row_stride). */
const int64_t q_ds = q->rank >= 2 ? q->stride[q->rank - 1] : 1;
const int64_t q_hs = q->rank >= 3 ? q->stride[q->rank - 2] : head_dim * q_ds;
const int64_t q_rs = row_stride(q, q_heads * head_dim);
const int64_t o_ds = o->rank >= 2 ? o->stride[o->rank - 1] : 1;
const int64_t o_hs = o->rank >= 3 ? o->stride[o->rank - 2] : head_dim * o_ds;
const int64_t o_rs = row_stride(o, q_heads * head_dim);
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
enum { QB = 64 };
const int64_t nqb = (q_len + QB - 1) / QB;
AVX_PARALLEL_FOR_IF(n_seq * kv_heads * nqb >= 4)
for (int64_t u = 0; u < n_seq * kv_heads * nqb; ++u) {
const int64_t qb = u % nqb, kh = (u / nqb) % kv_heads, s = u / (nqb * kv_heads);
const int64_t ctx = ldi(su, offlin(su, s));
if (ctx <= 0) continue;
const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
/* Panels plus one row frame: a single arena call, partitioned by hand. */
float* mem = scratch_f32((size_t)2 * (size_t)ctx * (size_t)head_dim +
(size_t)(3 * head_dim + AVX_KV_TILE) + 16);
float* Kp = mem;
float* Vp = mem + (size_t)ctx * (size_t)head_dim;
float* frame = Vp + (size_t)ctx * (size_t)head_dim;
float* qbuf = frame;
float* kbuf = frame + head_dim;
float* acc = frame + 2 * head_dim;
float* sbuf = frame + 3 * head_dim;
int64_t* kbv = (int64_t*)scratch_raw((size_t)ctx * sizeof(int64_t) + 64);
/* Widen the context once. Rows past max_blocks stay invalid, exactly as the
* per-row loop's break would leave them. */
int64_t nkeys = 0;
for (int64_t j = 0; j < ctx; ++j) {
if (j / block_size >= max_blocks) break;
const int64_t blk = ldi(bt, s * bt_rs + (j / block_size) * bt_cs);
if (blk < 0) {
kbv[j] = -1;
continue;
}
kbv[j] = blk * kvv.sb + kh * kvv.sh + (j % block_size) * kvv.so;
const float* kr = head_f32(kv, kbv[j], kvv.sd, head_dim, kds, kbuf);
for (int64_t d = 0; d < head_dim; ++d) Kp[(size_t)j * head_dim + d] = kr[d];
const float* vr = head_f32(kv, kbv[j] + head_dim * kvv.sd, kvv.sd, head_dim,
vds, kbuf);
for (int64_t d = 0; d < head_dim; ++d) Vp[(size_t)j * head_dim + d] = vr[d];
nkeys = j + 1;
}
const int64_t i0 = qb * QB, i1 = (i0 + QB < q_len) ? i0 + QB : q_len;
/* One gqa row at a time. A joint-rows form -- each key row loaded once for all gqa
* dots -- measures identical on a long-query shape: the nest is compute-saturated
* (dots, axpy, scalar exps) rather than bound by panel traffic, so sharing the loads
* frees nothing. Do not switch to it without measuring. */
for (int64_t g = 0; g < gqa; ++g) {
const int64_t h = kh * gqa + g;
for (int64_t i = i0; i < i1; ++i) {
const int64_t tok = s * q_len + i;
const int64_t pos = ctx - q_len + i;
const int64_t qb2 = tok * q_rs + h * q_hs;
const int64_t ob = tok * o_rs + h * o_hs;
const float* qv = head_f32(q, qb2, q_ds, head_dim, 1.0f, qbuf);
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
float m = -INFINITY, l = 0.0f;
int ntile = 0;
int64_t kbase[AVX_KV_TILE];
auto flush = [&]() {
if (ntile == 0) return;
float tmax = sbuf[0];
for (int t = 1; t < ntile; ++t) if (sbuf[t] > tmax) tmax = sbuf[t];
if (tmax > m) {
const float r = (m == -INFINITY) ? 0.0f : std::exp(m - tmax);
if (r != 1.0f) {
const vf vr = vf_set1(r);
int64_t d = 0;
for (; d + VF_N <= head_dim; d += VF_N)
vf_storeu(acc + d, vf_mul(vf_loadu(acc + d), vr));
for (; d < head_dim; ++d) acc[d] *= r;
l *= r;
}
m = tmax;
}
/* Scalar exps here, deliberately: the tile-vectorised form
* (vf_exp, as in the decode flush) measures neutral-to-slower on a
* long-query shape, because the nest is bound elsewhere. The values
* are the same either way. */
for (int t = 0; t < ntile; ++t) {
const float w = std::exp(sbuf[t] - m);
l += w;
axpy(acc, Vp + (size_t)kbase[t] * head_dim, w, head_dim);
}
ntile = 0;
};
for (int64_t j = 0; j < nkeys; ++j) {
if (causal ? (j > pos) : (j >= ctx)) continue;
if (window > 0) {
const int64_t d = pos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) continue;
}
if (kbv[j] < 0) continue;
sbuf[ntile] = dotf(qv, Kp + (size_t)j * head_dim, head_dim) * scale;
kbase[ntile] = j;
if (++ntile == AVX_KV_TILE) flush();
}
flush();
if (m == -INFINITY) {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f);
continue;
}
const float inv = l > 0.0f ? 1.0f / l : 0.0f;
if (o_ds == 1) {
const vf vi = vf_set1(inv);
int64_t d = 0;
for (; d + VF_N <= head_dim; d += VF_N)
vf_storeu(acc + d, vf_mul(vf_loadu(acc + d), vi));
for (; d < head_dim; ++d) acc[d] *= inv;
out_row(o, ob, head_dim, acc);
} else {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv);
}
}
}
}
return RAD_OK;
}
AVX_KERNEL(attn_paged) {
if (a->n_t < 8) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[7];
const RadTensor* kdes = rad_arg_in(a, 4);
const RadTensor* vdes = rad_arg_in(a, 5);
const RadTensor* cus = rad_arg_in(a, 6);
if (!q->data || !kv->data || !bt->data || !su->data || !o->data) return RAD_E_INVAL;
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
const int64_t gqa = p_int(a, "gqa", 1);
/* `block_size` is RAD_DERIVED (docs/OPS.md), so a caller who did not pin it and resolved to a
* kernel that declares no RAD_C_EQ for it arrives here without the key. The cache tensor says
* what the block size is; reading it off the operand is this plugin's rule anyway. */
const int64_t block_size = p_int(a, "block_size", kv->rank == 4 ? kv->shape[2] : 0);
const int causal = (int)p_int(a, "causal", 1);
const int64_t window = p_int(a, "window", 0);
if (head_dim <= 0 || gqa <= 0 || block_size <= 0) return RAD_E_SHAPE;
if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
const int64_t kv_heads = kv->rank == 4 ? kv->shape[1] : 0;
if (kv_heads <= 0) return RAD_E_SHAPE;
const int64_t q_heads = gqa * kv_heads;
if (q->rank >= 3 && q->shape[q->rank - 2] != q_heads) return RAD_E_SHAPE;
const int64_t n_seq = numel(su);
const int64_t rows = numel(q) / (q_heads * head_dim);
if (n_seq <= 0 || rows <= 0) return RAD_E_SHAPE;
if (!cus && rows % n_seq != 0) return RAD_E_SHAPE;
if (cus && numel(cus) != n_seq + 1) return RAD_E_SHAPE;
const int64_t q_len = cus ? 0 : rows / n_seq;
if (numel(o) < rows * q_heads * head_dim) return RAD_E_SHAPE;
if (kv->rank == 4 && kv->shape[2] != block_size) return RAD_E_SHAPE;
if (kv->rank == 4 && kv->shape[3] < 2 * head_dim) return RAD_E_SHAPE;
const int64_t max_blocks = bt->rank >= 2 ? bt->shape[bt->rank - 1] : numel(bt) / n_seq;
const int64_t bt_rs = bt->rank >= 2 ? bt->stride[bt->rank - 2] : max_blocks;
const int64_t bt_cs = bt->rank >= 2 ? bt->stride[bt->rank - 1] : 1;
const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
/* Row strides of q and out read as [rows, q_heads, head_dim], at whatever rank they arrived --
* libref's reading. A rank-2 operand is a column slice whose row stride is its own. */
const int64_t q_ds = q->rank >= 2 ? q->stride[q->rank - 1] : 1;
const int64_t q_hs = q->rank >= 3 ? q->stride[q->rank - 2] : head_dim * q_ds;
const int64_t q_rs = row_stride(q, q_heads * head_dim);
const int64_t o_ds = o->rank >= 2 ? o->stride[o->rank - 1] : 1;
const int64_t o_hs = o->rank >= 3 ? o->stride[o->rank - 2] : head_dim * o_ds;
const int64_t o_rs = row_stride(o, q_heads * head_dim);
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
/* Uniform long queries share one context: the panel form widens it once instead of once
* per row. Ragged (cus) inputs stay below whatever their lengths. */
if (!cus && q_len >= 32) return attn_paged_prefill(a, stream);
/* Rows run as (token, kv-head) groups: the gqa query rows of a group share the key
* and value rows behind every key, so each is widened once for gqa dots/axpys rather
* than once per row. Per-row arithmetic is untouched -- rows match bit for bit. */
const int64_t total = rows * kv_heads;
AVX_PARALLEL_FOR_IF(total >= 2)
for (int64_t tidx = 0; tidx < total; ++tidx) {
const int64_t kh = tidx % kv_heads;
const int64_t tok = tidx / kv_heads;
/* Which sequence owns this token and where inside its query it sits. Linear rather
* than a binary search: n_seq is a handful. Once per group, not once per row. */
int64_t s = 0, qlen = q_len, i = 0;
if (cus) {
while (s + 1 < n_seq && ldi(cus, offlin(cus, s + 1)) <= tok) ++s;
const int64_t beg = ldi(cus, offlin(cus, s));
qlen = ldi(cus, offlin(cus, s + 1)) - beg;
i = tok - beg;
} else {
s = tok / q_len;
i = tok - s * q_len;
}
if (qlen <= 0) continue;
const int64_t ctx = ldi(su, offlin(su, s));
const int64_t pos = ctx - qlen + i;
const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
/* One arena call carves the whole frame, because a second one may reallocate and
* invalidate the first pointer (avx_common.h). */
float* frame = (float*)scratch_f32((size_t)gqa * (size_t)(2 * head_dim + AVX_KV_TILE + 2) +
(size_t)(2 * head_dim) + 16);
float* qpan = frame; /* [gqa, head_dim] queries */
float* krow = qpan + (size_t)gqa * head_dim; /* one widened key row */
float* vrow = krow + head_dim; /* one widened value row */
float* accs = vrow + head_dim; /* [gqa, head_dim] */
float* sbufs = accs + (size_t)gqa * head_dim; /* [gqa, TILE] scores */
float* mm = sbufs + (size_t)gqa * AVX_KV_TILE;
float* ll = mm + gqa;
int64_t kbase[AVX_KV_TILE];
for (int64_t g = 0; g < gqa; ++g) {
const int64_t h = kh * gqa + g;
float* qd = qpan + g * head_dim;
const float* qr = head_f32(q, tok * q_rs + h * q_hs, q_ds, head_dim, 1.0f, qd);
if (qr != qd) std::memcpy(qd, qr, (size_t)head_dim * sizeof(float));
float* ac = accs + g * head_dim;
for (int64_t d = 0; d < head_dim; ++d) ac[d] = 0.0f;
mm[g] = -INFINITY;
ll[g] = 0.0f;
}
int ntile = 0;
/* Flush a tile: per row, update the running maximum, rescale what is already
* accumulated, then add this tile's weighted values in ascending key order. The
* value row is widened once per key and shared across the group's axpys. */
auto flush = [&]() {
if (ntile == 0) return;
for (int64_t g = 0; g < gqa; ++g) {
float* sb = sbufs + g * AVX_KV_TILE;
float* ac = accs + g * head_dim;
float m = mm[g], l = ll[g];
float tmax = sb[0];
for (int t = 1; t < ntile; ++t) if (sb[t] > tmax) tmax = sb[t];
if (tmax > m) {
const float r = (m == -INFINITY) ? 0.0f : std::exp(m - tmax);
if (r != 1.0f) {
const vf vr = vf_set1(r);
int64_t d = 0;
for (; d + VF_N <= head_dim; d += VF_N)
vf_storeu(ac + d, vf_mul(vf_loadu(ac + d), vr));
for (; d < head_dim; ++d) ac[d] *= r;
l *= r;
}
m = tmax;
}
/* The tile's exps, vectorised: the accumulation keeps its order. */
{
const vf vm = vf_set1(m);
int t = 0;
for (; t + VF_N <= ntile; t += VF_N)
vf_storeu(sb + t, vf_exp(vf_sub(vf_loadu(sb + t), vm)));
for (; t < ntile; ++t) sb[t] = std::exp(sb[t] - m);
}
mm[g] = m;
ll[g] = l;
}
for (int t = 0; t < ntile; ++t) {
/* One widening per key for the whole group, then gqa axpys. */
const float* vv = head_f32(kv, kbase[t] + head_dim * kvv.sd, kvv.sd, head_dim,
vds, vrow);
for (int64_t g = 0; g < gqa; ++g) {
const float w = sbufs[g * AVX_KV_TILE + t];
ll[g] += w;
axpy(accs + g * head_dim, vv, w, head_dim);
}
}
ntile = 0;
};
for (int64_t j = 0; j < ctx; ++j) {
if (causal ? (j > pos) : (j >= ctx)) continue;
if (window > 0) {
const int64_t d = pos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) continue;
}
if (j / block_size >= max_blocks) break; /* the table is only this wide */
const int64_t blk = ldi(bt, s * bt_rs + (j / block_size) * bt_cs);
if (blk < 0) continue;
const int64_t kb = blk * kvv.sb + kh * kvv.sh + (j % block_size) * kvv.so;
/* One widening per key for the whole group, then gqa dots. */
const float* kvrow = head_f32(kv, kb, kvv.sd, head_dim, kds, krow);
for (int64_t g = 0; g < gqa; ++g)
sbufs[g * AVX_KV_TILE + ntile] =
dotf(qpan + g * head_dim, kvrow, head_dim) * scale;
kbase[ntile] = kb;
if (++ntile == AVX_KV_TILE) flush();
}
flush();
for (int64_t g = 0; g < gqa; ++g) {
const int64_t h = kh * gqa + g;
const int64_t ob = tok * o_rs + h * o_hs;
float* ac = accs + g * head_dim;
if (mm[g] == -INFINITY) {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f);
continue;
}
const float inv = ll[g] > 0.0f ? 1.0f / ll[g] : 0.0f;
if (o_ds == 1) {
const vf vi = vf_set1(inv);
int64_t d = 0;
for (; d + VF_N <= head_dim; d += VF_N)
vf_storeu(ac + d, vf_mul(vf_loadu(ac + d), vi));
for (; d < head_dim; ++d) ac[d] *= inv;
out_row(o, ob, head_dim, ac);
} else {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, ac[d] * inv);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ attn_dense */
/* The vision tower's: nothing paged, nothing quantised, `cu_seqlens` bounding one image (or one
* attention window) per entry so a whole batch is ONE launch rather than a per-segment loop and a
* concatenate. Causal is a parameter because a dense decoder-only prefill wants the same kernel.
*
* Same online softmax as the paged form, and the tile is over the segment rather than the page
* table -- so the K and V rows are consecutive in memory and the hardware prefetcher sees a single
* stream, which is the one thing the dense form has that the paged one cannot. */
AVX_KERNEL(attn_dense) {
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3], *o = &a->t[4];
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
const int64_t gqa = p_int(a, "gqa", 1);
const int causal = (int)p_int(a, "causal", 0);
if (head_dim <= 0 || gqa <= 0) return RAD_E_SHAPE;
if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2] : 1;
const int64_t kv_heads = q_heads / gqa;
if (kv_heads <= 0 || q_heads % gqa != 0) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1;
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t total_q = numel(q) / (q_heads * head_dim);
if (numel(o) < total_q * q_heads * head_dim) return RAD_E_SHAPE;
if (numel(k) < total_q * kv_heads * head_dim) return RAD_E_SHAPE;
if (numel(v) < total_q * kv_heads * head_dim) return RAD_E_SHAPE;
/* libref's reading of all four, at whatever rank they arrived: a rank-2 operand is a column
* slice whose row stride is its own (avx_common.h: row_stride). */
const int64_t q_ds = q->rank >= 2 ? q->stride[q->rank - 1] : 1;
const int64_t q_hs = q->rank >= 3 ? q->stride[q->rank - 2] : head_dim * q_ds;
const int64_t q_rs = row_stride(q, q_heads * head_dim);
const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1;
const int64_t k_hs = k->rank >= 3 ? k->stride[k->rank - 2] : head_dim * k_ds;
const int64_t k_rs = row_stride(k, kv_heads * head_dim);
const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1;
const int64_t v_hs = v->rank >= 3 ? v->stride[v->rank - 2] : head_dim * v_ds;
const int64_t v_rs = row_stride(v, kv_heads * head_dim);
const int64_t o_ds = o->rank >= 2 ? o->stride[o->rank - 1] : 1;
const int64_t o_hs = o->rank >= 3 ? o->stride[o->rank - 2] : head_dim * o_ds;
const int64_t o_rs = row_stride(o, q_heads * head_dim);
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
AVX_PARALLEL_FOR_IF(n_seq * q_heads >= 2)
for (int64_t sh = 0; sh < n_seq * q_heads; ++sh) {
const int64_t s = sh / q_heads, h = sh % q_heads, kh = h / gqa;
const int64_t b0 = ldi(cu, offlin(cu, s));
const int64_t b1 = ldi(cu, offlin(cu, s + 1));
float* frame = (float*)scratch_f32((size_t)(4 * head_dim + AVX_KV_TILE) + 16);
float* qbuf = frame;
float* kbuf = frame + head_dim;
float* vbuf = frame + 2 * head_dim;
float* acc = frame + 3 * head_dim;
float* sbuf = frame + 4 * head_dim;
int64_t vbase[AVX_KV_TILE];
for (int64_t i = b0; i < b1; ++i) {
const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs;
const int64_t jend = causal ? (i + 1) : b1;
const float* qv = head_f32(q, qb, q_ds, head_dim, 1.0f, qbuf);
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
float m = -INFINITY, l = 0.0f;
int ntile = 0;
auto flush = [&]() {
if (ntile == 0) return;
float tmax = sbuf[0];
for (int t = 1; t < ntile; ++t) if (sbuf[t] > tmax) tmax = sbuf[t];
if (tmax > m) {
const float r = (m == -INFINITY) ? 0.0f : std::exp(m - tmax);
if (r != 1.0f) {
const vf vr = vf_set1(r);
int64_t d = 0;
for (; d + VF_N <= head_dim; d += VF_N)
vf_storeu(acc + d, vf_mul(vf_loadu(acc + d), vr));
for (; d < head_dim; ++d) acc[d] *= r;
l *= r;
}
m = tmax;
}
/* The tile's exps, vectorised (see the prefill flush above): the
* accumulation keeps its order. */
{
const vf vm = vf_set1(m);
int t = 0;
for (; t + VF_N <= ntile; t += VF_N)
vf_storeu(sbuf + t, vf_exp(vf_sub(vf_loadu(sbuf + t), vm)));
for (; t < ntile; ++t) sbuf[t] = std::exp(sbuf[t] - m);
}
for (int t = 0; t < ntile; ++t) {
const float w = sbuf[t];
l += w;
axpy(acc, head_f32(v, vbase[t], v_ds, head_dim, 1.0f, vbuf), w, head_dim);
}
ntile = 0;
};
for (int64_t j = b0; j < jend; ++j) {
const float* kvr = head_f32(k, j * k_rs + kh * k_hs, k_ds, head_dim, 1.0f, kbuf);
sbuf[ntile] = dotf(qv, kvr, head_dim) * scale;
vbase[ntile] = j * v_rs + kh * v_hs;
if (++ntile == AVX_KV_TILE) flush();
}
flush();
if (m == -INFINITY) {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f);
continue;
}
const float inv = l > 0.0f ? 1.0f / l : 0.0f;
if (o_ds == 1) {
const vf vi = vf_set1(inv);
int64_t d = 0;
for (; d + VF_N <= head_dim; d += VF_N)
vf_storeu(acc + d, vf_mul(vf_loadu(acc + d), vi));
for (; d < head_dim; ++d) acc[d] *= inv;
out_row(o, ob, head_dim, acc);
} else {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ kv_store */
/* The cache operand is INOUT and not OUT: this op touches only the mapped slots and every other
* slot in the pool must survive it, which is a liveness fact the buffer planner has to know.
*
* A NEGATIVE slot is SKIPPED, and that is a documented value rather than an accident: it is how a
* padded batch row says "this token has no cache slot". libr4d treats slot <= 0 as null because
* vLLM reserves block 0; a generic implementation must not steal a valid slot, so only the
* strictly negative is skipped -- libref's rule, and the two have to agree or a padded step writes
* different bytes under the two plugins. */
AVX_KERNEL(kv_store) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *k = &a->t[0], *v = &a->t[1], *sm = &a->t[2], *kv = &a->t[3];
const int64_t head_dim = p_int(a, "head_dim", k->rank >= 3 ? k->shape[k->rank - 1] : 0);
const int64_t block_size = p_int(a, "block_size", 0);
const int64_t kv_heads = p_int(a, "n_head_kv", kv->rank == 4 ? kv->shape[1] : 0);
if (head_dim <= 0 || block_size <= 0 || kv_heads <= 0) return RAD_E_SHAPE;
if (kv->rank == 4 && (kv->shape[1] != kv_heads || kv->shape[2] != block_size ||
kv->shape[3] < 2 * head_dim)) return RAD_E_SHAPE;
const int64_t M = numel(sm);
if (M <= 0 || numel(k) < M * kv_heads * head_dim) return RAD_E_SHAPE;
const int64_t n_blocks = kv->rank == 4 ? kv->shape[0] : 0;
/* `k` AND `v` ARRIVE RANK 2 FROM AN ARCHITECTURE THAT DOES NOT DE-INTERLEAVE ITS PROJECTION --
* a column slice of the fused QKV plane, whose row stride is the whole projection's width.
* Deriving the stride from the shape puts token 0 in the right slot and fills every later
* token's slot out of the previous token's query rows. libref's reading, through row_stride. */
const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1;
const int64_t k_hs = k->rank >= 3 ? k->stride[k->rank - 2] : head_dim * k_ds;
const int64_t k_rs = row_stride(k, kv_heads * head_dim);
const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1;
const int64_t v_hs = v->rank >= 3 ? v->stride[v->rank - 2] : head_dim * v_ds;
const int64_t v_rs = row_stride(v, kv_heads * head_dim);
const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
/* Validated before the loop, because an OpenMP body cannot return. */
for (int64_t t = 0; t < M; ++t) {
const int64_t slot = ldi(sm, offlin(sm, t));
if (slot >= 0 && n_blocks > 0 && slot / block_size >= n_blocks) return RAD_E_SHAPE;
}
AVX_PARALLEL_FOR_IF(M * kv_heads * head_dim >= AVX_PAR_MIN)
for (int64_t t = 0; t < M; ++t) {
const int64_t slot = ldi(sm, offlin(sm, t));
if (slot < 0) continue;
const int64_t blk = slot / block_size, off = slot % block_size;
float* buf = scratch_f32((size_t)head_dim);
for (int64_t h = 0; h < kv_heads; ++h) {
const int64_t cb = blk * kvv.sb + h * kvv.sh + off * kvv.so;
/* The head at a time, through the row converter, so a bf16 cache fed a bf16 activation
* is a widen and a narrow of a whole head rather than 2*head_dim dtype switches. The
* strided case falls back per element, which is what a non-unit cache stride means. */
if (k_ds == 1 && kvv.sd == 1) {
row_to_f32(k->dtype, byte_at(k->data, k->dtype, t * k_rs + h * k_hs), buf, head_dim);
out_row(kv, cb, head_dim, buf);
} else {
for (int64_t d = 0; d < head_dim; ++d)
stt(kv, cb + d * kvv.sd, ldt(k, t * k_rs + h * k_hs + d * k_ds));
}
if (v_ds == 1 && kvv.sd == 1) {
row_to_f32(v->dtype, byte_at(v->data, v->dtype, t * v_rs + h * v_hs), buf, head_dim);
out_row(kv, cb + head_dim, head_dim, buf);
} else {
for (int64_t d = 0; d < head_dim; ++d)
stt(kv, cb + (head_dim + d) * kvv.sd, ldt(v, t * v_rs + h * v_hs + d * v_ds));
}
}
}
return RAD_OK;
}
/* ================================================================== rotary
*
* NeoX pairs element i with i + rotary_dim/2; GPT-J (the "interleaved" style) pairs 2i with 2i+1.
* Which one a checkpoint wants is a property of the checkpoint, so it is a parameter and not a
* guess -- and getting it wrong produces fluent text with a broken sense of position, which is the
* hardest kind of wrong to notice.
*
* THE ANGLE TABLE IS THE WHOLE OPTIMISATION HERE. libref computes
* `1/pow(theta, 2i/rot)` and then a cos and a sin FOR EVERY (token, head, i) -- three libm calls
* per element, on an op that otherwise does two multiplies and an add. But the angle depends only
* on (position, i): every head of a token wants the same cos/sin. Building the row's table once
* and reusing it across all n_head + n_head_kv heads removes (heads - 1)/heads of the transcendental
* work, which at 32 heads is 97% of it, and the values are identical because they are the same
* computation performed once instead of many times -- so this is bit-identical, not merely close.
*
* The inverse frequencies depend only on `i` and are built ONCE PER LAUNCH for the same reason.
*
* What is NOT vectorised is the cos/sin themselves: a vector sincos is a polynomial with its own
* accuracy, and `rope` feeds a position signal where a fraction of a ULP is exactly the error that
* produces fluent text with wrong positions. The table makes them rare enough not to matter. */
/* The multi-component modes (docs/OPS.md, `rope`): which position component drives each of the
* rot/2 frequencies, and for `axial` a ladder per section. libref's rope_freqs states the same
* rule; the two are checked against each other by avx_check. */
enum { ROPE_NEOX = 0, ROPE_GPTJ = 1, ROPE_MROPE = 2, ROPE_IMROPE = 3, ROPE_AXIAL = 4 };
/* cos in [0, half), sin in [half, rot). Same layout `rope_table` writes, deliberately.
*
* NOT sincosf: it is bit-identical to the two separate calls over a sweep of millions of angles,
* but measures SLOWER than them, because glibc's joint wrapper costs more than two fast-path
* calls. */
static void angles(float* cs, const float* invf, int64_t half, float pos) {
for (int64_t i = 0; i < half; ++i) {
const float ang = pos * invf[i];
cs[i] = std::cos(ang);
cs[half + i] = std::sin(ang);
}
}
/* ...and with a position per component, `comp[i]` naming the one frequency i reads. */
static void angles_multi(float* cs, const float* invf, const int* comp, int64_t half,
const float* pos) {
for (int64_t i = 0; i < half; ++i) {
const float ang = pos[comp[i]] * invf[i];
cs[i] = std::cos(ang);
cs[half + i] = std::sin(ang);
}
}
static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot, int mode,
const float* cs, int64_t half, float* buf) {
if (mode == ROPE_NEOX && ds == 1) {
/* x0 and x1 are two contiguous runs of `half`, so the whole rotation is vector work. */
row_to_f32(t->dtype, byte_at(t->data, t->dtype, base), buf, rot);
int64_t i = 0;
for (; i + VF_N <= half; i += VF_N) {
const vf x0 = vf_loadu(buf + i), x1 = vf_loadu(buf + half + i);
const vf c = vf_loadu(cs + i), s = vf_loadu(cs + half + i);
vf_storeu(buf + i, vf_sub(vf_mul(x0, c), vf_mul(x1, s)));
vf_storeu(buf + half + i, vf_add(vf_mul(x0, s), vf_mul(x1, c)));
}
for (; i < half; ++i) {
const float x0 = buf[i], x1 = buf[half + i];
buf[i] = x0 * cs[i] - x1 * cs[half + i];
buf[half + i] = x0 * cs[half + i] + x1 * cs[i];
}
out_row(t, base, rot, buf);
return;
}
/* GPT-J's interleave, and every strided case. The pairs are adjacent, so a vector form needs a
* de-interleave and a re-interleave for two multiplies -- not worth the code on a layout only
* older checkpoints use. */
for (int64_t i = 0; i < half; ++i) {
const int64_t i0 = (mode == ROPE_GPTJ) ? 2 * i : i;
const int64_t i1 = (mode == ROPE_GPTJ) ? 2 * i + 1 : i + half;
const float x0 = ldt(t, base + i0 * ds), x1 = ldt(t, base + i1 * ds);
const float c = cs[i], s = cs[half + i];
stt(t, base + i0 * ds, x0 * c - x1 * s);
stt(t, base + i1 * ds, x0 * s + x1 * c);
}
}
static float* inv_freqs(int64_t half, int64_t rot, float theta) {
float* f = (float*)scratch_raw((size_t)half * sizeof(float));
for (int64_t i = 0; i < half; ++i)
f[i] = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot);
return f;
}
AVX_KERNEL(rope) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *qkv = &a->t[0], *pos = &a->t[1];
const int64_t head_dim = p_int(a, "head_dim", 0);
const int64_t n_head = p_int(a, "n_head", 0);
const int64_t n_head_kv = p_int(a, "n_head_kv", 0);
const float theta = p_f32(a, "theta", 10000.0f);
const float rscale = p_f32(a, "scale", 1.0f);
static const char* kModes[] = { "neox", "gptj", "mrope", "imrope", "axial" };
const int mode = p_enum(a, "mode", kModes, 5, -1);
if (mode < 0) return RAD_E_UNSUPPORTED;
const int64_t rot = p_int(a, "rotary_dim", head_dim);
if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
/* [M] one component a token, or [C, M] component-major with `sections`. */
int64_t sec[8] = {};
int n_sec = 0;
for (const char* v = p_str(a, "sections", nullptr); v && *v && n_sec < 8;) {
char* e = nullptr;
const long long x = std::strtoll(v, &e, 10);
if (e == v) break;
if (x <= 0) return RAD_E_SHAPE;
sec[n_sec++] = x;
v = e;
}
const bool multi = pos->rank >= 2;
const int64_t n_comp = multi ? pos->shape[0] : 1;
if (multi && (mode <= ROPE_GPTJ || n_sec <= 0 || n_comp > 8 ||
n_comp < (mode == ROPE_IMROPE ? 3 : n_sec)))
return RAD_E_SHAPE;
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
const int64_t M = multi ? pos->shape[1] : numel(pos);
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row;
const int64_t ds = laststride(qkv);
const int64_t half = rot / 2;
float* invf = inv_freqs(half, rot, theta);
int comp[512] = {};
if (half > 512) return RAD_E_UNSUPPORTED;
if (multi) {
int64_t start[8] = {}, total = 0;
for (int c = 0; c < n_sec; ++c) { start[c] = total; total += sec[c]; }
if ((mode == ROPE_MROPE || mode == ROPE_AXIAL) && total != half) return RAD_E_SHAPE;
for (int64_t i = 0; i < half; ++i) {
int c = 0;
if (mode == ROPE_MROPE || mode == ROPE_AXIAL) {
while (c + 1 < n_sec && i >= start[c + 1]) ++c;
if (mode == ROPE_AXIAL)
invf[i] = 1.0f / std::pow(theta, (float)(2 * (i - start[c])) /
(float)(2 * sec[c]));
} else if (mode == ROPE_IMROPE) {
if (i % 3 == 1 && i < 3 * sec[1]) c = 1;
else if (i % 3 == 2 && i < 3 * sec[2]) c = 2;
}
comp[i] = c;
}
}
const int pair_mode = mode == ROPE_GPTJ ? ROPE_GPTJ : ROPE_NEOX;
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
AVX_PARALLEL_FOR_IF(M * (n_head + n_head_kv) * rot >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
const float div = rscale != 0.0f ? rscale : 1.0f;
const int64_t row = m * rs;
float* cs = scratch_f32((size_t)rot);
float* buf = scratch_f32_b((size_t)rot);
if (multi) {
float pc[8];
for (int64_t c = 0; c < n_comp; ++c) pc[c] = (float)ldi(pos, c * pcs + m * pms) / div;
angles_multi(cs, invf, comp, half, pc);
} else {
angles(cs, invf, half, (float)ldi(pos, offlin(pos, m)) / div);
}
/* Q heads then K heads. The V heads that follow are left alone, which is the whole reason
* this op takes the fused qkv rather than two tensors. */
for (int64_t h = 0; h < n_head + n_head_kv; ++h)
rope_head(qkv, row + h * head_dim * ds, ds, rot, pair_mode, cs, half, buf);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ qk_norm_rope */
/* An RMS norm over each head against its own gain, then RoPE.
*
* THE NORM OUTPUT IS ROUNDED TO THE TENSOR'S DTYPE BEFORE THE ROTATION. That is not an accident of
* writing it back in place -- it is what the unfused pair does, because the norm stores a tensor
* and the rotation reads it, and libr4d's r4d_qk_norm_rope_gate matches the unfused reference for
* exactly this reason. A fused kernel that kept f32 across the seam would be half an ulp better
* and would fail a comparison against this. So the norm is written with out_row and the rotation
* re-reads it, rather than being carried in registers. */
AVX_KERNEL(qk_norm_rope) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *qkv = &a->t[0], *pos = &a->t[1], *qw = &a->t[2], *kw = &a->t[3];
const int64_t head_dim = p_int(a, "head_dim", 0);
const int64_t n_head = p_int(a, "n_head", 0);
const int64_t n_head_kv = p_int(a, "n_head_kv", 0);
const float theta = p_f32(a, "theta", 10000.0f);
const float eps = p_f32(a, "eps", 1e-6f);
const float rscale = p_f32(a, "scale", 1.0f);
const float wadd = p_f32(a, "wadd", 0.0f);
static const char* kModes[] = { "neox", "gptj" };
const int mode = p_enum(a, "mode", kModes, 2, ROPE_NEOX);
const int64_t rot = p_int(a, "rotary_dim", head_dim);
if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
if (numel(qw) < head_dim || numel(kw) < head_dim) return RAD_E_SHAPE;
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
const int64_t M = numel(pos);
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row;
const int64_t ds = laststride(qkv);
const int64_t half = rot / 2;
/* One arena call for the launch-invariant tables: the inverse frequencies and both widened
* gains. A second scratch_raw would reallocate under the parallel region. */
float* tab = (float*)scratch_raw((size_t)(half + 2 * head_dim) * sizeof(float) + 64);
float* invf = tab;
float* gq = tab + half;
float* gk = tab + half + head_dim;
for (int64_t i = 0; i < half; ++i)
invf[i] = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot);
for (int64_t d = 0; d < head_dim; ++d) {
gq[d] = ldt(qw, d * laststride(qw)) + wadd;
gk[d] = ldt(kw, d * laststride(kw)) + wadd;
}
AVX_PARALLEL_FOR_IF(M * (n_head + n_head_kv) * head_dim >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
const float p = (float)ldi(pos, offlin(pos, m)) / (rscale != 0.0f ? rscale : 1.0f);
const int64_t row = m * rs;
float* cs = scratch_f32((size_t)rot);
float* buf = scratch_f32_b((size_t)head_dim);
float* rbuf = scratch_f32_c((size_t)head_dim);
angles(cs, invf, half, p);
for (int64_t h = 0; h < n_head + n_head_kv; ++h) {
const float* g = h < n_head ? gq : gk;
const int64_t base = row + h * head_dim * ds;
const float* xv = head_f32(qkv, base, ds, head_dim, 1.0f, buf);
const float sc = 1.0f / std::sqrt(row_sumsq(xv, head_dim) / (float)head_dim + eps);
const vf vs = vf_set1(sc);
int64_t d = 0;
for (; d + VF_N <= head_dim; d += VF_N)
vf_storeu(rbuf + d, vf_mul(vf_mul(vf_loadu(xv + d), vs), vf_loadu(g + d)));
for (; d < head_dim; ++d) rbuf[d] = xv[d] * sc * g[d];
/* Written back through the operand's dtype, then re-read by rope_head -- the rounding
* across the seam is the contract. */
if (ds == 1) out_row(qkv, base, head_dim, rbuf);
else for (int64_t i = 0; i < head_dim; ++i) stt(qkv, base + i * ds, rbuf[i]);
rope_head(qkv, base, ds, rot, mode, cs, half, rbuf);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ rope_table */
/* The cos/sin plane a fused prologue reads instead of theta, written at each position's OWN row of
* a [max_ctx, rot] table: `rot` values a row, cos for the first rot/2 and sin for the second.
*
* THE ANGLES ARE `rope`'s, TO THE LAST OPERATION, and that is the whole contract: a fused rotation
* reading a table built any other way would be a different model by a fraction of a ULP per
* element -- fluent text, subtly wrong positions. So the two share `inv_freqs` and `angles` rather
* than each computing the angle their own way. Only the rows `positions` names are written; a
* negative position is a padded row and writes nothing. */
AVX_KERNEL(rope_table) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *pos = &a->t[0], *cs = &a->t[1];
const int64_t rot = p_int(a, "rot", 0);
const float theta = p_f32(a, "theta", 10000.0f);
const float rscale = p_f32(a, "scale", 1.0f);
if (rot < 2 || (rot & 1)) return RAD_E_SHAPE;
const int64_t M = numel(pos);
if (M <= 0 || numel(cs) % rot) return RAD_E_SHAPE;
const int64_t rows = numel(cs) / rot;
const int64_t half = rot / 2;
const float* invf = inv_freqs(half, rot, theta);
AVX_PARALLEL_FOR_IF(M * rot >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
const int64_t pp = ldi(pos, offlin(pos, m));
if (pp < 0 || pp >= rows) continue;
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
float* buf = scratch_f32((size_t)rot);
angles(buf, invf, half, p);
/* `cs` may be strided, and offlin has to be evaluated per element there -- which is what
* libref does unconditionally. The dense case is one row store. */
if (rad_tensor_is_contiguous(cs)) {
out_row(cs, pp * rot, rot, buf);
} else {
for (int64_t i = 0; i < rot; ++i) stt(cs, offlin(cs, pp * rot + i), buf[i]);
}
}
return RAD_OK;
}
+326
View File
@@ -0,0 +1,326 @@
/* avx_bench.cpp -- rad-avx-bench: what this machine can do, and what libavx gets of it.
*
* ============================== A SPEEDUP AGAINST libref IS NOT A RESULT ==============================
*
* libref is a nest of scalar loops with a per-element dtype switch and it says so in its own
* header. "libavx is 14x libref" is therefore a statement about libref, and this tool refuses to
* print it as though it were a statement about libavx. What it prints beside every op is the
* fraction of THIS MACHINE'S measured ceiling the kernel reaches -- and the ceiling is measured
* here, by --peak, rather than quoted off a spec sheet, because a spec sheet describes a part and
* not the machine it is in: a memory channel population, a thermal cap or a firmware setting that
* parks a link costs real throughput and shows up only under measurement.
*
* The libref column stays, because the ratio is what says an op is WIRED AT ALL, and because a
* kernel that is slower than the reference is a real and findable defect. It is reported as what
* it is.
*
* ============================== THE THINGS THAT MAKE A HOST BENCH LIE ==============================
*
* Each of these is a way a host benchmark quietly measures something other than the kernel:
*
* AN INOUT OPERAND ACCUMULATES ACROSS ITERATIONS. A twenty-iteration loop over `rope` leaves the
* tensor rotated twenty-one times, and a harness that does not reset between iterations reports
* a large error for a correct kernel. Timing is not immune -- an op whose cost depends on its input
* (every sampler that narrows in place) measures something different each time round. h_reset
* restores the drawn bytes between iterations and its cost is excluded from the timing.
*
* A CACHE-WARM LOOP CANNOT RANK A BANDWIDTH-BOUND KERNEL. Running the same 40 KB row a thousand
* times measures L1, so a warm loop ranks kernels by how they behave in cache and not by the
* bandwidth they need. --cold walks a working set larger than L3 between iterations; the default
* is warm and the column says which it is.
*
* THE FIRST CALL IS NOT THE STEADY STATE. The thread_local scratch arenas allocate on their
* first use at a size, so iteration one includes a malloc per thread. Warm-up iterations run
* before the clock starts.
*
* A MEDIAN, NOT A MEAN. One preempted iteration moves a mean and does not move a median, and on
* any machine that is also doing something else there is always one.
*/
#include "avx_harness.h"
#include "avx_isa.h"
#include <chrono>
#include <cinttypes>
#ifdef _OPENMP
#include <omp.h>
#endif
using Clock = std::chrono::steady_clock;
static double now_s() {
return std::chrono::duration<double>(Clock::now().time_since_epoch()).count();
}
static double median(std::vector<double>& v) {
if (v.empty()) return 0;
std::sort(v.begin(), v.end());
return v[v.size() / 2];
}
/* ================================================================== the machine's ceilings
*
* MEASURED, NOT QUOTED. Three numbers, and each is the ceiling for a different class of op here:
*
* FMA THROUGHPUT bounds the GEMMs. A dependency-free chain of FMAs on enough accumulators to
* cover the latency, all in registers, nothing touching memory. What comes out is what the
* machine can retire, including whatever clock it actually holds under a vector load -- which on
* a part with an AVX-512 offset is not the advertised boost.
*
* L1 BANDWIDTH bounds every elementwise op at a shape that fits, which is most of a decode step.
*
* DRAM BANDWIDTH bounds everything at prefill shapes and bounds `logits_gemm` always: a 248K
* vocabulary weight does not fit in any cache, so that op is a memory benchmark wearing a GEMM's
* name whatever the flops say.
*
* All three are single-threaded by default and scale with --threads, because a per-core ceiling is
* what an op that runs one row per thread is actually up against.
*/
static void bench_peak(Lib& avx, int threads) {
std::printf("\n== machine ceilings (measured here, not quoted) ==\n");
/* ---- FMA, PER ISA LEVEL, measured inside the plugin. It has to be: this file is
* baseline-compiled like the dispatcher (see avx_dispatch.cpp) and can only emit SSE2, so a
* ceiling computed here would be ten times below what an AVX-512 GEMM is actually up against
* and every kernel would look like it was doing well. `avx_peak_fma` runs the probe compiled
* with the level's own flags and hands back the FLOPS PERFORMED; the clock stays here, because
* it is here that the median over repetitions is taken. */
auto peak = (double (*)(int, int64_t))dlsym(avx.h, "avx_peak_fma");
if (peak) {
for (int lvl = 0; lvl < AVX_N_LEVELS; ++lvl) {
if (avx.isa_detect && lvl > avx.isa_detect()) {
std::printf(" FMA %-18s %8s (not executable on this CPU)\n",
avx.isa_name(lvl), "n/a");
continue;
}
std::vector<double> rates;
for (int rep = 0; rep < 5; ++rep) {
const int64_t iters = 1000000;
const double t0 = now_s();
const double fl = peak(lvl, iters);
const double dt = now_s() - t0;
rates.push_back(fl / dt);
}
/* The BEST of five, not the median: this is a CEILING, and a repetition that was
* preempted or ran at a lower clock is not evidence the machine cannot do better. The
* per-op numbers below take the median instead, for the opposite reason -- there the
* question is what a kernel does in practice. */
std::sort(rates.begin(), rates.end());
std::printf(" FMA %-18s %8.2f GFLOP/s (1 thread, in-register, no memory traffic)\n",
avx.isa_name(lvl), rates.back() / 1e9);
}
}
/* ---- memory, at three working-set sizes. A read-modify-write triad (a[i] = b[i] + s*c[i])
* because that is the traffic shape every elementwise op here has: two streams in, one out. */
auto triad = [&](size_t bytes_per_array, const char* label) {
const size_t n = bytes_per_array / sizeof(float);
std::vector<float> A(n), B(n), C(n);
for (size_t i = 0; i < n; ++i) { B[i] = (float)i * 1e-6f; C[i] = 1.0f; }
std::vector<double> ts;
for (int rep = 0; rep < 7; ++rep) {
const double t0 = now_s();
#ifdef _OPENMP
#pragma omp parallel for schedule(static) num_threads(threads)
#endif
for (int64_t i = 0; i < (int64_t)n; ++i) A[(size_t)i] = B[(size_t)i] + 0.5f * C[(size_t)i];
ts.push_back(now_s() - t0);
}
const double dt = median(ts);
/* Three arrays touched: two read, one written. The write also reads the line unless the
* store is non-temporal, which this is not -- so 3x is the honest count and 4x would be
* counting a read-for-ownership the compiler may or may not have elided. */
std::printf(" triad %-15s %8.2f GB/s (%zu threads, %.0f KiB working set)\n", label,
3.0 * (double)n * sizeof(float) / dt / 1e9, (size_t)threads,
3.0 * (double)bytes_per_array / 1024.0);
};
triad(16 * 1024, "L1");
triad(512 * 1024, "L2");
triad(256u * 1024 * 1024, "DRAM");
}
/* ================================================================== conversion rates
* The claim avx_support.cpp's header makes and does not carry the numbers for. Timed through the
* PLUGIN's own `cast` op at each ISA level, which is the only way to time the conversion the
* kernels actually use rather than a copy of it compiled here with different flags. */
static void bench_cvt(Lib& avx, Lib& ref) {
std::printf("\n== dtype conversion, through `cast` (MB/s of SOURCE bytes) ==\n");
const char* dts[] = { "bf16", "f16", "fp8_e4m3", "i8" };
const int64_t N = 1 << 16;
std::printf(" %-12s %10s %10s %10s %10s %10s\n", "pair", "scalar", "avx", "avx2", "avx512",
"libref");
for (const char* dt : dts)
for (int dir = 0; dir < 2; ++dir) {
const char* from = dir ? dt : "f32";
const char* to = dir ? "f32" : dt;
Case c{ "cast", { HI("M", 1), HI("n", N), HS("from", from), HS("to", to) }, 0, 0 };
const RadKernelInfo* kr = ref.row("cast");
const RadKernelInfo* ka = avx.row("cast");
if (!kr || !ka) continue;
Prepared pr = h_prepare(ref, kr, c, kr, ka);
if (!pr.ok) continue;
const uint32_t sdt = pr.opd[0].d.dtype;
const double src_bytes = (double)dt_bytes(sdt, N);
char line[512];
int off = std::snprintf(line, sizeof line, " %-12s", (std::string(from) + "->" + to).c_str());
for (int lvl = 0; lvl < AVX_N_LEVELS; ++lvl) {
if (avx.isa_force && avx.isa_force(lvl) != lvl) {
off += std::snprintf(line + off, sizeof line - off, " %10s", "n/a");
continue;
}
for (int w = 0; w < 20; ++w) ka->launch(&pr.ab, nullptr);
std::vector<double> ts;
for (int r = 0; r < 9; ++r) {
const double t0 = now_s();
for (int it = 0; it < 50; ++it) ka->launch(&pr.ab, nullptr);
ts.push_back((now_s() - t0) / 50);
}
off += std::snprintf(line + off, sizeof line - off, " %10.0f",
src_bytes / median(ts) / 1e6);
}
{
for (int w = 0; w < 3; ++w) kr->launch(&pr.aa, nullptr);
std::vector<double> ts;
for (int r = 0; r < 5; ++r) {
const double t0 = now_s();
kr->launch(&pr.aa, nullptr);
ts.push_back(now_s() - t0);
}
off += std::snprintf(line + off, sizeof line - off, " %10.0f",
src_bytes / median(ts) / 1e6);
}
std::printf("%s\n", line);
}
if (avx.isa_force) avx.isa_force(AVX_N_LEVELS - 1);
}
/* ================================================================== per-op timing */
struct Row {
std::string op, geom;
double t_ref = 0;
double t[AVX_N_LEVELS] = { 0, 0, 0, 0 };
double bytes = 0, flops = 0;
};
static double time_launch(const RadKernelInfo* k, RadArgs* args, Prepared& pr, bool is_ref,
int warm, int iters, int reps) {
for (int w = 0; w < warm; ++w) { k->launch(args, nullptr); h_reset(pr); }
std::vector<double> ts;
for (int r = 0; r < reps; ++r) {
double acc = 0;
for (int it = 0; it < iters; ++it) {
const double t0 = now_s();
k->launch(args, nullptr);
acc += now_s() - t0;
/* Outside the clock: an INOUT op must start from the drawn bytes every time or it is
* timing a different computation each round. */
h_reset(pr);
}
ts.push_back(acc / iters);
}
(void)is_ref;
return median(ts);
}
int main(int argc, char** argv) {
std::string ref_path = "libref.so", avx_path = "libavx.so", only_op;
bool do_peak = false, do_cvt = false, do_ops = true;
int threads = 1;
int iters = 20, reps = 7;
for (int i = 1; i < argc; ++i) {
const std::string s = argv[i];
auto next = [&]() -> const char* { return i + 1 < argc ? argv[++i] : ""; };
if (s == "--ref") ref_path = next();
else if (s == "--avx") avx_path = next();
else if (s == "--op") only_op = next();
else if (s == "--peak") { do_peak = true; do_ops = false; }
else if (s == "--cvt") { do_cvt = true; do_ops = false; }
else if (s == "--all") { do_peak = do_cvt = do_ops = true; }
else if (s == "--threads") threads = std::atoi(next());
else if (s == "--iters") iters = std::atoi(next());
else if (s == "-h" || s == "--help") {
std::printf(
"rad-avx-bench -- what this machine can do, and what libavx gets of it.\n\n"
" --ref PATH the reference plugin (default libref.so)\n"
" --avx PATH the plugin under test (default libavx.so)\n"
" --peak measure this machine's FMA and memory ceilings and stop\n"
" --cvt measure the dtype conversions per ISA level and stop\n"
" --all ceilings, conversions and every op\n"
" --op NAME only this op\n"
" --threads N OpenMP threads for the ceiling measurement (default 1)\n"
" --iters N timed iterations per rep (default 20)\n");
return 0;
}
}
#ifdef _OPENMP
/* ONE THREAD BY DEFAULT, and that is a measurement decision rather than a timid one. Every
* geometry in the case table is small -- deliberately, so the checker is fast -- and a
* 32-thread fork/join over a 640-element row measures the barrier. The per-core number is what
* ranks a kernel change; --threads is there for the ceiling, where the aggregate is the point. */
omp_set_num_threads(1);
#endif
Lib ref, avx;
if (!ref.open(ref_path.c_str()) || !avx.open(avx_path.c_str())) return 2;
std::printf("oracle : %s %s\nunder : %s %s\n", ref.info->name, ref.info->version,
avx.info->name, avx.info->version);
if (avx.isa_detect)
std::printf("cpu : highest executable level is %s\n", avx.isa_name(avx.isa_detect()));
if (do_peak) bench_peak(avx, threads);
if (do_cvt) bench_cvt(avx, ref);
if (!do_ops) return 0;
const std::vector<Case> cases = build_cases();
std::vector<Row> rows;
for (const Case& c : cases) {
if (!only_op.empty() && only_op != c.op) continue;
const RadKernelInfo* kr = ref.row(c.op);
const RadKernelInfo* ka = avx.row(c.op);
if (!kr || !ka) continue;
Prepared pr = h_prepare(ref, kr, c, kr, ka);
if (!pr.ok) continue;
if (ka->launch(&pr.ab, nullptr) == RAD_E_UNSUPPORTED) continue;
h_reset(pr);
Row r;
r.op = c.op;
r.geom = case_str(c);
r.bytes = c.bytes;
r.flops = c.flops;
/* libref gets fewer iterations: it is one to two orders slower and the whole run would be
* spent in the oracle. Its median over three is stable enough for a ratio. */
r.t_ref = time_launch(kr, &pr.aa, pr, true, 2, 3, 3);
for (int lvl = 0; lvl < AVX_N_LEVELS; ++lvl) {
if (avx.isa_force && avx.isa_force(lvl) != lvl) { r.t[lvl] = 0; continue; }
r.t[lvl] = time_launch(ka, &pr.ab, pr, false, 5, iters, reps);
}
rows.push_back(r);
}
std::printf("\n== per op, microseconds per launch (median of %d reps x %d iters, 1 thread, "
"cache-warm) ==\n", reps, iters);
std::printf("%-22s %9s %9s %9s %9s %9s %8s %s\n", "op", "libref", "scalar", "avx", "avx2",
"avx512", "x(ref)", "rate");
for (const Row& r : rows) {
char rate[64] = "";
const double best = r.t[AVX_N_LEVELS - 1] > 0 ? r.t[AVX_N_LEVELS - 1] : r.t[0];
if (best > 0 && r.flops > 0)
std::snprintf(rate, sizeof rate, "%.1f GFLOP/s", r.flops / best / 1e9);
else if (best > 0 && r.bytes > 0)
std::snprintf(rate, sizeof rate, "%.1f GB/s", r.bytes / best / 1e9);
std::printf("%-22s %9.2f", r.op.c_str(), r.t_ref * 1e6);
for (int lvl = 0; lvl < AVX_N_LEVELS; ++lvl) {
if (r.t[lvl] > 0) std::printf(" %9.2f", r.t[lvl] * 1e6);
else std::printf(" %9s", "n/a");
}
std::printf(" %8.1f %-14s %s\n", best > 0 ? r.t_ref / best : 0.0, rate, r.geom.c_str());
}
std::printf("\nThe x(ref) column is a statement about libref, which is a scalar loop with a\n"
"per-element dtype switch and says so. The rate column against the ceilings from\n"
"--peak is the statement about libavx.\n");
return 0;
}
+410
View File
@@ -0,0 +1,410 @@
/* avx_cases.cpp -- the geometry table both harnesses run.
*
* ONE TABLE, TWO BINARIES. A benchmark taken at a different extent from the correctness check is a
* measurement of something else, and the two tables would drift the first time one of them gained
* a case. tools/opshapes.h makes this argument for rad-kbench and rad-tune; it holds one level
* down too.
*
* WHAT THE VALUES ARE CHOSEN FOR. Not realism -- a real n_embd would make the checker take minutes
* and would not find anything a 640-wide row does not. They are chosen to break a hand-vectorised
* kernel:
*
* A ROW WIDER THAN ANY VECTOR, so the main body runs at every level (16 floats at AVX-512).
* A ROW THAT DOES NOT DIVIDE IT, because the tail loop is where a hand-vectorised kernel is
* wrong and where a level-3 masked store and a level-0 scalar loop can disagree. 645 and 259
* are chosen for exactly this: 645 % 16 == 5, % 8 == 5, and 259 % 16 == 3.
* MORE THAN ONE ROW, so a kernel that computed row 0 and broadcast it is caught.
* M = 1, 7 and 65 ON EVERY GEMM, which is decode, a speculative verify window, and one row past
* any register-block edge a microkernel can have.
* BOTH SIDES OF EVERY BANDED OPTION -- `causal` on and off, `window` bounded and unbounded,
* `norm` on and off, both `a_order` spellings, both rope `mode`s. A parameter exists because
* two implementations can disagree about it; a check that ran one value could never see that.
*
* Every op appears in f32, where the tolerance is tight enough that only the summation order may
* differ, and in bf16, where the narrowing is exercised.
*
* `bytes` and `flops` are for the bench's rate columns and are left 0 wherever the cost is not a
* simple function of the geometry -- a sampler that narrows a candidate set in place, a scatter
* whose work depends on the draw. An invented denominator is worse than no rate at all: it
* produces a number that looks comparable and is not.
*/
#include "avx_harness.h"
std::vector<Case> build_cases() {
std::vector<Case> c;
auto add = [&](const char* op, std::vector<P> p, double bytes = 0, double flops = 0) {
c.push_back(Case{ op, std::move(p), bytes, flops });
};
/* Bytes an elementwise op of `rows` x `n` moves at `w` bytes an element and `k` streams. */
auto EB = [](double rows, double n, double w, double k) { return rows * n * w * k; };
for (const char* dt : { "f32", "bf16", "f16" }) {
const double w = std::strcmp(dt, "f32") == 0 ? 4.0 : 2.0;
add("rmsnorm", { HI("M", 7), HI("n", 640), HF("eps", 1e-6), HS("dtype", dt),
HF("wadd", 0) }, EB(7, 640, w, 2));
add("rmsnorm", { HI("M", 3), HI("n", 645), HF("eps", 1e-5), HS("dtype", dt),
HF("wadd", 1) }, EB(3, 645, w, 2));
add("rmsnorm_add", { HI("M", 5), HI("n", 640), HF("eps", 1e-6), HS("dtype", dt),
HF("wadd", 0) }, EB(5, 640, w, 4));
add("layernorm", { HI("M", 5), HI("n", 645), HF("eps", 1e-5), HS("dtype", dt) },
EB(5, 645, w, 2));
add("add", { HI("M", 9), HI("n", 645), HS("dtype", dt) }, EB(9, 645, w, 3));
add("mul", { HI("M", 9), HI("n", 640), HS("dtype", dt) }, EB(9, 640, w, 3));
add("silu_mul", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 3));
add("gelu", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("silu", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2));
add("sigmoid", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("softmax", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("gather_rows", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2));
add("scatter_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("scale_rows", { HI("M", 6), HI("n", 645), HS("act", "sigmoid"), HS("dtype", dt) },
EB(6, 645, w, 2));
add("scale_rows", { HI("M", 6), HI("n", 640), HS("act", "none"), HS("dtype", dt) },
EB(6, 640, w, 2));
}
/* Every dtype pair, because `cast` is where the narrowing conventions live and the tolerance
* for it is 1e-6 -- which is to say exact. A cast that rounded differently from the ABI's RTNE
* would make every operand of every other op disagree by up to an ulp. */
for (const char* from : { "f32", "bf16", "f16", "fp8_e4m3", "fp8_e5m2", "i8" })
for (const char* to : { "f32", "bf16", "f16", "fp8_e4m3", "fp8_e5m2", "i8" })
add("cast", { HI("M", 5), HI("n", 259), HS("from", from), HS("to", to) });
/* The wide residual stream. hc = 4 and lowrank = 8 is Qwen4-Exp's gated residual, scaled down.
* `inject` on is the trunk case and off is the final mixer, and the two differ in the operand
* LIST -- which is what makes running both worth it rather than a duplicate. */
for (const char* dt : { "f32", "bf16" }) {
add("hc_enter", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) });
add("hc_write", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) });
add("hc_read", { HI("M", 5), HI("n", 128), HI("hc", 4), HI("lowrank", 8),
HF("eps", 1e-6), HS("dtype", dt), HF("wadd", 1), HI("inject", 1),
HI("group", 0) });
add("hc_read", { HI("M", 5), HI("n", 128), HI("hc", 4), HI("lowrank", 8),
HF("eps", 1e-6), HS("dtype", dt), HF("wadd", 0), HI("inject", 0),
HI("group", 0) });
/* The fp8 form and its Hadamard-rotated twin, 32-wide groups: four of them a stream. */
add("hc_read", { HI("M", 5), HI("n", 128), HI("hc", 4), HI("lowrank", 8),
HF("eps", 1e-6), HS("dtype", dt), HF("wadd", 1), HI("inject", 1),
HI("group", 32), HI("rotate", 1) });
add("mtp_enter", { HI("M", 5), HI("n", 128), HI("hc", 4), HF("eps", 1e-6), HS("dtype", dt),
HF("wadd", 1), HI("ngroup", 4) });
add("ple_gate", { HI("M", 5), HI("n", 128), HI("hc", 4), HF("eps", 1e-6), HS("dtype", dt),
HF("wadd", 1), HF("gate_eps", 1e-6) });
add("ple_conv", { HI("M", 9), HI("n", 128), HI("width", 4), HI("dilation", 2),
HS("dtype", dt) });
}
add("ngram_ids", { HI("M", 9), HI("heads", 3), HI("ngram", 4), HI("eos", 2) });
/* Quantisation. 128 is every real grid; 64 proves a second block edge works. n = 256 keeps
* both dividing, which the had_* forms require by contract (a rotation block may not straddle
* the end of a row). */
for (int group : { 64, 128 }) {
add("quant_act_i8", { HI("M", 5), HI("n", 256), HI("group", group),
HS("dtype", "bf16") }, EB(5, 256, 2, 1.5));
add("quant_act_i8", { HI("M", 5), HI("n", 256), HI("group", group),
HS("dtype", "f32") }, EB(5, 256, 4, 1.25));
add("quant_act_fp8", { HI("M", 5), HI("n", 256), HI("group", group),
HS("dtype", "bf16") }, EB(5, 256, 2, 1.5));
add("had_quant_act_fp8", { HI("M", 5), HI("n", 256), HI("group", group),
HS("dtype", "bf16") });
add("had_quant_act_i8", { HI("M", 5), HI("n", 256), HI("group", group),
HS("dtype", "bf16") });
add("dequant", { HI("M", 5), HI("n", 256), HI("group", group),
HS("dtype", "bf16") });
add("gated_had_quant_i8", { HI("M", 5), HI("n", 256), HI("group", group),
HS("dtype", "bf16"), HS("act", "silu"), HI("mode", 0) });
add("rmsnorm_had_quant_i8", { HI("M", 5), HI("n", 256), HF("eps", 1e-6),
HI("group", group), HS("dtype", "bf16"), HF("wadd", 0) });
add("rmsnorm_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-6),
HI("group", group), HS("dtype", "bf16"), HF("wadd", 0) });
add("gated_quant_fp8", { HI("M", 5), HI("n", 256), HI("group", group),
HS("dtype", "bf16"), HS("act", "silu") });
}
/* The fp8 fusions off the grid: a row the group does not divide (260 = 4 x 64 + 4, so the last
* scale covers four values), f32 activations -- which are narrowed to bf16 all the same -- and
* the other gate and gain. */
add("rmsnorm_quant_fp8", { HI("M", 5), HI("n", 260), HF("eps", 1e-6), HI("group", 64),
HS("dtype", "f32"), HF("wadd", 1) });
add("gated_quant_fp8", { HI("M", 5), HI("n", 260), HI("group", 64), HS("dtype", "f32"),
HS("act", "sigmoid") });
add("gram_accum", { HI("M", 5), HI("n", 128), HI("group", 128), HS("dtype", "fp8_e4m3") },
0, 2.0 * 5 * 128 * 128);
/* ...and the plain bf16 activation, which passes no scale. */
add("gram_accum", { HI("M", 5), HI("n", 260), HI("group", 128), HS("dtype", "bf16") },
0, 2.0 * 5 * 260 * 260);
/* GEMM. K = 259 is deliberately not a multiple of anything. */
for (const char* dt : { "f32", "bf16", "f16" })
for (int M : { 1, 7, 65 }) {
const double fl = 2.0 * M * 96 * 259;
add("gemm_nt", { HI("M", M), HI("N", 96), HI("K", 259), HS("dtype", dt) }, 0, fl);
add("gemm_nt_bias", { HI("M", M), HI("N", 96), HI("K", 259), HS("dtype", dt) }, 0, fl);
for (const char* act : { "none", "gelu", "gelu_tanh" })
add("gemm_nt_bias", { HI("M", M), HI("N", 96), HI("K", 259), HS("dtype", dt),
HS("act", act) }, 0, fl);
add("logits_gemm", { HI("M", M), HI("n_vocab", 96), HI("n_embd", 259),
HS("dtype", dt) }, 0, fl);
}
/* fp8a8 and fp8a16 ARE THE ONLY TWO libref CAN DESCRIBE, and that is a real limit rather than
* a gap in this table: `gemm_nt_q` is one op over six weight formats and the SCALE GRID is
* what differs between them -- per row, per row-group, per output-row-block, an e8m0 exponent
* byte, with or without a zero point. Every one of those is a property of the kernel that
* reads it, so libref declines to guess (ref_shapes.cpp says so at length) and a case at
* "w4a8" would be SKIPPED, not checked. The packed-nibble path is still exercised -- through
* `dequant`, whose grid the schema does state. */
for (const char* dt : { "fp8a8", "fp8a16" })
for (int M : { 1, 65 }) {
const double fl = 2.0 * M * 96 * 256;
add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128),
HS("dtype", dt) }, 0, fl);
add("gemm_nt_q_bias", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128),
HS("dtype", dt) }, 0, fl);
}
/* The gated form, which libref describes at fp8a8 only. N is the WEIGHT's rows, so the output
* is N/2 wide: 96 is one scale group a row at group 128 and 256 is two. */
for (int M : { 1, 65 })
for (const char* act : { "silu", "sigmoid" })
add("gemm_nt_q_gated", { HI("M", M), HI("N", 192), HI("K", 256), HI("group", 128),
HS("dtype", "fp8a8"), HS("act", act) }, 0,
2.0 * M * 192 * 256);
add("gemm_nt_q_gated", { HI("M", 7), HI("N", 512), HI("K", 256), HI("group", 128),
HS("dtype", "fp8a8"), HS("act", "silu") }, 0, 2.0 * 7 * 512 * 256);
for (const char* dt : { "f32", "bf16" }) {
add("embed_lookup", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt),
HI("vocab_offset", 0), HF("wscale", 0) });
add("embed_lookup_q", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt),
HI("vocab_offset", 0), HF("wscale", 0.01) });
}
/* Attention. q_len 1 is decode, 17 a ragged verify window. `window` 0 is unbounded and 8 the
* sliding form, which is a different loop bound and where an off-by-one lives. 64 takes
* the prefill panel form (q_len >= 32, uniform), so the second kernel has coverage too. */
for (const char* dt : { "f32", "bf16" })
for (int qlen : { 1, 17, 64 })
for (int window : { 0, 8 })
add("attn_paged", { HI("q_len", qlen), HI("head_dim", 64), HI("gqa", 4),
HI("block_size", 16), HI("causal", 1), HI("window", window),
HS("q_dtype", dt), HS("kv_dtype", dt), HF("scale", 0.125),
HI("max_ctx", 128), HI("n_head", 8), HI("max_seqs", 2) });
for (const char* dt : { "f32", "bf16" })
for (int causal : { 0, 1 })
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2),
HI("causal", causal), HS("dtype", dt), HF("scale", 0.125),
HI("max_seqlen", 24) });
for (const char* dt : { "f32", "bf16" })
add("kv_store", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2),
HI("block_size", 16), HS("kv_dtype", dt), HF("k_scale", 1.0),
HF("v_scale", 1.0) });
for (const char* mode : { "neox", "gptj" }) {
add("rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2),
HF("theta", 10000.0), HF("scale", 1.0), HS("mode", mode),
HI("rotary_dim", 64) });
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2),
HF("theta", 10000.0), HF("eps", 1e-6), HF("scale", 1.0),
HS("mode", mode), HI("rotary_dim", 64), HF("wadd", 0) });
}
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 10000.0), HF("scale", 1.0),
HS("dtype", "f32") });
/* The multi-component forms: Qwen3-VL's interleaved M-RoPE over a partial rotary, and a vision
* tower's 2-D axial rotary over a whole 72-wide head. */
for (const char* dt : { "f32", "bf16" }) {
add("rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 4), HI("n_head_kv", 2),
HF("theta", 1e7), HF("scale", 1.0), HS("mode", "imrope"),
HI("rotary_dim", 64), HS("sections", "11 11 10"), HS("dtype", dt) });
add("rope", { HI("M", 12), HI("head_dim", 72), HI("n_head", 4), HI("n_head_kv", 4),
HF("theta", 10000.0), HF("scale", 1.0), HS("mode", "axial"),
HI("rotary_dim", 72), HS("sections", "18 18"), HS("dtype", dt) });
add("grid_embed", { HI("M", 20), HI("n", 72), HI("side", 6), HS("dtype", dt) });
}
/* MoE. `a_order` exists because the two grouped GEMMs of one routed block disagree about it,
* and a check that ran one spelling could never have seen the defect it was added for. */
for (const char* dt : { "f32", "bf16" }) {
add("router_topk", { HI("M", 9), HI("n_expert", 8), HI("top_k", 2), HI("norm", 1),
HS("dtype", dt) });
add("router_topk", { HI("M", 9), HI("n_expert", 8), HI("top_k", 2), HI("norm", 0),
HS("dtype", dt) });
add("moe_gather", { HI("M", 9), HI("n", 128), HI("top_k", 2), HS("dtype", dt) });
/* The shared-expert fold: `shared`/`shared_gate` are always described, so the
* harness always presents them -- this case names the sigmoid spelling, the plain one
* above covers "none". */
add("moe_gather", { HI("M", 9), HI("n", 128), HI("top_k", 2), HS("dtype", dt),
HS("act", "sigmoid") });
add("row_topk", { HI("M", 5), HI("N", 97), HI("R", 4), HI("vocab_off", 0),
HS("dtype", dt) });
add("row_topk_merge", { HI("M", 5), HI("R", 4), HI("world_size", 2), HS("dtype", dt) });
/* "sorted" and not "slot": libref refuses any other spelling with RAD_E_UNSUPPORTED, and a
case at a spelling both plugins decline is a case that proves nothing. */
for (const char* order : { "token", "sorted" }) {
add("moe_gemm", { HI("M", 9), HI("N", 64), HI("K", 128), HI("n_expert", 8),
HI("top_k", 2), HS("a_order", order), HS("dtype", dt) });
add("moe_gemm_q", { HI("M", 9), HI("N", 64), HI("K", 128), HI("n_expert", 8),
HI("top_k", 2), HI("group", 128), HS("a_order", order),
HS("dtype", "w8a8") });
}
/* The two classes at different widths: a gate/up pair whose odd experts are half as wide
* (the output's second part begins past the odd class's zeros), and a down projection
* whose odd experts are half as long. */
add("moe_gemm_q", { HI("M", 9), HI("N", 256), HI("K", 128), HI("N_odd", 128),
HI("parts", 2), HI("n_expert", 8), HI("top_k", 2), HI("group", 128),
HS("a_order", "token"), HS("dtype", "w8a8") });
add("moe_gemm_q", { HI("M", 9), HI("N", 64), HI("K", 256), HI("K_odd", 128),
HI("n_expert", 8), HI("top_k", 2), HI("group", 128),
HS("a_order", "sorted"), HS("dtype", "w8a8") });
}
add("moe_scatter", { HI("M", 9), HI("n_expert", 8), HI("top_k", 2), HI("expert_base", 0) });
/* Gated delta net. head_k = head_v = 32 and chunk 8 keeps the state matrices small enough to
* read in a dump while still running every loop the full 128/128 shape does.
*
* `n_head_k`, `n_head_v` and `n_seq` ARE NOT PARAMETERS OF THESE OPS and are passed anyway.
* The gdn family reads its head counts off the OPERANDS, so no op names them and no geometry
* carries them -- which means a tool sizing the operands cold has nothing to size them FROM,
* and libref's shape hook declines (RAD_E_UNSUPPORTED) rather than inventing a head ratio and
* calling the result correctness. tools/opshapes.h calls the same three a `ShapeCtx` and takes
* them from the container's metadata. Here they are stated in the case, which is the same
* decision made by the same person for the same reason; without them every gdn case is SKIPPED
* AND COUNTED and the family is never checked at all.
*
* `n_seq` 2 rather than 1 deliberately: every gdn op opens by reading `cu`, and a single
* sequence makes a wrong `cu` walk indistinguishable from a right one. */
add("gdn_conv_prep", { HI("M", 16), HI("head_k", 32), HI("head_v", 32), HI("chunk", 8),
HI("conv_width", 4), HF("l2_eps", 1e-6), HF("softplus_thr", 20.0),
HI("n_head_k", 2), HI("n_head_v", 2), HI("n_seq", 2) });
add("gdn_conv_update", { HI("q_len", 2), HI("head_k", 32), HI("head_v", 32),
HI("conv_width", 4), HI("max_query_len", 2),
HI("n_head_k", 2), HI("n_head_v", 2), HI("n_seq", 2) });
add("gdn_kkt_solve", { HI("M", 16), HI("head_k", 32), HI("chunk", 8),
HI("n_head_k", 2), HI("n_head_v", 2), HI("n_seq", 2) });
add("gdn_chunk_scan", { HI("M", 16), HI("head_k", 32), HI("head_v", 32), HI("chunk", 8),
HF("scale", 0.176), HI("state_fp16", 0),
HI("n_head_k", 2), HI("n_head_v", 2), HI("n_seq", 2) });
add("gdn_recurrent_update", { HI("q_len", 2), HI("head_k", 32), HI("head_v", 32),
HI("n_head_v", 2), HF("scale", 0.176), HF("eps", 1e-6),
HF("l2_eps", 1e-6), HF("softplus_thr", 20.0), HS("act", "silu"),
HI("state_fp16", 0), HI("n_head_k", 2), HI("n_seq", 2) });
add("gdn_conv_recurrent_update", { HI("q_len", 2), HI("head_k", 32), HI("head_v", 32),
HI("conv_width", 4), HI("n_head_v", 2), HF("scale", 0.176),
HF("eps", 1e-6), HF("l2_eps", 1e-6),
HF("softplus_thr", 20.0), HS("act", "silu"),
HI("state_fp16", 0), HI("n_head_k", 2), HI("n_seq", 2) });
for (const char* act : { "silu", "sigmoid" })
add("gdn_gated_rmsnorm", { HI("M", 12), HI("channels", 128), HF("eps", 1e-6),
HS("act", act) });
/* Collectives at world_size 1, which is the only width libavx serves and says so in its row. */
add("all_reduce", { HI("world_size", 1), HI("numel", 645), HS("dtype", "f32"), HI("exact", 1),
HI("min_bytes", 0), HI("hops", 1) });
add("all_gather", { HI("world_size", 1), HI("numel", 645), HS("dtype", "f32"), HI("row", 0) });
/* Sampling. n_vocab 517 is above every vector width and divides nothing; n_cand 12 is a real
* candidate set after a top-k. */
for (const char* op : { "sample_penalties", "sample_dry", "sample_temp", "sample_mask",
"sample_argmax" })
add(op, { HI("M", 5), HI("n_vocab", 517) });
add("sample_topk", { HI("M", 5), HI("n_vocab", 517), HI("vocab_off", 0) });
for (const char* op : { "sample_topp", "sample_minp", "sample_typical", "sample_xtc",
"sample_pick", "sample_merge_topk" })
add(op, { HI("M", 5), HI("n_cand", 12) });
/* The drafter's walk: four steps over eight candidates, so every step after the first reads its
* predecessor off the walk. Rank 64 is whole vectors at every level and 37 is not; a stride of
* 2 reads every other anchor. */
add("dflash_select", { HI("M", 3), HI("steps", 4), HI("top_k", 8), HI("rank", 64),
HI("n_vocab", 300), HI("anchor_stride", 1), HS("dtype", "bf16") });
add("dflash_select", { HI("M", 5), HI("steps", 3), HI("top_k", 12), HI("rank", 37),
HI("n_vocab", 97), HI("anchor_stride", 2), HS("dtype", "bf16") });
/* ================================================================== speed-only, at model size
*
* WHY THESE EXIST SEPARATELY. Everything above is sized to break a kernel, not to represent
* one -- a 640-wide row exercises every code path a 2048-wide row does and the checker would
* spend minutes inside libref to learn nothing more. But SPEED is decided by the cache
* hierarchy, and a shape that fits in L1 answers a different question from the one a
* deployment asks. rad-avx-check skips every case below; rad-avx-bench runs them.
*
* The geometry is a ~1.5B dense model -- n_embd 2048, n_ff 5632, n_vocab 32000, 16 heads of
* 128 -- which is the size a CPU plugin plausibly serves. M = 1 is decode, 64 a speculative
* verify window, 512 a prefill chunk.
*
* `logits_gemm` AT 32000 x 2048 IS THE ONE THAT IS NOT A GEMM. Its weight is 128 MiB in bf16,
* which fits in no cache on any part this runs on, so whatever the flop count says it is a memory
* benchmark -- and reading it against the DRAM triad rather than the FMA ceiling is the only
* honest way to read it. It is in this list precisely because no other case can show that. */
auto speed = [&](const char* op, std::vector<P> p, double bytes, double flops) {
c.push_back(Case{ op, std::move(p), bytes, flops, true });
};
for (int M : { 1, 64, 512 }) {
speed("gemm_nt", { HI("M", M), HI("N", 2048), HI("K", 2048), HS("dtype", "bf16") },
0, 2.0 * M * 2048 * 2048);
speed("gemm_nt", { HI("M", M), HI("N", 5632), HI("K", 2048), HS("dtype", "bf16") },
0, 2.0 * M * 5632 * 2048);
speed("rmsnorm", { HI("M", M), HI("n", 2048), HF("eps", 1e-6), HS("dtype", "bf16"),
HF("wadd", 0) }, (double)M * 2048 * 2 * 2, 0);
speed("silu_mul", { HI("M", M), HI("n", 5632), HS("dtype", "bf16") },
(double)M * 5632 * 3 * 2, 0);
speed("softmax", { HI("M", M), HI("n", 2048), HS("dtype", "f32") },
(double)M * 2048 * 4 * 2, 0);
speed("quant_act_fp8", { HI("M", M), HI("n", 2048), HI("group", 128),
HS("dtype", "bf16") }, (double)M * 2048 * 3, 0);
speed("had_quant_act_fp8", { HI("M", M), HI("n", 2048), HI("group", 128),
HS("dtype", "bf16") }, (double)M * 2048 * 3, 0);
speed("quant_act_i8", { HI("M", M), HI("n", 2048), HI("group", 128),
HS("dtype", "bf16") }, (double)M * 2048 * 3, 0);
speed("had_quant_act_i8", { HI("M", M), HI("n", 2048), HI("group", 128),
HS("dtype", "bf16") }, (double)M * 2048 * 3, 0);
}
/* GDN at qwen35 model shape (k128/v128, chunk 64, 16 key heads, 48 value heads): the
* prefill heart (chunk_scan over a 512 chunk) and the decode heart (recurrent_update at
* q_len 1). NO RATE: the traffic denominator depends on the state layout, so a time and no
* rate is the honest column. libref runs these scalar -- keep --iters low. */
speed("gdn_chunk_scan", { HI("M", 512), HI("head_k", 128), HI("head_v", 128), HI("chunk", 64),
HF("scale", 0.176), HI("state_fp16", 0),
HI("n_head_k", 16), HI("n_head_v", 48), HI("n_seq", 2) }, 0, 0);
speed("gdn_chunk_scan", { HI("M", 128), HI("head_k", 128), HI("head_v", 128), HI("chunk", 64),
HF("scale", 0.176), HI("state_fp16", 0),
HI("n_head_k", 16), HI("n_head_v", 48), HI("n_seq", 2) }, 0, 0);
speed("gdn_recurrent_update", { HI("q_len", 1), HI("head_k", 128), HI("head_v", 128),
HI("n_head_v", 48), HF("scale", 0.176), HF("eps", 1e-6),
HF("l2_eps", 1e-6), HF("softplus_thr", 20.0), HS("act", "silu"),
HI("state_fp16", 0), HI("n_head_k", 16), HI("n_seq", 2) }, 0, 0);
speed("gdn_kkt_solve", { HI("M", 512), HI("head_k", 128), HI("chunk", 64),
HI("n_head_k", 16), HI("n_head_v", 48), HI("n_seq", 2) }, 0, 0);
/* Conv prep at model shape: conv_dim 10240 = 2*16*128 + 48*128, width 4, over a 512 chunk. */
speed("gdn_conv_prep", { HI("M", 512), HI("head_k", 128), HI("head_v", 128), HI("chunk", 64),
HI("conv_width", 4), HF("l2_eps", 1e-6), HF("softplus_thr", 20.0),
HI("n_head_k", 16), HI("n_head_v", 48), HI("n_seq", 2) }, 0, 0);
/* Conv update at decode shape: one new token a sequence, same widths. */
speed("gdn_conv_update", { HI("q_len", 1), HI("head_k", 128), HI("head_v", 128),
HI("conv_width", 4), HI("max_query_len", 1),
HI("n_head_k", 16), HI("n_head_v", 48), HI("n_seq", 2) }, 0, 0);
speed("logits_gemm", { HI("M", 1), HI("n_vocab", 32000), HI("n_embd", 2048),
HS("dtype", "bf16") }, (double)32000 * 2048 * 2, 2.0 * 32000 * 2048);
speed("sample_argmax", { HI("M", 1), HI("n_vocab", 32000) }, (double)32000 * 4, 0);
speed("sample_topk", { HI("M", 1), HI("n_vocab", 32000), HI("vocab_off", 0) }, 0, 0);
/* Decode attention over a real context: 16 query heads in groups of 4, 2048 keys already in
* the cache. This is the shape a decode step spends its time in. */
speed("attn_paged", { HI("q_len", 1), HI("head_dim", 128), HI("gqa", 4), HI("block_size", 16),
HI("causal", 1), HI("window", 0), HS("q_dtype", "bf16"),
HS("kv_dtype", "bf16"), HF("scale", 0.088), HI("max_ctx", 2048),
HI("n_head", 16), HI("max_seqs", 1) },
/* NO RATE. The KV bytes an attention row reads depend on the CONTEXT LENGTH the
draw put in `seqused`, which this table does not set and cannot see, so any
denominator here would be invented. A time and no rate is the honest column. */
0, 0);
/* Prefill attention: 512 queries over 512 cached keys, same heads. */
speed("attn_paged", { HI("q_len", 512), HI("head_dim", 128), HI("gqa", 4),
HI("block_size", 16), HI("causal", 1), HI("window", 0),
HS("q_dtype", "bf16"), HS("kv_dtype", "bf16"), HF("scale", 0.088),
HI("max_ctx", 512), HI("n_head", 16), HI("max_seqs", 1) },
0, 0);
/* Rope at model shape: 512 tokens, 16+4 heads of 128. Time-only (libref scalar). */
speed("rope", { HI("M", 512), HI("head_dim", 128), HI("n_head", 16), HI("n_head_kv", 4),
HF("theta", 10000.0), HF("scale", 1.0), HS("mode", "neox"),
HI("rotary_dim", 128) }, 0, 0);
speed("qk_norm_rope", { HI("M", 512), HI("head_dim", 128), HI("n_head", 16),
HI("n_head_kv", 4), HF("theta", 10000.0), HF("eps", 1e-6),
HF("scale", 1.0), HS("mode", "neox"), HI("rotary_dim", 128),
HF("wadd", 0) }, 0, 0);
return c;
}
+952
View File
@@ -0,0 +1,952 @@
/* avx_check.cpp -- rad-avx-check: libavx against libref, every op, every ISA level, no engine.
*
* ============================== WHAT THIS IS AND WHY IT IS NOT rad-kbench ==============================
*
* rad-kbench is the tree's kernel checker and it is the right tool for a DEVICE plugin: it needs
* rad_core, a Geometry, a plugin loader and (for the fixture path) a recorded artifact. Building
* it means building the engine, which on a machine with no device toolchain means building the
* engine's host half to test a host plugin. This is the same comparison with nothing under it: two dlopen calls, a
* table of geometries, and libref's own operand descriptions to size the buffers.
*
* It links NEITHER plugin. That is not laziness -- the claim being made is about the .so the
* engine would load, and a checker that statically linked the kernels would be exercising a
* different binary with different inlining and different flags.
*
* ============================== THE FOUR THINGS IT CHECKS, IN ORDER ==============================
*
* 1. SCHEMA AGREEMENT, before any arithmetic. The loader refuses two plugins whose schemas for
* one op disagree, and it refuses the WHOLE plugin -- so a single drifted parameter makes
* every row libavx carries unreachable, and the message an operator sees names one op and
* leaves them to find the rest. libavx's schema table is a hand-kept copy of libref's
* (avx_registry.cpp says so at length); this is what keeps the copy honest, running the
* loader's own rule: parameter key/type/requiredness positionally, operand role/optionality
* positionally, names deliberately NOT compared.
*
* 2. COVERAGE. Every op libref implements, libavx must implement. A row that is ABSENT and a row
* that RETURNS RAD_E_UNSUPPORTED are reported differently and neither is reported as a pass.
* This is the check that catches a kernel that was built and never wired, because a kernel
* that declines is indistinguishable from a kernel that works to anything that only looks for
* the return codes it expects.
*
* 3. THE NUMBERS. Both plugins are handed BYTE-IDENTICAL inputs and every OUT and INOUT operand
* is compared. The FINITENESS PATTERN is compared first and separately: a NaN on one side and
* a number on the other is a failure, not a tolerance question, and the obvious spelling
* (`rel > tol || rel < 0`) is FALSE for NaN -- which is how a NaN passes a comparison
* silently. After the geometry table, a set of HAND-BUILT cases covers the operand shapes a
* description cannot draw -- strided column slices, several sequences, rolling windows read
* past offset zero, a band above the operand's rows (see hand_cases below).
*
* 4. EVERY ISA LEVEL. The scalar, AVX, AVX2 and AVX-512 paths are four instruction streams
* compiled from one source, and only the level the machine under it happens to execute gets
* exercised by accident. Each is forced in turn through avx_isa_force -- an exported
* symbol rather than an environment variable, because an env switch that changes what a
* kernel computes is exactly what this project refuses to have. A level the CPU cannot
* execute is reported as NOT EXECUTABLE and counted nowhere: claiming a pass for a path that
* never ran is the one result worse than a failure.
*/
#include "avx_harness.h"
#include "avx_isa.h"
#include <deque>
#include <functional>
/* ================================================================== error metric
* rad-kbench's, including the thing its header says it got wrong once: the finiteness pattern is
* compared BEFORE any norm. */
struct Err {
double max_abs = 0, max_rel = 0, rel_l2 = 0;
int64_t nonfinite_gap = 0, n = 0;
};
static Err compare(const float* got, const float* ref, int64_t n) {
Err e;
e.n = n;
double num = 0, den = 0;
for (int64_t i = 0; i < n; ++i) {
const bool fg = std::isfinite(got[i]), fr = std::isfinite(ref[i]);
if (fg != fr) { ++e.nonfinite_gap; continue; }
if (!fg) continue;
const double d = (double)got[i] - (double)ref[i];
e.max_abs = std::max(e.max_abs, std::fabs(d));
const double sc = std::fabs((double)ref[i]);
if (sc > 1e-30) e.max_rel = std::max(e.max_rel, std::fabs(d) / sc);
num += d * d;
den += (double)ref[i] * (double)ref[i];
}
e.rel_l2 = den > 0 ? std::sqrt(num / den) : (num > 0 ? 1.0 : 0.0);
return e;
}
/* rad-kbench's tolerance table, and it means the same thing here: what a DIFFERENT SUMMATION ORDER
* of the same arithmetic costs, not what a wrong kernel costs. A vectorised reduction IS that
* different order, so these are the right numbers for this comparison rather than a loosened
* version of them. A kernel with a transposed operand lands nowhere near any of these. */
struct Tol { const char* op; const char* dtype; double rel_l2; };
static const Tol kTol[] = {
{ "gemm_nt", "bf16", 8e-3 },
{ "gemm_nt", "f16", 4e-3 },
{ "gemm_nt", "f32", 2e-5 },
{ "gemm_nt", "*", 3e-2 },
{ "logits_gemm", "bf16", 8e-3 },
{ "logits_gemm", "f32", 2e-5 },
{ "moe_gemm", "*", 3e-2 },
{ "attn_", "bf16", 2e-2 },
{ "attn_", "f32", 1e-4 },
{ "attn_", "*", 3e-2 },
{ "rmsnorm", "bf16", 4e-3 },
{ "rmsnorm", "f32", 1e-6 },
{ "layernorm", "f32", 1e-6 },
{ "softmax", "f32", 1e-6 },
{ "quant_act", "*", 1e-6 },
{ "dequant", "*", 1e-6 },
{ "cast", "*", 1e-6 },
{ "all_reduce", "f32", 1e-6 },
{ "all_reduce", "*", 4e-3 },
{ "all_gather", "*", 0.0 },
{ "*", "f32", 1e-5 },
{ "*", "bf16", 6e-3 },
{ "*", "f16", 3e-3 },
{ "*", "*", 2e-2 },
};
static double tolerance_for(const std::string& op, const char* dtype) {
const char* dt = dtype ? dtype : "*";
for (const Tol& t : kTol) {
const bool om = std::strcmp(t.op, "*") == 0 || op.rfind(t.op, 0) == 0;
const bool dm = std::strcmp(t.dtype, "*") == 0 || std::strcmp(t.dtype, dt) == 0;
if (om && dm) return t.rel_l2;
}
return 2e-2;
}
struct Stats {
int checked = 0, passed = 0, failed = 0, skipped = 0, declined = 0, missing = 0;
double worst = 0;
std::string worst_where;
};
static void run_case(const Lib& ref, const Lib& avx, const Case& c, bool verbose,
double tol_override, Stats* st) {
const RadKernelInfo* kr = ref.row(c.op);
const RadKernelInfo* ka = avx.row(c.op);
if (!kr) { ++st->skipped; return; }
if (!ka) { ++st->missing; return; }
/* Side A is libref, side B is libavx. The description comes from the ORACLE: the two have to
* be handed the same bytes for the comparison to mean anything, and where they could disagree
* about an extent the reference semantics are the ones that define the op. */
/* A SKIP IS REPORTED WITH ITS REASON, and that is not a nicety. A silent skip is how a checker
* reports coverage it does not have, and the two reasons here mean completely
* different things. "the oracle cannot describe this geometry" is a limit of libref's shape
* hook and the case should be rewritten or dropped; "the oracle declined the launch" means the
* case is asking for something the op does not define. Either way it is the CASE TABLE that is
* wrong, and a count with no name does not say which line. */
Prepared pr = h_prepare(ref, kr, c, kr, ka);
if (pr.skipped || !pr.ok) {
++st->skipped;
if (verbose)
std::printf(" %-22s %-46s SKIP: libref's opd_shape declines this geometry\n",
c.op, case_str(c).c_str());
return;
}
const int rr = kr->launch(&pr.aa, nullptr);
const int ra = ka->launch(&pr.ab, nullptr);
/* THE ORACLE IS ASKED FIRST, and getting this order wrong cost a false report. If libref
* declines the geometry there is nothing to compare against, so the case is SKIPPED -- even
* when libavx declined it too, which is the correct and identical behaviour rather than a gap.
* Reporting libavx's decline before looking at the oracle's blamed the plugin for a case the
* op does not define (it was a case table asking for an `a_order` spelling neither
* implementation accepts). A DECLINE only means something when the oracle produced an answer. */
if (rr < 0) {
++st->skipped;
if (verbose)
std::printf(" %-22s %-46s SKIP: libref's launch returned %d\n", c.op,
case_str(c).c_str(), rr);
return;
}
if (ra == RAD_E_UNSUPPORTED) {
++st->declined;
if (verbose) std::printf(" %-22s %-46s DECLINED\n", c.op, case_str(c).c_str());
return;
}
if (ra < 0) {
std::printf(" FAIL %-20s %s\n libavx returned %d where libref returned %d\n",
c.op, case_str(c).c_str(), ra, rr);
++st->failed;
++st->checked;
return;
}
bool ok = true;
double worst = 0;
const double tol = tol_override >= 0 ? tol_override : tolerance_for(c.op, case_dtype(c));
for (size_t i = 0; i < pr.opd.size(); ++i) {
const Opd& o = pr.opd[i];
if (o.absent || o.n <= 0) continue;
if (o.role != RAD_OPD_OUT && o.role != RAD_OPD_INOUT) continue;
std::vector<float> fr((size_t)o.n), fa((size_t)o.n);
h_widen(o.a.data(), o.d.dtype, o.n, fr.data());
h_widen(o.b.data(), o.d.dtype, o.n, fa.data());
const Err e = compare(fa.data(), fr.data(), o.n);
worst = std::max(worst, e.rel_l2);
if (e.nonfinite_gap != 0 || !(e.rel_l2 <= tol)) {
ok = false;
std::printf(" FAIL %-20s %s\n operand %d (%s) rel_l2=%.3e max_abs=%.3e "
"nonfinite_gap=%lld tol=%.1e\n",
c.op, case_str(c).c_str(), (int)i,
pr.schema->operands[i].name ? pr.schema->operands[i].name : "?",
e.rel_l2, e.max_abs, (long long)e.nonfinite_gap, tol);
}
}
++st->checked;
if (ok) ++st->passed; else ++st->failed;
if (worst > st->worst) {
st->worst = worst;
st->worst_where = std::string(c.op) + " " + case_str(c);
}
if (verbose)
std::printf(" %-22s %-46s rel_l2=%.3e tol=%.1e %s\n", c.op, case_str(c).c_str(), worst,
tol, ok ? "ok" : "FAIL");
}
/* ================================================================== exhaustive conversion
*
* THE ONE CHECK A DRAW CANNOT MAKE. Every geometry in the case table fills its operands with
* standard normals, which is the right domain for an activation and reaches almost none of the
* interesting bit patterns of a narrow float: no NaN, no infinity, no subnormal, no negative zero.
* A conversion is exactly where those live -- `cvt_fp8e4m3_to_f32` has a separate branch for the
* subnormal range and another for the format's single NaN encoding, and a draw of normals exercises
* neither.
*
* So the 8-bit and 16-bit formats are checked EXHAUSTIVELY: every one of the 256 or 65536 bit
* patterns, through the plugin's own `cast`, against libref's. For an 8-bit source that is the
* complete input space and the result is a proof rather than evidence; for a 16-bit one it is the
* complete space too. The narrowing direction (f32 -> narrow) cannot be exhaustive over 2^32, so it
* is fed the widened patterns back plus the boundary values of each format -- which is where a
* narrowing rounds differently if it is going to.
*
* It is worth the forty lines because this is the class of bug that survives everything else: the
* fp8 encode's lower bound was wrong by seven octaves and every geometry in the table still passed
* until `cast` was run at a tolerance of 1e-6. */
static bool exhaustive_cast(const Lib& ref, const Lib& avx, bool verbose) {
const RadKernelInfo* kr = ref.row("cast");
const RadKernelInfo* ka = avx.row("cast");
if (!kr || !ka) return true;
struct Fmt { const char* name; uint32_t dt; int bits; };
static const Fmt kFmt[] = {
{ "fp8_e4m3", RAD_F8E4M3, 8 }, { "fp8_e5m2", RAD_F8E5M2, 8 },
{ "bf16", RAD_BF16, 16 }, { "f16", RAD_F16, 16 },
{ "i8", RAD_I8, 8 },
};
bool ok = true;
for (const Fmt& f : kFmt) {
const int64_t n = (int64_t)1 << f.bits;
std::vector<uint8_t> src((size_t)((n * f.bits) / 8));
if (f.bits == 8) for (int64_t i = 0; i < n; ++i) src[(size_t)i] = (uint8_t)i;
else for (int64_t i = 0; i < n; ++i) ((uint16_t*)src.data())[i] = (uint16_t)i;
/* ---- widening: every pattern of the narrow format into f32. */
std::vector<float> ya((size_t)n, 0), yb((size_t)n, 0);
for (int pass = 0; pass < 2; ++pass) {
const bool narrowing = pass == 1;
/* ---- narrowing: the widened values back down, which covers every value the format can
* represent plus, through the round trip, the ties at each of its steps. */
std::vector<uint8_t> na((size_t)((n * f.bits) / 8), 0);
std::vector<uint8_t> nb((size_t)((n * f.bits) / 8), 0);
RadParam p[4];
p[0] = RadParam{ "M", RAD_P_INT, 1, 0, nullptr, 0 };
p[1] = RadParam{ "n", RAD_P_INT, (long long)n, 0, nullptr, 0 };
p[2] = RadParam{ "from", RAD_P_STR, 0, 0, narrowing ? "f32" : f.name, 0 };
p[3] = RadParam{ "to", RAD_P_STR, 0, 0, narrowing ? f.name : "f32", 0 };
auto mk_t = [&](void* data, uint32_t dt) {
RadTensor t{};
t.data = data; t.dtype = dt; t.rank = 2;
t.shape[0] = 1; t.shape[1] = n;
t.stride[0] = n; t.stride[1] = 1;
return t;
};
RadTensor ta[2], tb[2];
if (!narrowing) {
ta[0] = mk_t(src.data(), f.dt); ta[1] = mk_t(ya.data(), RAD_F32);
tb[0] = mk_t(src.data(), f.dt); tb[1] = mk_t(yb.data(), RAD_F32);
} else {
ta[0] = mk_t(ya.data(), RAD_F32); ta[1] = mk_t(na.data(), f.dt);
tb[0] = mk_t(ya.data(), RAD_F32); tb[1] = mk_t(nb.data(), f.dt);
}
RadArgs aa{}, ab{};
aa.t = ta; aa.n_t = 2; aa.p = p; aa.n_p = 4; aa.world_size = 1;
ab = aa; ab.t = tb;
if (kr->launch(&aa, nullptr) < 0 || ka->launch(&ab, nullptr) < 0) continue;
int64_t bad = 0;
int64_t first = -1;
if (!narrowing) {
for (int64_t i = 0; i < n; ++i) {
const bool na_ = std::isnan(ya[(size_t)i]), nb_ = std::isnan(yb[(size_t)i]);
if (na_ != nb_ || (!na_ && ya[(size_t)i] != yb[(size_t)i])) {
if (first < 0) first = i;
++bad;
}
}
} else {
for (size_t i = 0; i < na.size(); ++i)
if (na[i] != nb[i]) { if (first < 0) first = (int64_t)i; ++bad; }
}
if (bad) {
ok = false;
std::printf("EXACT cast %-10s %-10s %lld of %lld patterns differ, first at %lld\n",
narrowing ? "f32 ->" : "-> f32", f.name, (long long)bad,
(long long)n, (long long)first);
} else if (verbose) {
std::printf(" cast %-6s %-9s all %lld bit patterns identical\n",
narrowing ? "f32 ->" : "-> f32", f.name, (long long)n);
}
}
}
return ok;
}
/* ================================================================== operands no description draws
*
* libref's opd_shape describes every op the one way a cold harness can use it: one sequence where
* the op allows it, every operand dense at its declared rank, integer operands at their plainest
* value. The engine hands kernels more than that, and each case below is one of those shapes, with
* its operands built by hand:
*
* several sequences through a path chosen for uniform queries;
* a rank-2 COLUMN SLICE of a fused projection, whose row stride is the projection's width;
* a speculative step whose `num_accepted` reads a rolling window past offset zero;
* a ranged parameter at its band's upper bound over an operand of fewer rows;
* head widths that do not divide a kernel's channel panel;
* packed weight codes at odd element offsets, which fall off the row converter;
* integer stores of values past the target's range, and exponents of -inf and NaN.
*
* Both plugins get byte-identical copies, and every OUT or INOUT buffer is compared WHOLE -- not
* just the view the op was handed -- so a write outside the view is a difference too. */
struct Hand {
struct Buf {
uint32_t dt = RAD_F32;
int64_t elems = 0;
std::vector<uint8_t> a, b;
bool out = false;
};
std::string name, op;
std::deque<Buf> bufs;
std::vector<int> buf_of; /* per operand, the backing buffer or -1 */
std::vector<RadTensor> ta, tb;
std::vector<RadParam> p;
std::deque<std::string> strs;
double tol = 1e-5;
Hand(const char* n, const char* o, double t) : name(n), op(o), tol(t) {}
/* An operand over a fresh buffer of `span` elements, viewed with `shape` and `stride`. The
* whole buffer is filled -- the bytes outside the view are another projection's columns, and
* a kernel that reads them must read the same thing on both sides. */
Hand& view(uint32_t dt, std::vector<int64_t> shape, std::vector<int64_t> stride, int64_t span,
const std::function<float(int64_t)>& fill, bool out = false) {
Buf bf;
bf.dt = dt; bf.elems = span; bf.out = out;
std::vector<float> v((size_t)span);
for (int64_t i = 0; i < span; ++i) v[(size_t)i] = fill(i);
bf.a.assign(dt_bytes(dt, span) + 8, 0);
h_narrow(v.data(), dt, span, bf.a.data());
bf.b = bf.a;
bufs.push_back(std::move(bf));
RadTensor t{};
t.dtype = dt;
t.rank = (uint32_t)shape.size();
for (size_t i = 0; i < shape.size(); ++i) {
t.shape[i] = shape[i];
t.stride[i] = stride[i];
}
ta.push_back(t); tb.push_back(t);
buf_of.push_back((int)bufs.size() - 1);
return *this;
}
/* A dense operand of `shape`. */
Hand& dense(uint32_t dt, std::vector<int64_t> shape, const std::function<float(int64_t)>& fill,
bool out = false) {
std::vector<int64_t> st(shape.size());
int64_t acc = 1;
for (int i = (int)shape.size() - 1; i >= 0; --i) {
st[(size_t)i] = acc;
acc *= shape[(size_t)i];
}
return view(dt, shape, st, acc, fill, out);
}
Hand& idx(std::vector<int64_t> v, bool out = false) {
return dense(RAD_I32, { (int64_t)v.size() }, [v](int64_t i) { return (float)v[(size_t)i]; },
out);
}
Hand& none() {
ta.push_back(RadTensor{});
tb.push_back(RadTensor{});
buf_of.push_back(-1);
return *this;
}
Hand& pi(const char* k, long long v) {
p.push_back(RadParam{ k, RAD_P_INT, v, 0, nullptr, 0 });
return *this;
}
Hand& pf(const char* k, double v) {
p.push_back(RadParam{ k, RAD_P_F64, 0, 0, nullptr, v });
return *this;
}
Hand& ps(const char* k, const char* v) {
strs.emplace_back(v);
p.push_back(RadParam{ k, RAD_P_STR, 0, 0, strs.back().c_str(), 0 });
return *this;
}
/* Returns false on a failure, having printed it. */
bool run(const Lib& ref, const Lib& avx, bool verbose) {
const RadKernelInfo* kr = ref.row(op.c_str());
const RadKernelInfo* ka = avx.row(op.c_str());
if (!kr || !ka) {
std::printf(" FAIL %-20s %s\n no row for the op in %s\n", op.c_str(),
name.c_str(), kr ? "libavx" : "libref");
return false;
}
for (size_t i = 0; i < ta.size(); ++i) {
if (buf_of[i] < 0) continue;
ta[i].data = bufs[(size_t)buf_of[i]].a.data();
tb[i].data = bufs[(size_t)buf_of[i]].b.data();
}
RadArgs aa{}, ab{};
aa.t = ta.data(); aa.n_t = (int)ta.size();
aa.p = p.data(); aa.n_p = (int)p.size();
aa.world_size = 1;
ab = aa; ab.t = tb.data();
const int rr = kr->launch(&aa, nullptr);
const int ra = ka->launch(&ab, nullptr);
if (rr < 0) {
std::printf(" FAIL %-20s %s\n libref refused the case (%d); the case is wrong\n",
op.c_str(), name.c_str(), rr);
return false;
}
if (ra < 0) {
std::printf(" FAIL %-20s %s\n libavx returned %d where libref returned %d\n",
op.c_str(), name.c_str(), ra, rr);
return false;
}
bool ok = true;
double worst = 0;
for (const Buf& bf : bufs) {
if (!bf.out) continue;
std::vector<float> fr((size_t)bf.elems), fa((size_t)bf.elems);
h_widen(bf.a.data(), bf.dt, bf.elems, fr.data());
h_widen(bf.b.data(), bf.dt, bf.elems, fa.data());
const Err e = compare(fa.data(), fr.data(), bf.elems);
worst = std::max(worst, e.rel_l2);
if (e.nonfinite_gap != 0 || !(e.rel_l2 <= tol)) {
ok = false;
std::printf(" FAIL %-20s %s\n rel_l2=%.3e max_abs=%.3e nonfinite_gap=%lld "
"tol=%.1e\n", op.c_str(), name.c_str(), e.rel_l2, e.max_abs,
(long long)e.nonfinite_gap, tol);
}
}
if (verbose)
std::printf(" %-22s %-46s rel_l2=%.3e tol=%.1e %s\n", op.c_str(), name.c_str(), worst,
tol, ok ? "ok" : "FAIL");
return ok;
}
};
/* A deterministic fill that is not a constant: the value of element i under seed s. */
static std::function<float(int64_t)> hfill(uint64_t s, float sigma = 1.0f) {
return [s, sigma](int64_t i) {
uint64_t x = s * 0x9E3779B97F4A7C15ull + (uint64_t)i;
x ^= x >> 31; x *= 0xBF58476D1CE4E5B9ull; x ^= x >> 29;
return ((float)(x % 2001) / 1000.0f - 1.0f) * sigma;
};
}
static bool hand_cases(const Lib& ref, const Lib& avx, bool verbose, int* n_checked) {
std::vector<Hand> hs;
/* ---- attention: two sequences through the uniform long-query form, no cu_seqlens ------- */
{
const int64_t S = 2, QL = 32, KVH = 1, G = 2, HD = 16, BS = 16, NB = 6;
Hand h("n_seq=2 q_len=32 no cu_seqlens", "attn_paged", 1e-4);
h.dense(RAD_F32, { S * QL, KVH * G, HD }, hfill(1))
.dense(RAD_F32, { NB, KVH, BS, 2 * HD }, hfill(2))
.dense(RAD_I32, { S, 3 }, [](int64_t i) { return (float)((i * 5) % 6); })
.idx({ 40, 36 })
.none().none().none()
.dense(RAD_F32, { S * QL, KVH * G, HD }, hfill(3), true)
.pi("q_len", QL).pi("head_dim", HD).pi("gqa", G).pi("block_size", BS).pi("causal", 1)
.pi("window", 0).ps("q_dtype", "f32").ps("kv_dtype", "f32");
hs.push_back(std::move(h));
}
/* ---- attention and the KV write over column slices of a fused [q|k|v] projection ------- */
{
const int64_t T = 5, NH = 2, KVH = 1, HD = 16, W = (NH + 2 * KVH) * HD, BS = 4, NB = 4;
Hand h("k, v are rank-2 column slices, row stride 64", "kv_store", 1e-6);
h.view(RAD_F32, { T, KVH * HD }, { W, 1 }, T * W, hfill(4)) /* k at column 0 */
.view(RAD_F32, { T, KVH * HD }, { W, 1 }, T * W, hfill(5))
.idx({ 3, 0, 9, 14, 6 })
.dense(RAD_F32, { NB, KVH, BS, 2 * HD }, hfill(6), true)
.pi("M", T).pi("head_dim", HD).pi("n_head_kv", KVH).pi("block_size", BS)
.ps("kv_dtype", "f32");
hs.push_back(std::move(h));
Hand g("q and out are rank-2 column slices", "attn_paged", 1e-4);
g.view(RAD_F32, { T, NH * HD }, { W, 1 }, T * W, hfill(7))
.dense(RAD_F32, { NB, KVH, BS, 2 * HD }, hfill(8))
.dense(RAD_I32, { T, 2 }, [](int64_t i) { return (float)(i % NB); })
.idx({ 3, 5, 7, 2, 8 })
.none().none().none()
.view(RAD_F32, { T, NH * HD }, { W, 1 }, T * W, hfill(9), true)
.pi("q_len", 1).pi("head_dim", HD).pi("gqa", NH / KVH).pi("block_size", BS)
.pi("causal", 1).pi("window", 0).ps("q_dtype", "f32").ps("kv_dtype", "f32");
hs.push_back(std::move(g));
Hand d("q, k, v, out are rank-2 column slices", "attn_dense", 1e-4);
d.view(RAD_F32, { T, HD }, { W, 1 }, T * W, hfill(10))
.view(RAD_F32, { T, HD }, { W, 1 }, T * W, hfill(11))
.view(RAD_F32, { T, HD }, { W, 1 }, T * W, hfill(12))
.idx({ 0, 2, 5 })
.view(RAD_F32, { T, HD }, { W, 1 }, T * W, hfill(13), true)
.pi("M", T).pi("head_dim", HD).pi("gqa", 1).pi("causal", 1).ps("dtype", "f32");
hs.push_back(std::move(d));
}
/* ---- the GDN decode convolution read past offset zero ---------------------------------- */
{
const int64_t S = 2, QL = 3, HG = 2, H = 2, K = 16, V = 16, WID = 4;
const int64_t CD = 2 * HG * K + H * V, SL = WID - 2 + QL;
Hand h("num_accepted 2 and 3", "gdn_conv_update", 2e-5);
h.dense(RAD_F32, { S * QL, CD }, hfill(14))
.dense(RAD_F32, { CD, WID }, hfill(15, 0.5f))
.none()
.dense(RAD_F32, { 3, CD, SL }, hfill(16), true)
.idx({ 2, 0 })
.idx({ 2, 3 })
.idx({ 0, QL, 2 * QL })
.dense(RAD_F32, { S * QL, HG, K }, hfill(17), true)
.dense(RAD_F32, { S * QL, HG, K }, hfill(18), true)
.dense(RAD_F32, { S * QL, H, V }, hfill(19), true)
.pi("q_len", QL).pi("head_k", K).pi("head_v", V).pi("conv_width", WID)
.pi("max_query_len", QL);
hs.push_back(std::move(h));
/* The same step over a CHANNEL-CONTIGUOUS state, [slot][t][c] viewed as [slot][c][t]:
* the layout that takes libavx's row-move path rather than its element loop. */
Hand m("num_accepted 2 and 3, channel-contiguous state", "gdn_conv_update", 2e-5);
m.dense(RAD_F32, { S * QL, CD }, hfill(14))
.dense(RAD_F32, { CD, WID }, hfill(15, 0.5f))
.none()
.view(RAD_F32, { 3, CD, SL }, { SL * CD, 1, CD }, 3 * SL * CD, hfill(16), true)
.idx({ 2, 0 })
.idx({ 2, 3 })
.idx({ 0, QL, 2 * QL })
.dense(RAD_F32, { S * QL, HG, K }, hfill(17), true)
.dense(RAD_F32, { S * QL, HG, K }, hfill(18), true)
.dense(RAD_F32, { S * QL, H, V }, hfill(19), true)
.pi("q_len", QL).pi("head_k", K).pi("head_v", V).pi("conv_width", WID)
.pi("max_query_len", QL);
hs.push_back(std::move(m));
}
/* ---- head widths that do not divide the 1024-channel panel ------------------------------- */
{
const int64_t S = 2, QL = 2, HG = 4, H = 8, K = 96, V = 96, WID = 4;
const int64_t CD = 2 * HG * K + H * V, SL = WID - 2 + QL;
Hand h("head_k = head_v = 96, conv_dim 1536", "gdn_conv_update", 2e-5);
h.dense(RAD_F32, { S * QL, CD }, hfill(20))
.dense(RAD_F32, { CD, WID }, hfill(21, 0.5f))
.none()
.dense(RAD_F32, { 2, CD, SL }, hfill(22), true)
.idx({ 1, 0 })
.idx({ 1, 2 })
.idx({ 0, QL, 2 * QL })
.dense(RAD_F32, { S * QL, HG, K }, hfill(23), true)
.dense(RAD_F32, { S * QL, HG, K }, hfill(24), true)
.dense(RAD_F32, { S * QL, H, V }, hfill(25), true)
.pi("q_len", QL).pi("head_k", K).pi("head_v", V).pi("conv_width", WID)
.pi("max_query_len", QL);
hs.push_back(std::move(h));
const int64_t M = 6;
Hand p("head_k = head_v = 96, conv_dim 1536", "gdn_conv_prep", 2e-5);
p.dense(RAD_F32, { M, CD + 2 * H }, hfill(26))
.dense(RAD_F32, { CD, WID }, hfill(27, 0.5f))
.none()
.dense(RAD_F32, { H }, hfill(28, 0.5f))
.dense(RAD_F32, { H }, hfill(29, 0.5f))
.dense(RAD_F32, { 2, CD, WID - 1 }, hfill(30), true)
.idx({ 0, 4, M })
.none().none()
.idx({ 1, 0 })
.idx({ 1, 0 })
.dense(RAD_F32, { M, HG, K }, hfill(31), true)
.dense(RAD_F32, { M, HG, K }, hfill(32), true)
.dense(RAD_F32, { M, H, V }, hfill(33), true)
.dense(RAD_F32, { M, H }, hfill(34), true)
.dense(RAD_F32, { M, H }, hfill(35), true)
.pi("M", M).pi("head_k", K).pi("head_v", V).pi("chunk", 4).pi("conv_width", WID)
.pf("l2_eps", 1e-6).pf("softplus_thr", 20.0);
hs.push_back(std::move(p));
}
/* ---- the PLE ops at their band's upper bound, and a verify over two sequences ------------ */
{
const int64_t T = 5, N = 32, HC = 2, BAND = 64;
Hand g("M = 64 over 5 rows", "ple_gate", 1e-5);
g.dense(RAD_F32, { T, HC * N }, hfill(36))
.dense(RAD_F32, { T, HC * N }, hfill(37))
.dense(RAD_F32, { T, N }, hfill(38))
.dense(RAD_F32, { HC * N }, hfill(39, 0.2f))
.dense(RAD_F32, { HC * N }, hfill(40, 0.2f))
.dense(RAD_F32, { HC * N }, hfill(41, 0.2f))
.dense(RAD_F32, { T, HC * N }, hfill(42), true)
.dense(RAD_F32, { T, HC * N }, hfill(43), true)
.pi("M", BAND).pi("n", N).pi("hc", HC).pf("eps", 1e-6).ps("dtype", "f32")
.pf("wadd", 1.0);
hs.push_back(std::move(g));
/* Two sequences, a verify of 3 and one of 2, reading at offsets 1 and 2 of a window deep
* enough for both: hist 6 at width 4 and dilation 2, plus a verify's n - 1. */
const int64_t WIDTH = 4, DIL = 2, HIST = (WIDTH - 1) * DIL, SL = HIST + 2;
Hand c("M = 64 over 5 rows, verifies of 3 and 2", "ple_conv", 1e-5);
c.dense(RAD_F32, { T, N }, hfill(44))
.dense(RAD_F32, { N, WIDTH }, hfill(45, 0.5f))
.dense(RAD_F32, { 2, N, SL }, hfill(46), true)
.idx({ 0, 3, 5 })
.dense(RAD_F32, { T, N }, hfill(47))
.idx({ 1, 0 })
.idx({ 7, 9 })
.idx({ 2, 3 })
.dense(RAD_F32, { T, N }, hfill(48), true)
.pi("M", BAND).pi("n", N).pi("width", WIDTH).pi("dilation", DIL).ps("dtype", "f32");
hs.push_back(std::move(c));
Hand n("M = 64 over 5 rows, verifies of 3 and 2", "ngram_ids", 0.0);
n.idx({ 11, 12, 13, 21, 22 })
.dense(RAD_I32, { 2, 2 + 2 }, [](int64_t i) { return (float)(100 + i); }, true)
.idx({ 0, 3, 5 })
.dense(RAD_I64, { 3 }, [](int64_t i) { return (float)(1000003 + 7919 * i); })
.dense(RAD_I64, { 4 }, [](int64_t i) { return (float)(97 + 2 * i); })
.dense(RAD_I64, { 4 }, [](int64_t i) { return (float)(1000 * i); })
.idx({ 1, 0 })
.idx({ 7, 9 })
.idx({ 2, 3 })
.dense(RAD_I32, { T, 4 }, [](int64_t) { return -1.0f; }, true)
.pi("M", BAND).pi("heads", 4).pi("ngram", 3).pi("eos", 5);
hs.push_back(std::move(n));
}
/* ---- packed weight codes at odd element offsets ------------------------------------------ */
{
const int64_t M = 2, N = 4, K = 33;
Hand h("W4 weight, K = 33: odd rows start mid-byte", "gemm_nt_q", 1e-5);
h.dense(RAD_F32, { M, K }, hfill(49))
.none()
.dense(RAD_I4, { N, K }, hfill(50, 2.0f))
.dense(RAD_F32, { N, 1 }, [](int64_t i) { return 0.5f + 0.25f * (float)i; })
.dense(RAD_F32, { M, N }, hfill(51), true)
.pi("M", M).pi("N", N).pi("K", K).ps("dtype", "w4a16");
hs.push_back(std::move(h));
Hand w("W2 weight, K = 33", "gemm_nt_q", 1e-5);
w.dense(RAD_F32, { M, K }, hfill(52))
.none()
.dense(RAD_I2, { N, K }, hfill(53, 2.0f))
.dense(RAD_F32, { N, 1 }, [](int64_t i) { return 1.0f + (float)i; })
.dense(RAD_F32, { M, N }, hfill(54), true)
.pi("M", M).pi("N", N).pi("K", K).ps("dtype", "w2a16");
hs.push_back(std::move(w));
}
/* ---- integer stores past the range, and exponents of -inf and NaN ------------------------ */
{
const float big[] = { 1e10f, -1e10f, INFINITY, -INFINITY, 2.5f, -2.5f, 3.5f, 127.5f,
-128.5f, 300.0f, -300.0f, 0.49f };
const int64_t n = (int64_t)(sizeof big / sizeof big[0]);
for (const char* to : { "i8", "u8", "i16" }) {
/* 51 elements: the vector body runs at every level and so does the scalar tail. */
const int64_t len = 4 * n + 3;
Hand h((std::string("f32 -> ") + to + " past the range").c_str(), "cast", 0.0);
const uint32_t dt = rad_dtype_parse(to);
h.dense(RAD_F32, { 1, len }, [&big, n](int64_t i) { return big[i % n]; })
.dense(dt, { 1, len }, [](int64_t) { return 0.0f; }, true)
.pi("M", 1).pi("n", len).ps("from", "f32").ps("to", to);
hs.push_back(std::move(h));
}
/* 48 wide, a whole number of vectors at every level: a scalar tail's own exp would turn
* the row's sum into a NaN by itself and hide what the vector exp did with one. */
Hand s("rows of -inf: one fully masked, one partly", "softmax", 1e-6);
const int64_t w = 48;
s.dense(RAD_F32, { 3, w }, [w](int64_t i) {
const int64_t r = i / w, c = i % w;
if (r == 0) return -INFINITY;
if (r == 1 && c % 3 == 0) return -INFINITY;
return (float)(c % 7) * 0.5f - 1.0f;
})
.dense(RAD_F32, { 3, w }, [](int64_t) { return 0.0f; }, true)
.pi("M", 3).pi("n", w).ps("dtype", "f32");
hs.push_back(std::move(s));
}
/* ---- the drafter's walk with the pairwise term in charge -------------------------------- *
* A cold description draws `pred` and `succ` as weights, at 0.02, where the pairwise term is a
* thousandth of `unary` and never moves a pick: the walk is checked and the form is not. Here
* the codebooks are unit-scale and `unary` half that, so every pick is the form's. Some
* candidates are outside the vocabulary (-1 and past it) and so is the second sequence's
* anchor, which is the "contributes nothing" branch. Once with `hp` and once without. */
for (int with_hp : { 1, 0 }) {
const int64_t M = 3, L = 4, K = 8, R = 40, NV = 50;
Hand h(with_hp ? "unit codebooks, hp present, ids outside the vocab"
: "unit codebooks, hp absent (a plane of ones)", "dflash_select", 0.0);
h.dense(RAD_I32, { M * L, K }, [](int64_t i) { return (float)((i * 7 + 3) % 53 - 1); })
.dense(RAD_F32, { M * L, K }, hfill(31, 0.5f));
if (with_hp) h.dense(RAD_BF16, { M * L, R }, hfill(32));
else h.none();
h.idx({ 5, 60, 17 })
.dense(RAD_BF16, { NV, R }, hfill(33))
.dense(RAD_BF16, { NV, R }, hfill(34))
.dense(RAD_I32, { M, L }, [](int64_t) { return 0.0f; }, true)
.pi("M", M).pi("steps", L).pi("top_k", K).pi("rank", R).pi("n_vocab", NV)
.pi("anchor_stride", 1).ps("dtype", "bf16");
hs.push_back(std::move(h));
}
/* ---- the fp8 fusions without their optional operands ------------------------------------ *
* The cold descriptions always carry `residual` and `out_bf16`; the plain norm and a caller
* that wants only the codes are the other forms. `mode` 1 is sigmoid in libr4d's spelling. */
{
const int64_t M = 4, n = 200;
Hand r("no residual, no out_bf16, ragged group", "rmsnorm_quant_fp8", 4e-3);
r.dense(RAD_BF16, { M, n }, hfill(41))
.none()
.dense(RAD_BF16, { n }, hfill(42, 0.1f))
.dense(RAD_F8E4M3, { M, n }, [](int64_t) { return 0.0f; }, true)
.dense(RAD_F32, { M, 4 }, [](int64_t) { return 0.0f; }, true)
.pi("M", M).pi("n", n).pf("eps", 1e-6).pi("group", 64).ps("dtype", "bf16")
.pf("wadd", 1.0);
hs.push_back(std::move(r));
Hand g("mode 1, no out_bf16", "gated_quant_fp8", 6e-3);
g.dense(RAD_BF16, { M, 2 * n }, hfill(43))
.dense(RAD_F8E4M3, { M, n }, [](int64_t) { return 0.0f; }, true)
.dense(RAD_F32, { M, 4 }, [](int64_t) { return 0.0f; }, true)
.pi("M", M).pi("n", n).pi("group", 64).ps("dtype", "bf16").pi("mode", 1);
hs.push_back(std::move(g));
}
/* ---- scatter_rows: a negative index writes nothing, and the rows nobody names stay ------- */
{
const int64_t n = 70;
Hand s("idx with -1 over a 12-row pool", "scatter_rows", 0.0);
s.dense(RAD_F32, { 4, n }, hfill(51))
.idx({ 5, -1, 0, 9 })
.dense(RAD_F32, { 12, n }, hfill(52), true)
.pi("M", 4).pi("n", n).ps("dtype", "f32");
hs.push_back(std::move(s));
}
bool ok = true;
int fails = 0;
for (Hand& h : hs) {
++*n_checked;
if (!h.run(ref, avx, verbose)) { ok = false; ++fails; }
}
std::printf(" hand-built: %d checked, %d failed\n", (int)hs.size(), fails);
return ok;
}
/* ================================================================== schema agreement
* core/plugin/loader.cpp:schema_same, reproduced so a drift is caught here rather than at an
* engine start on a machine that has a model on it. */
static bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string* why) {
char buf[256];
if (a.n_params != b.n_params) {
std::snprintf(buf, sizeof buf, "%d parameters vs %d", a.n_params, b.n_params);
*why = buf; return false;
}
for (int i = 0; i < a.n_params; ++i) {
const RadParamSpec& x = a.params[i];
const RadParamSpec& y = b.params[i];
const char* xk = x.key ? x.key : "";
const char* yk = y.key ? y.key : "";
if (std::strcmp(xk, yk)) {
std::snprintf(buf, sizeof buf, "parameter %d is '%s' vs '%s'", i, xk, yk);
*why = buf; return false;
}
if (x.type != y.type) {
std::snprintf(buf, sizeof buf, "parameter '%s' has type %d vs %d", xk, x.type, y.type);
*why = buf; return false;
}
if (x.required != y.required) {
std::snprintf(buf, sizeof buf, "parameter '%s' is %s vs %s", xk,
x.required ? "required" : "optional",
y.required ? "required" : "optional");
*why = buf; return false;
}
}
if (a.n_operands != b.n_operands) {
std::snprintf(buf, sizeof buf, "%d operands vs %d", a.n_operands, b.n_operands);
*why = buf; return false;
}
for (int i = 0; i < a.n_operands; ++i)
if (a.operands[i].role != b.operands[i].role ||
a.operands[i].optional != b.operands[i].optional) {
std::snprintf(buf, sizeof buf, "operand %d ('%s') has a different role/optionality", i,
a.operands[i].name ? a.operands[i].name : "?");
*why = buf; return false;
}
return true;
}
/* embed_lookup_q over a file-backed table, two ranks and the reader racing (avx_check_rows.cpp). */
bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool verbose,
bool bf16);
int main(int argc, char** argv) {
std::string ref_path = "libref.so", avx_path = "libavx.so", only_op;
int only_level = -1;
bool verbose = false;
double tol_override = -1;
for (int i = 1; i < argc; ++i) {
const std::string s = argv[i];
auto next = [&]() -> const char* { return i + 1 < argc ? argv[++i] : ""; };
if (s == "--ref") ref_path = next();
else if (s == "--avx") avx_path = next();
else if (s == "--op") only_op = next();
else if (s == "--level") only_level = std::atoi(next());
else if (s == "--tol") tol_override = std::atof(next());
else if (s == "-v" || s == "--verbose") verbose = true;
else if (s == "-h" || s == "--help") {
std::printf(
"rad-avx-check -- libavx against libref, every op, every ISA level.\n\n"
" --ref PATH the oracle plugin (default libref.so)\n"
" --avx PATH the plugin under test (default libavx.so)\n"
" --op NAME only this op\n"
" --level N only this ISA level (0 scalar 1 avx 2 avx2 3 avx512)\n"
" --tol X override every tolerance (for bisecting, not for passing)\n"
" -v print every case, not only the failures\n");
return 0;
}
}
Lib ref, avx;
if (!ref.open(ref_path.c_str()) || !avx.open(avx_path.c_str())) return 2;
std::printf("oracle : %s %s (%s)\n", ref.info->name, ref.info->version, ref_path.c_str());
std::printf("under : %s %s (%s)\n", avx.info->name, avx.info->version, avx_path.c_str());
/* ---- 1. schema agreement */
int sch_bad = 0;
for (int i = 0, n = avx.schema_count(); i < n; ++i) {
const RadOpSchema* sa = avx.schema_at(i);
if (!sa || !sa->op) continue;
const RadOpSchema* sr = ref.schema(sa->op);
if (!sr) {
std::printf("SCHEMA %-24s declared by libavx and not by libref\n", sa->op);
++sch_bad;
continue;
}
std::string why;
if (!schema_same(*sr, *sa, &why)) {
std::printf("SCHEMA %-24s DISAGREES: %s\n", sa->op, why.c_str());
++sch_bad;
}
}
std::printf("schemas: %d declared, %d disagree with libref\n", avx.schema_count(), sch_bad);
if (sch_bad) {
std::printf("\nThe loader refuses a plugin on ANY schema disagreement, so this would make "
"every row\nlibavx carries unreachable. Nothing below is worth reading until "
"that is fixed.\n");
return 1;
}
/* ---- 2. coverage */
int missing = 0;
for (int i = 0, n = ref.kernel_count(); i < n; ++i) {
const RadKernelInfo* kr = ref.kernel_at(i);
if (!kr || !kr->op) continue;
if (!avx.row(kr->op)) {
std::printf("COVER %-24s libref implements it, libavx does not\n", kr->op);
++missing;
}
}
std::printf("coverage: libref %d rows, libavx %d rows, %d op(s) missing\n",
ref.kernel_count(), avx.kernel_count(), missing);
/* ---- 3/4. the numbers, per ISA level */
const std::vector<Case> cases = build_cases();
if (!avx.isa_force) {
std::printf("\nNOTE: %s exports no avx_isa_force, so only the path it selects for itself "
"is\nexercised. That is honest but it is not the four-level sweep.\n",
avx_path.c_str());
} else {
std::printf("cpu : highest executable level is %s\n", avx.isa_name(avx.isa_detect()));
}
int rc = missing ? 1 : 0;
const int lo = only_level >= 0 ? only_level : 0;
const int hi = only_level >= 0 ? only_level : AVX_N_LEVELS - 1;
std::vector<std::string> declined_ops;
for (int lvl = lo; lvl <= hi; ++lvl) {
int actual = lvl;
if (avx.isa_force) actual = avx.isa_force(lvl);
if (actual != lvl) {
/* CLAMPED, AND SAID SO. Reporting a pass for a level the machine cannot execute would
* be reporting that a path works on a machine that never ran it. */
std::printf("\n== level %d (%s): NOT EXECUTABLE on this CPU -- avx_isa_force clamped to"
" %s.\n This row proves nothing about level %d and is not counted.\n",
lvl, avx.isa_name ? avx.isa_name(lvl) : "?",
avx.isa_name ? avx.isa_name(actual) : "?", lvl);
continue;
}
std::printf("\n== level %d (%s) ==\n", lvl, avx.isa_name ? avx.isa_name(lvl) : "?");
/* Before the tolerances: the conversions have to be EXACT, and they are checked over their
* whole input space rather than over a draw. Run per level, because the vectorised bodies
* differ per level and a draw of normals reaches none of the patterns that separate them. */
if (!exhaustive_cast(ref, avx, verbose)) rc = 1;
Stats st;
for (const Case& c : cases) {
if (!only_op.empty() && only_op != c.op) continue;
/* A speed-only case has no correctness question to ask -- see avx_harness.h. */
if (c.speed_only) continue;
const size_t before = (size_t)st.declined;
run_case(ref, avx, c, verbose, tol_override, &st);
if ((size_t)st.declined != before && lvl == lo) {
bool seen = false;
for (const std::string& s : declined_ops) if (s == c.op) { seen = true; break; }
if (!seen) declined_ops.push_back(c.op);
}
}
std::printf(" %d checked, %d passed, %d failed, %d declined, %d skipped, %d missing."
" worst rel_l2 = %.3e",
st.checked, st.passed, st.failed, st.declined, st.skipped, st.missing,
st.worst);
if (!st.worst_where.empty()) std::printf("\n worst case: %s", st.worst_where.c_str());
std::printf("\n");
if (st.failed || st.declined || st.missing) rc = 1;
if (only_op.empty()) {
int hand_checked = 0;
if (!hand_cases(ref, avx, verbose, &hand_checked)) rc = 1;
}
if (only_op.empty() || only_op == "embed_lookup_q") {
/* Beside the binary: the table is read with O_DIRECT, which a tmpfs refuses. */
const std::string self = argv[0];
const size_t sl = self.rfind('/');
const std::string at = sl == std::string::npos ? "." : self.substr(0, sl);
/* The E4M3 table the quantised containers carry, and the plain bf16 one a checkpoint
* served as it ships carries: one path, two row sizes. */
if (!row_gather_case(avx, at, 1000, verbose, false)) rc = 1;
if (!row_gather_case(avx, at, 1000, verbose, true)) rc = 1;
}
}
if (!declined_ops.empty()) {
std::printf("\nDECLINED (RAD_E_UNSUPPORTED from a row that claims the op) -- %d op(s):\n ",
(int)declined_ops.size());
for (const std::string& s : declined_ops) std::printf(" %s", s.c_str());
std::printf("\nA row that declines is worse than no row: the selector resolves to it and "
"the step\nfails at issue rather than at declare.\n");
}
std::printf("\n%s\n", rc == 0 ? "PASS" : "FAIL");
return rc;
}
+191
View File
@@ -0,0 +1,191 @@
/* avx_check_rows.cpp -- embed_lookup_q over a FILE-BACKED table, the form a model serves it in.
*
* The geometry table checks the op against libref over a heap buffer, which the gather reads as
* memory. A table in a container is not read that way: its rows come through a row cache every
* thread shares, with direct reads of the file for the cache's misses and a reader thread a call
* ahead (avx_ngram.cpp). What can go wrong there is WHICH bytes arrive -- a slot claimed twice, a
* row decoded from a slot that was taken over, a wait on a claim that was given up -- and libref
* has no such path to compare against, so the answer here is the file's own bytes.
*
* Two threads play the ranks of one call, as the engine's rank threads do: the same ids, rank 0
* and 1 of 2, released together, so a thread claims rows, waits on rows the other has claimed, and
* meets its own claim again when an id repeats within a call. Half the ids come from a small hot
* set the cache keeps; the rest from a table four times the cache's 2^19 rows, so sets fill and
* rows are evicted while the other thread may be reading them. Every call also hands over the NEXT
* call's ids as `ahead`, as the engine's prefill does, so the reader thread claims and reads those
* rows while this call's threads are still decoding theirs: a third thread in every race above.
*
* Every output row is compared bit for bit with that id's bytes in the file through the call's
* scale, and a padding id must come back as a zero row. The row is 40 codes, so the AVX-512 decode
* takes one full 32-code step and a masked tail. The table is a file in `dir` rather than under
* TMPDIR, because the gather reads with O_DIRECT and a tmpfs refuses it. */
#include "avx_harness.h"
#include <barrier>
#include <cerrno>
#include <cstring>
#include <thread>
#include <fcntl.h>
#include <linux/io_uring.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool verbose,
bool bf16) {
const RadKernelInfo* r = avx.row("embed_lookup_q");
const char* what = bf16 ? "embed_lookup_q from a file, bf16 table" : "embed_lookup_q from a file";
if (!r || !r->launch) {
std::printf(" %s: no row\n", what);
return false;
}
/* A bf16 table is twice the bytes a row and is read with no scale: its rows are their output,
* so what this checks there is the cache and the reads at a row size the E4M3 table never
* has. */
/* The gather's misses are io_uring reads, and a sandbox can forbid io_uring outright -- Docker's
* default seccomp profile does. There the gather refuses every call by design, so the case
* says why it cannot run rather than counting a refusal per call. */
{
io_uring_params p{};
const long ring = syscall(__NR_io_uring_setup, 1, &p);
if (ring < 0) {
std::printf(" %s: SKIPPED -- io_uring is unavailable here (%s)\n", what,
std::strerror(errno));
return true;
}
::close((int)ring);
}
const int64_t n = 40, V = int64_t(1) << 21, M = 512, hot = 4096;
const int64_t rb = bf16 ? 2 * n : n;
const float scale = 0.375f;
const std::string path = dir + "/rad-avx-check-rows.bin";
uint64_t x = 0x9e3779b97f4a7c15ull;
auto rnd = [&x]() { x ^= x << 13; x ^= x >> 7; x ^= x << 17; return x; };
{
const int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (fd < 0) { std::printf(" %s: cannot create %s\n", what, path.c_str());
return false; }
std::vector<uint64_t> chunk(1 << 16);
bool wrote = true;
for (int64_t done = 0; done < V * rb && wrote; done += (int64_t)(chunk.size() * 8)) {
for (auto& w : chunk) w = rnd();
const size_t want = (size_t)std::min<int64_t>(V * rb - done, (int64_t)chunk.size() * 8);
wrote = ::write(fd, chunk.data(), want) == (ssize_t)want;
}
wrote = wrote && ::fsync(fd) == 0;
::close(fd);
if (!wrote) { ::unlink(path.c_str()); std::printf(" %s: short write\n", what);
return false; }
}
/* A filesystem without direct I/O -- a tmpfs -- is one the gather refuses by design, so the
* case cannot run there; it says so rather than counting a refusal per call. */
{
const int dfd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_DIRECT);
struct statx sx {};
const bool dio = dfd >= 0 &&
::statx(dfd, "", AT_EMPTY_PATH, STATX_DIOALIGN, &sx) == 0 &&
(sx.stx_mask & STATX_DIOALIGN) && sx.stx_dio_offset_align != 0;
if (dfd >= 0) ::close(dfd);
if (!dio) {
::unlink(path.c_str());
std::printf(" %s: SKIPPED -- %s cannot do direct I/O\n", what, dir.c_str());
return true;
}
}
const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
void* map = fd < 0 ? MAP_FAILED : mmap(nullptr, (size_t)(V * rb), PROT_READ, MAP_SHARED, fd, 0);
if (fd >= 0) ::close(fd);
if (map == MAP_FAILED) { ::unlink(path.c_str()); std::printf(" %s: mmap\n", what);
return false; }
const uint8_t* tab = static_cast<const uint8_t*>(map);
std::vector<int32_t> hotset((size_t)hot);
for (auto& h : hotset) h = (int32_t)(rnd() % (uint64_t)V);
std::vector<int32_t> ids((size_t)(calls * M));
for (int64_t c = 0; c < calls; ++c)
for (int64_t m = 0; m < M; ++m) {
const uint64_t v = rnd();
int32_t& id = ids[(size_t)(c * M + m)];
if (m > 0 && v % 29 == 0) id = ids[(size_t)(c * M + m - 1)]; /* repeated in a call */
else if (v % 16 == 0) id = -1; /* padding */
else if (v % 16 < 8) id = hotset[(v >> 8) % (uint64_t)hot];
else id = (int32_t)((v >> 8) % (uint64_t)V);
}
uint16_t lut[256];
for (int b = 0; b < 256; ++b) lut[b] = rad_f32_to_bf16(rad_fp8e4m3_to_f32((uint8_t)b) * scale);
auto tensor = [](void* p, uint32_t dt, std::initializer_list<int64_t> shape) {
RadTensor t{};
t.data = p;
t.dtype = dt;
t.rank = (uint32_t)shape.size();
int i = 0;
for (int64_t s : shape) t.shape[i++] = s;
int64_t st = 1;
for (int k = (int)t.rank - 1; k >= 0; --k) { t.stride[k] = st; st *= t.shape[k]; }
return t;
};
std::barrier<> go(2);
int64_t bad[2] = {0, 0}, refused[2] = {0, 0};
auto rank = [&](int rk) {
uint16_t sc = rad_f32_to_bf16(scale);
std::vector<uint16_t> out((size_t)(M * n));
std::vector<RadTensor> ts = {
tensor(nullptr, RAD_I32, {M}),
tensor(const_cast<uint8_t*>(tab), bf16 ? RAD_BF16 : RAD_F8E4M3, {V, n}),
tensor(bf16 ? nullptr : &sc, RAD_BF16, {1}), tensor(out.data(), RAD_BF16, {M, n}),
tensor(nullptr, RAD_I32, {M}) };
RadParam ps[3] = {};
ps[0].key = "M"; ps[0].kind = RAD_P_INT; ps[0].ival = M;
ps[1].key = "n_embd"; ps[1].kind = RAD_P_INT; ps[1].ival = n;
ps[2].key = "n_vocab"; ps[2].kind = RAD_P_INT; ps[2].ival = V;
RadArgs a{};
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps; a.n_p = 3;
a.rank = rk; a.world_size = 2;
for (int64_t c = 0; c < calls; ++c) {
ts[0].data = &ids[(size_t)(c * M)];
/* The last call has nothing ahead of it, and says so with an absent operand. */
ts[4].data = c + 1 < calls ? &ids[(size_t)((c + 1) * M)] : nullptr;
std::fill(out.begin(), out.end(), (uint16_t)0xdead);
go.arrive_and_wait();
if (r->launch(&a, nullptr) != RAD_OK) { ++refused[rk]; continue; }
for (int64_t m = 0; m < M; ++m) {
const int32_t id = ids[(size_t)(c * M + m)];
for (int64_t i = 0; i < n; ++i) {
uint16_t want = 0;
if (id >= 0 && bf16) std::memcpy(&want, tab + ((int64_t)id * n + i) * 2, 2);
else if (id >= 0) want = lut[tab[(int64_t)id * n + i]];
if (out[(size_t)(m * n + i)] != want) { ++bad[rk]; break; }
}
}
}
};
std::thread t0(rank, 0), t1(rank, 1);
t0.join();
t1.join();
/* THE ADDRESS RANGE STAYS RESERVED. libavx resolves a table to its file once, by the address
* range of its mapping, for the life of the process (avx_ngram.cpp, table_file) -- the
* engine's container mapping is one. A case that unmapped here could have the next case's file
* mapped at the same addresses, and the gather would read this file through the fd it kept:
* every row of the next case wrong, on whichever run the kernel happens to reuse the range.
* An inaccessible anonymous mapping over the same range frees the file and keeps the range. */
if (mmap(map, (size_t)(V * rb), PROT_NONE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS |
MAP_NORESERVE, -1, 0) == MAP_FAILED)
munmap(map, (size_t)(V * rb));
::unlink(path.c_str());
const bool pass = bad[0] + bad[1] + refused[0] + refused[1] == 0;
if (verbose || !pass)
std::printf(" %s: %lld calls x 2 ranks, rows wrong %lld/%lld, "
"calls refused %lld/%lld %s\n", what, (long long)calls, (long long)bad[0],
(long long)bad[1], (long long)refused[0], (long long)refused[1],
pass ? "ok" : "FAIL");
else
std::printf(" %s: %lld calls x 2 ranks, every row exact\n", what, (long long)calls);
return pass;
}
+361
View File
@@ -0,0 +1,361 @@
/* avx_common.h -- what every kernel in this plugin needs and the ABI does not give it.
*
* Deliberately thin. rad_plugin.h already carries the parameter readers, the absent-operand rule,
* the row-pitch helper and every narrowing conversion, and its header explains at length why those
* belong in the ABI rather than once per plugin. This plugin calls them. What is here is the three
* things that are genuinely this plugin's:
*
* THE SCRATCH ARENA. Every kernel converts a row to f32 before it computes (avx_vec.h), so every
* kernel needs a row of scratch. RadArgs::scratch would be the ABI's answer and it is the wrong
* one here: it is sized once at declare from the band's upper bound, it is one buffer, and this
* plugin runs its outer loop under OpenMP -- so every thread needs its own, and the number of
* threads is not known at declare. A thread_local arena that grows to a high-water
* mark and is then reused is allocation-free on the hot path, which is what the ABI's "must not
* allocate" is protecting, and it is what libref does too (it holds std::vector in its kernels).
* The growth is logged under AVX_TRACE so a kernel that reallocates per call is visible.
*
* THE OPERAND PREAMBLE. Sixty-eight launches open by fetching n operands, refusing if a required
* one is absent, and reading the extents off the tensors rather than off the parameters --
* libref/ref_ops.h explains why that rule exists and it is the same rule here: a ranged parameter
* is collapsed to a BAND, so a loop bounded by `M` runs to the band's upper bound and walks off
* the arena. Every extent in this plugin comes from a RadTensor.
*
* THE THREADING DECISION, in one place. OpenMP over the OUTER dimension only, one thread owning
* whole output rows, no reduction() clause anywhere -- the same rule libref states, for a
* different reason. libref wants bit-identical answers across thread counts because it is the
* oracle. This plugin wants them because a kernel whose answer moves with the machine's load is
* a kernel no measurement can rank: two runs of the same binary would differ, and the difference
* would be read as whatever change was under test.
*/
#ifndef RAD_AVX_COMMON_H
#define RAD_AVX_COMMON_H
#include "rad_abi.h"
#include "rad_plugin.h"
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <cmath>
#ifdef _OPENMP
#include <omp.h>
#define AVX_PRAGMA(x) _Pragma(#x)
#define AVX_PARALLEL_FOR AVX_PRAGMA(omp parallel for schedule(static))
/* THE OUTER LOOP IS WORTH A TEAM ONLY WHEN THERE IS ENOUGH WORK TO PAY FOR STARTING ONE, and the
* `if` clause is how that is said without writing the serial loop twice. A fork/join costs a few
* microseconds; an op below the threshold spends more time in the barrier than in the arithmetic,
* which is the same shape of problem a small device dispatch has, one level down. The crossover is
* measured by `rad-avx-bench --threads`.
*
* `cond` is pasted into the pragma text, so it must contain no comma. */
#define AVX_PARALLEL_FOR_IF(cond) AVX_PRAGMA(omp parallel for schedule(static) if(cond))
#else
#define AVX_PARALLEL_FOR
#define AVX_PARALLEL_FOR_IF(cond)
#endif
/* Elements of output a launch must touch before a parallel region pays for itself. Used as
* AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN). */
#define AVX_PAR_MIN 16384
namespace avx {
/* ================================================================== scratch
* Aligned to 64 so a 512-bit aligned load is legal off it at every level. Returns a buffer of at
* least `n` floats, valid until the next call on this thread that asks for more. */
float* scratch_f32(size_t n);
/* A second and third independent buffer, for kernels that need two rows live at once (every gated
* op: gate and up, a and b, x and residual). Separate functions rather than an index so the call
* site says which buffer it means. */
float* scratch_f32_b(size_t n);
float* scratch_f32_c(size_t n);
void* scratch_raw(size_t bytes);
/* ================================================================== operand preamble */
/* Fetch the first `n` operands into `out`, returning 0 if any is absent. The array is indexed
* positionally and an absent OPTIONAL operand past `n` is fetched with rad_arg_in directly. */
static inline int take(const RadArgs* a, int n, const RadTensor** out) {
for (int i = 0; i < n; ++i) {
out[i] = rad_arg_in(a, i);
if (!out[i]) return 0;
}
return 1;
}
/* The (rows, lastdim) reading of a tensor, and the pitch between rows. Three lines every kernel
* would otherwise write. */
struct Plane {
void* p;
uint32_t dt;
int64_t rows, n, pitch;
};
static inline Plane plane(const RadTensor* t) {
Plane s;
s.p = t->data;
s.dt = t->dtype;
s.rows = rad_tensor_rows(t);
s.n = rad_tensor_lastdim(t);
s.pitch = rad_tensor_row_pitch(t);
return s;
}
/* Element offset of row r. Strides are in ELEMENTS (rad_types.h), so this is what a caller adds to
* a typed pointer -- never a byte count, which is what makes it safe for W4/W2 where a byte count
* would be fractional. */
static inline int64_t row_off(const Plane& s, int64_t r) { return r * s.pitch; }
/* ================================================================== libref's addressing, exactly
*
* THESE ARE COPIED FROM libref/ref_common.h AND THEY HAVE TO BE. They are not conveniences, they
* are the ADDRESSING CONTRACT: which bytes an operand's element (r, i) lives at, how a rank-3
* tensor is read as [rows, cols], and what a strided view means. A plugin that computed the right
* arithmetic over the wrong bytes would be checked against the oracle and would fail in a way that
* looks like a numerical bug, which is the most expensive kind to chase.
*
* `numel` returning 0 for a null-data tensor is part of it: that is how libref's shape checks
* refuse an absent required operand, and a copy that returned the product of the shape instead
* would accept the call and fault. */
static inline int64_t numel(const RadTensor* t) {
if (!t || !t->data || t->rank == 0) return 0;
int64_t n = 1;
for (uint32_t i = 0; i < t->rank; ++i) n *= t->shape[i];
return n;
}
static inline int64_t laststride(const RadTensor* t) { return t->rank ? t->stride[t->rank - 1] : 1; }
/* Element offset of the `lin`-th element in row-major logical order. */
static inline int64_t offlin(const RadTensor* t, int64_t lin) {
if (t->rank == 0) return lin;
int64_t acc = 1;
bool c = true;
for (int i = (int)t->rank - 1; i >= 0; --i) {
if (t->shape[i] != 1 && t->stride[i] != acc) { c = false; break; }
acc *= t->shape[i];
}
if (c) return lin;
int64_t off = 0;
for (int i = (int)t->rank - 1; i >= 0; --i) {
int64_t s = t->shape[i];
if (s <= 0) return 0;
off += (lin % s) * t->stride[i];
lin /= s;
}
return off;
}
/* The element offset of logical row `r` read as [rows, cols]. The leading axes are walked with
* their OWN strides, so a [T, H, V] tensor read as [T*H, V] lands correctly even when H's stride
* is not V -- which is exactly the fused-projection column slice docs/OPS.md warns about. */
static inline int64_t rowoff(const RadTensor* t, int64_t r, int64_t cols) {
if (t->rank >= 2 && t->shape[t->rank - 1] == cols) {
int64_t off = 0;
for (int i = (int)t->rank - 2; i >= 0; --i) {
int64_t s = t->shape[i];
if (s <= 0) return 0;
off += (r % s) * t->stride[i];
r /= s;
}
return off;
}
return r * cols;
}
static inline int64_t rows_of(const RadTensor* t, int64_t n) { return n > 0 ? numel(t) / n : 0; }
/* THE OPERAND'S EXTENT, WITH THE RANGED PARAMETER AS A CEILING. libref/ref_common.h's band_rows,
* copied for the reason the header gives: `M`, `numel` and `q_len` arrive as the band's upper
* bound, so the call's row count is the operand's and a count above the band is a caller bug. */
static inline int64_t band_rows(int64_t from_operand, int64_t band) {
if (from_operand <= 0) return 0;
return (band > 0 && from_operand > band) ? 0 : from_operand;
}
/* THE BLOCK A SCALE GRID OF `blocks` PIECES IMPLIES OVER `ext` ELEMENTS -- libref/ref_gemm.h's
* grid_block, which says why it is the power of two whose ceiling division gives `blocks` and not
* the quotient ext / blocks: a grid's last block may be partial. */
static inline int64_t grid_block(int64_t ext, int64_t blocks) {
if (ext <= 0) return 1;
if (blocks <= 1) return ext;
const int64_t lo = (ext + blocks - 1) / blocks;
int64_t b = 1;
while (b < lo) b <<= 1;
return (ext + b - 1) / b == blocks ? b : lo;
}
/* `row_stride`: which axis carries a row of `cols` elements, at whatever rank the operand arrived
* in -- libref/ref_gemm.h's rule, copied for the header's reason. A rank-2 operand is not dense
* because it is rank 2: the engine hands attention a COLUMN SLICE of the fused QKV plane,
* [tokens, kv_heads * head_dim] with the whole projection's width as its row stride, and deriving
* the stride from the shape reads every token after the first out of the previous token's row. */
static inline int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
int64_t span = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
span *= t->shape[i];
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
if (span > cols) break;
}
return t->stride[t->rank - 2];
}
/* ONE ELEMENT, AS f32 AND BACK, with the two things the ABI's accessors do not do.
*
* THE PACKED CODES. rad_load_f32 returns 0 for W4, W2 and MXFP4 -- its contract says a dtype it
* cannot read is a refusal and not a value -- so every strided or odd-offset read of a packed
* weight that falls off the row converter would decode as zeros. The codes are libref's
* (ref_common.h: w4_code, w2_code, mxfp4_code), the same ones row_to_f32 unpacks in bulk.
*
* THE INTEGER STORE ROUNDS TO NEAREST-EVEN AND SATURATES, as libref's st_dt does, where
* rad_store_f32 truncates and converts out-of-range values with a plain cast. A NaN stores 0. */
static inline float ld_elem(const void* p, uint32_t dt, int64_t i) {
switch (dt) {
case RAD_I4: {
const uint8_t b = ((const uint8_t*)p)[i >> 1];
const uint8_t nb = (i & 1) ? (uint8_t)(b >> 4) : (uint8_t)(b & 0xf);
return (float)((int)(nb ^ 0x8u) - 8);
}
case RAD_I2: {
const uint8_t b = ((const uint8_t*)p)[i >> 2];
const uint8_t c = (uint8_t)((b >> (2 * (i & 3))) & 0x3u);
return (float)((int)(c ^ 0x2u) - 2);
}
case RAD_FP4E2M1: {
static const float kMag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
const uint8_t b = ((const uint8_t*)p)[i >> 1];
const uint8_t nb = (i & 1) ? (uint8_t)(b >> 4) : (uint8_t)(b & 0xf);
return (nb & 8u) ? -kMag[nb & 7u] : kMag[nb & 7u];
}
default: return rad_load_f32(p, dt, i);
}
}
/* Round to nearest-even and clamp to [lo, hi], in double so that every bound of every integer
* width up to 32 bits is exact. NaN is 0. */
static inline double round_sat(float v, double lo, double hi) {
if (std::isnan(v)) return 0.0;
const double r = (double)std::nearbyintf(v);
return r < lo ? lo : (r > hi ? hi : r);
}
static inline void st_elem(void* p, uint32_t dt, int64_t i, float v) {
switch (dt) {
case RAD_I8: ((int8_t*)p)[i] = (int8_t)round_sat(v, -128.0, 127.0); break;
case RAD_U8: ((uint8_t*)p)[i] = (uint8_t)round_sat(v, 0.0, 255.0); break;
case RAD_I16: ((int16_t*)p)[i] = (int16_t)round_sat(v, -32768.0, 32767.0); break;
case RAD_I32: ((int32_t*)p)[i] = (int32_t)round_sat(v, -2147483648.0, 2147483647.0); break;
case RAD_U32: ((uint32_t*)p)[i] = (uint32_t)round_sat(v, 0.0, 4294967295.0); break;
case RAD_I64: {
/* 2^63 is the first float past the range, so the bound is a comparison, not a clamp
* value a double could hold. */
const double r = round_sat(v, -9223372036854775808.0, 9223372036854775808.0);
((int64_t*)p)[i] = r >= 9223372036854775808.0 ? INT64_MAX : (int64_t)r;
break;
}
default: rad_store_f32(p, dt, i, v); break;
}
}
static inline float ldt(const RadTensor* t, int64_t off) { return ld_elem(t->data, t->dtype, off); }
static inline void stt(const RadTensor* t, int64_t off, float v) {
st_elem(t->data, t->dtype, off, v);
}
/* IS THIS OPERAND'S ROW DENSE? The whole vectorised path is predicated on it: a row whose elements
* are one apart can be converted with one call and then read as a flat f32 array, and a row whose
* elements are not has to go through the strided gather. Almost every operand in a real step is
* dense; the exceptions are named in docs/OPS.md and are a handful of sites. */
static inline bool dense_row(const RadTensor* t) { return laststride(t) == 1; }
/* ================================================================== parameters
* Deliberately LAXER than rad_param_geti, and for libref's reason rather than a different one: a
* tool or a test may call a launch directly with no declare in front of it to enforce the type, so
* a range and a string spelling of an integer are both read rather than refused. The ABI's own
* reader is right for a kernel reached through declare and wrong for one reached through a
* checker, and this plugin is reached through both. */
static inline const RadParam* p_find(const RadArgs* a, const char* k) {
return a ? rad_param_find(a->p, a->n_p, k) : nullptr;
}
static inline long long p_int(const RadArgs* a, const char* k, long long dflt) {
const RadParam* p = p_find(a, k);
if (!p) return dflt;
if (p->kind == RAD_P_INT) return p->ival;
if (p->kind == RAD_P_RANGE) return p->ihi;
if (p->kind == RAD_P_STR && p->sval) return std::strtoll(p->sval, nullptr, 10);
return dflt;
}
static inline const char* p_str(const RadArgs* a, const char* k, const char* dflt) {
const RadParam* p = p_find(a, k);
if (!p) return dflt;
if (p->kind == RAD_P_STR && p->sval) return p->sval;
return dflt;
}
static inline float p_f32(const RadArgs* a, const char* k, float dflt) {
const RadParam* p = p_find(a, k);
if (!p) return dflt;
if (p->kind == RAD_P_F64) return (float)p->dval;
if (p->kind == RAD_P_STR && p->sval) return (float)std::strtod(p->sval, nullptr);
if (p->kind == RAD_P_INT) return (float)p->ival;
if (p->kind == RAD_P_RANGE) return (float)p->ihi;
return dflt;
}
static inline int p_enum(const RadArgs* a, const char* k, const char* const* names, int n,
int dflt) {
const RadParam* p = p_find(a, k);
if (!p) return dflt;
if (p->kind == RAD_P_STR && p->sval) {
for (int i = 0; i < n; ++i)
if (names[i] && std::strcmp(names[i], p->sval) == 0) return i;
return dflt;
}
if (p->kind == RAD_P_INT) return (int)p->ival;
return dflt;
}
static inline int64_t ld_int_dt(uint32_t dt, const void* p, int64_t i) {
switch (dt) {
case RAD_I32: return (int64_t)((const int32_t*)p)[i];
case RAD_U32: return (int64_t)((const uint32_t*)p)[i];
case RAD_I64: return ((const int64_t*)p)[i];
case RAD_I16: return (int64_t)((const int16_t*)p)[i];
case RAD_I8: return (int64_t)((const int8_t*)p)[i];
case RAD_U8: return (int64_t)((const uint8_t*)p)[i];
case RAD_BOOL: return ((const uint8_t*)p)[i] ? 1 : 0;
case RAD_F32: return (int64_t)((const float*)p)[i];
default: return 0;
}
}
static inline void st_int_dt(uint32_t dt, void* p, int64_t i, int64_t v) {
switch (dt) {
case RAD_I32: ((int32_t*)p)[i] = (int32_t)v; break;
case RAD_U32: ((uint32_t*)p)[i] = (uint32_t)v; break;
case RAD_I64: ((int64_t*)p)[i] = v; break;
case RAD_I16: ((int16_t*)p)[i] = (int16_t)v; break;
case RAD_I8: ((int8_t*)p)[i] = (int8_t)v; break;
case RAD_U8: ((uint8_t*)p)[i] = (uint8_t)v; break;
default: rad_store_f32(p, dt, i, (float)v); break;
}
}
static inline int64_t ldi(const RadTensor* t, int64_t off) { return ld_int_dt(t->dtype, t->data, off); }
/* Bytes of element i for a dtype whose element is not a whole byte. Only the packed weight codes
* need it and they are always read through row_to_f32, but `dequant` addresses a group start. */
static inline const void* byte_at(const void* base, uint32_t dt, int64_t i) {
const uint8_t* b = (const uint8_t*)base;
switch (dt) {
case RAD_I4: case RAD_FP4E2M1: return b + (i >> 1);
case RAD_I2: return b + (i >> 2);
default: return b + i * (size_t)(rad_dtype_bits(dt) / 8);
}
}
} /* namespace avx */
#endif /* RAD_AVX_COMMON_H */
+239
View File
@@ -0,0 +1,239 @@
/* avx_dispatch.cpp -- the one translation unit that may not contain a vector instruction.
*
* ============================== THE RULE THIS FILE EXISTS TO ENFORCE ==============================
*
* Everything else in this plugin is compiled with -mavx2 or -mavx512f and therefore may not be
* EXECUTED until something has established that the machine can run it. This file is what
* establishes it, so it is compiled with no -m flags at all, and CMakeLists.txt states that as a
* property of the target rather than leaving it to habit.
*
* The failure mode if this is got wrong is worth naming because it is not a wrong answer, it is a
* SIGILL in the fallback that exists to prevent SIGILLs, and it happens before main, on whichever
* machine the build was not tested on. A compiler is free to auto-vectorise anything it likes in a file
* compiled with -mavx512f -- including the table-of-function-pointers copy below, which is exactly
* the shape a vectoriser likes -- so "this function contains no intrinsics" is not the same claim
* as "this function contains no AVX-512", and only the flags on the object give the second one.
*
* ============================== WHAT IS DETECTED, AND WHY __builtin_cpu_supports ==============================
*
* Raw CPUID is not enough and the reason is the OS, not the CPU. AVX and AVX-512 add architectural
* state (YMM, then ZMM and the mask registers) that the kernel must agree to save across a context
* switch; it signals that through XCR0, read with XGETBV. A CPU may enumerate AVX-512 in CPUID
* while the OS has left the ZMM state disabled -- a VM with a restricted feature mask, an older
* kernel, a hypervisor hiding it -- and using AVX-512 then faults on the first instruction.
* __builtin_cpu_supports does the XGETBV check; a hand-rolled CPUID dispatch usually does not, and
* that omission is the single most common way this kind of code is wrong.
*
* AVX-512 IS ALSO NOT ONE FEATURE. The check below is the conjunction of F, BW, DQ and VL because
* the kernels use all four: BW for the byte and word shuffles the bf16 pack needs, DQ for the
* 64-bit integer forms, VL for the 128/256-bit encodings of the AVX-512 instructions. A Knights
* Landing has F and not the others, and a kernel that tested F alone would fault on it.
*/
#include "avx_isa.h"
#include "avx_common.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <new>
#include <vector>
/* ================================================================== the fp8 decode tables
*
* Built at load from the ABI's OWN converters, not typed out. A typed-out table is a second
* definition of the format and can drift from rad_fp8e4m3_to_f32, which is exactly what
* rad_plugin.h's header argues against at length. 256 calls at startup cost nothing and cannot
* disagree. */
extern "C" { float avx_fp8e4m3_tab[256] = { 0 };
float avx_fp8e5m2_tab[256] = { 0 }; }
static void fp8_tables_init(void) {
for (int i = 0; i < 256; ++i) {
avx_fp8e4m3_tab[i] = rad_fp8e4m3_to_f32((uint8_t)i);
avx_fp8e5m2_tab[i] = rad_fp8e5m2_to_f32((uint8_t)i);
}
}
/* ================================================================== detection */
static int g_detected = -1;
static int g_level = -1;
extern "C" int avx_isa_detect(void) {
if (g_detected >= 0) return g_detected;
#if defined(__x86_64__) || defined(_M_X64) || defined(__i386__)
__builtin_cpu_init();
if (__builtin_cpu_supports("avx512f") && __builtin_cpu_supports("avx512bw") &&
__builtin_cpu_supports("avx512dq") && __builtin_cpu_supports("avx512vl"))
g_detected = AVX_LEVEL_AVX512;
else if (__builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") &&
__builtin_cpu_supports("f16c"))
g_detected = AVX_LEVEL_AVX2;
else if (__builtin_cpu_supports("avx"))
g_detected = AVX_LEVEL_AVX;
else
g_detected = AVX_LEVEL_SCALAR;
#else
/* Not x86. The plugin still loads and still computes the right answers -- that is the whole
* point of the scalar level being a real implementation rather than a stub -- it is simply
* slow, and `rad_plugin_info().build_target` says "host" so nothing is being claimed. */
g_detected = AVX_LEVEL_SCALAR;
#endif
return g_detected;
}
extern "C" const char* avx_isa_name(int level) {
switch (level) {
case AVX_LEVEL_SCALAR: return "scalar";
case AVX_LEVEL_AVX: return "avx";
case AVX_LEVEL_AVX2: return "avx2";
case AVX_LEVEL_AVX512: return "avx512";
default: return "?";
}
}
extern "C" const AvxKernelTable* avx_table_for(int level) {
switch (level) {
case AVX_LEVEL_AVX512: return &avx_table_v3;
case AVX_LEVEL_AVX2: return &avx_table_v2;
case AVX_LEVEL_AVX: return &avx_table_v1;
default: return &avx_table_sc;
}
}
static const AvxKernelTable* g_tab = 0;
extern "C" const AvxKernelTable* avx_table_live(void) {
if (!g_tab) { g_level = avx_isa_detect(); g_tab = avx_table_for(g_level); }
return g_tab;
}
extern "C" int avx_isa_level(void) {
if (g_level < 0) (void)avx_table_live();
return g_level;
}
extern "C" int avx_isa_force(int level) {
const int cap = avx_isa_detect();
/* CLAMPED, NOT HONOURED. Asking for a level the machine cannot execute is a caller error, and
* the only honest response is to run what the machine has -- returning the level actually
* selected so a checker can report "asked for avx512, ran avx2" rather than believing it
* tested something it did not. Honouring it would be a SIGILL. */
if (level < 0) level = 0;
if (level > cap) level = cap;
g_level = level;
g_tab = avx_table_for(level);
return level;
}
/* ================================================================== the thunks
*
* One baseline-compiled function per op, pointed at by the registry row, doing one indirect call
* into the selected level's table.
*
* WHY NOT REPOINT THE ROWS THEMSELVES. RadKernelInfo is returned by rad_kernel_at as a
* `const RadKernelInfo*` out of a static table, and the loader is entitled to read it before
* rad_plugin_open has run (it reads the op names to check schema agreement). A row whose `launch`
* was null until open() had patched it is a row that is briefly wrong, and a row that is briefly
* wrong during startup is read as a row that was never wired at all. A
* thunk is always correct, needs no mutation of a table the ABI hands out as const, and costs one
* predicted indirect branch per launch -- which against a kernel whose cheapest form touches a
* 4096-element row is not measurable. */
#define AVX_THUNK(nm) \
extern "C" int avx_thunk_##nm(const RadArgs* a, RadStream s) { \
return avx_table_live()->nm(a, s); \
}
AVX_OP_LIST(AVX_THUNK)
#undef AVX_THUNK
/* ================================================================== scratch
*
* One growable arena per thread per slot. The first call at a given size allocates; every call
* after it at or below that size does not, which is what makes the hot path allocation-free
* without pretending a host kernel can work in zero bytes.
*
* ALIGNED TO 64 so that a _mm512_load_ps off it is legal -- an aligned load from a 32-byte-aligned
* buffer is a fault at AVX-512, and `new float[]` promises only 16. The kernels mostly use the
* unaligned loads (on every core since Nehalem the penalty is zero when the address happens to be
* aligned, so there is nothing to win by demanding alignment), but the GEMM packing buffers use
* aligned stores and they come from here. */
namespace {
struct Arena {
void* p = nullptr;
size_t bytes = 0;
~Arena() { std::free(p); }
void* get(size_t want) {
if (want <= bytes) return p;
/* Grow geometrically: a kernel called at a ladder of increasing sizes would otherwise
* realloc at every rung. A request past half the address space is taken as asked, so the
* doubling cannot wrap to zero and spin. */
size_t nb = bytes ? bytes : 4096;
while (nb < want) nb = nb > SIZE_MAX / 2 ? want : nb * 2;
void* q = nb <= SIZE_MAX - 63 ? std::aligned_alloc(64, (nb + 63) & ~(size_t)63) : nullptr;
/* NO BUFFER IS A STOP, NOT A SMALLER BUFFER. The contract is "at least the size asked
* for" and no caller checks it: every kernel writes the full row into what comes back,
* most of them inside an OpenMP body that cannot return a status. Handing back the old,
* smaller buffer turns an allocation failure into a heap overflow that corrupts whatever
* sits after it; a null would be a fault at an address that says nothing. So the process
* stops here, with the size that could not be had. */
if (!q) {
std::fprintf(stderr, "libavx: could not allocate %zu bytes of kernel scratch\n", want);
std::abort();
}
std::free(p);
p = q; bytes = nb;
return p;
}
};
thread_local Arena g_a, g_b, g_c, g_raw;
} /* namespace */
namespace avx {
float* scratch_f32 (size_t n) { return (float*)g_a.get(n * sizeof(float)); }
float* scratch_f32_b(size_t n) { return (float*)g_b.get(n * sizeof(float)); }
float* scratch_f32_c(size_t n) { return (float*)g_c.get(n * sizeof(float)); }
void* scratch_raw (size_t b) { return g_raw.get(b); }
}
/* ================================================================== plugin open/close
* The loader resolves these by these exact names (rad_abi.h) and a plugin that spells them
* differently is silently never initialised -- which here would mean an fp8 table of zeros and
* every fp8 operand reading as 0.0, a wrong answer with no diagnostic. Spelled from the ABI's own
* typedefs so a signature drift is a compile error. */
extern "C" int rad_plugin_open(void) {
fp8_tables_init();
(void)avx_table_live();
return RAD_OK;
}
extern "C" void rad_plugin_close(void) {}
[[maybe_unused]] static const RadPluginOpenFn kOpenCheck = rad_plugin_open;
[[maybe_unused]] static const RadPluginCloseFn kCloseCheck = rad_plugin_close;
/* ================================================================== the measured FMA ceiling
*
* Exported for rad-avx-bench, and it has to come from HERE rather than from the bench because the
* bench is baseline-compiled (see the top of this file) and can only emit SSE2. The per-level
* probes live in avx_support.cpp, compiled with the same flags as every kernel, so what they
* report is the ceiling the kernels are actually up against -- including whatever clock the part
* holds under a sustained vector load, which on anything with an AVX-512 frequency offset is not
* the advertised boost.
*
* Returns the FLOPS PERFORMED, not a rate: the caller owns the clock, because it is the caller
* that knows to take a median over repetitions rather than trusting one. */
extern "C" double avx_peak_fma_sc(int64_t);
extern "C" double avx_peak_fma_v1(int64_t);
extern "C" double avx_peak_fma_v2(int64_t);
extern "C" double avx_peak_fma_v3(int64_t);
extern "C" double avx_peak_fma(int level, int64_t iters) {
switch (level) {
case AVX_LEVEL_AVX512: return avx_peak_fma_v3(iters);
case AVX_LEVEL_AVX2: return avx_peak_fma_v2(iters);
case AVX_LEVEL_AVX: return avx_peak_fma_v1(iters);
default: return avx_peak_fma_sc(iters);
}
}
+430
View File
@@ -0,0 +1,430 @@
/* avx_elementwise.cpp -- the elementwise vocabulary: add, mul, the activations, the gated product,
* the row gather and scatter, cast, softmax and the per-row scale.
*
* ============================== THESE ARE MEMORY-BOUND, NOT COMPUTE-BOUND ==============================
*
* Every op in this file touches each element a constant number of times and does a handful of
* flops with it, so the ceiling is the load/store units and then the cache hierarchy. That decides
* the shape of the code twice over:
*
* THE DTYPE SWITCH IS HOISTED TO THE ROW. libref calls ld_dt() per element, which is a switch on
* every load and the reason it is slow -- it is not the scalar arithmetic, it is that no
* vectoriser can cross that branch. `in_row`/`out_row` (avx_support.cpp) convert a whole row
* once and hand back f32. For an f32 operand they hand back the caller's own pointer and copy
* nothing.
*
* THE FUSED FORMS ROUND EXACTLY WHERE libref ROUNDS. This is the part that is not a performance
* decision and cannot be traded: `softmax` writes the un-normalised exponentials to `y`, reads
* them BACK through the output dtype, and multiplies by 1/sum -- so at bf16 the answer carries
* two roundings and not one. `rmsnorm_add` does the same with `residual_out`. A faster
* implementation that kept f32 all the way through would be half an ulp BETTER and would
* disagree with the oracle and with every device kernel this is checked beside. The round trip
* is done in a hot scratch buffer rather than through the output operand, which is the same
* arithmetic at cache-resident cost.
*
* ============================== THE BROADCAST RULES ARE TWO DIFFERENT OPS ==============================
*
* `mul` broadcasts a single ROW down the rows -- a bias's shape. `scale_rows` broadcasts a single
* COLUMN across them -- a per-token gate's. They are separate ops precisely so that neither has to
* guess, and the guess would be ambiguous exactly when rows == n. libref's header makes the same
* point; it is repeated here because the temptation to merge them is real and the failure is a
* plausible number rather than an error.
*/
#include "avx_vec.h"
#include "avx_common.h"
using namespace avx;
/* Round a row of f32 through an operand's storage dtype and back, which is what a fused op that
* writes an intermediate and reads it again computes. A no-op for f32, which is why the f32
* tolerance for these ops is as tight as it is. */
static inline void roundtrip(uint32_t dt, float* v, int64_t n, void* tmp) {
if (dt == RAD_F32) return;
row_from_f32(dt, v, tmp, n);
row_to_f32(dt, tmp, v, n);
}
/* ------------------------------------------------------------------ add / mul */
/* y = a op b over the output's extent. `b` may carry exactly one row and is then broadcast down
* the rows; nothing else broadcasts, because silent broadcasting of an arbitrary shape is how a
* shape bug becomes a plausible number. */
template <bool MUL>
static int elementwise2(const RadArgs* a) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
const int64_t n = p_int(a, "n", numel(Y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(A) < rows * n) return RAD_E_SHAPE;
const bool bcast = numel(B) == n && rows > 1;
if (!bcast && numel(B) < rows * n) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* sa = scratch_f32((size_t)n);
float* sb = scratch_f32_b((size_t)n);
float* sy = scratch_f32_c((size_t)n);
const float* x = in_row(A, rowoff(A, r, n), n, sa);
const float* y = in_row(B, bcast ? 0 : rowoff(B, r, n), n, sb);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) {
vf u = vf_loadu(x + i), v = vf_loadu(y + i);
vf_storeu(sy + i, MUL ? vf_mul(u, v) : vf_add(u, v));
}
for (; i < n; ++i) sy[i] = MUL ? x[i] * y[i] : x[i] + y[i];
out_row(Y, rowoff(Y, r, n), n, sy);
}
return RAD_OK;
}
AVX_KERNEL(add) { return elementwise2<false>(a); }
AVX_KERNEL(mul) { return elementwise2<true>(a); }
/* ------------------------------------------------------------------ scale_rows */
/* y[m, i] = x[m, i] * act(s[m]), then + add[m, i] if the optional residual is passed.
*
* The activation is applied to the SCALAR and not to the product, which is what a gate means --
* Qwen3.5-MoE's shared expert is scaled by sigmoid(shared_expert_gate(x)).
*
* THE RESIDUAL ADD IS A ROUND TRIP AND THAT IS THE CONTRACT. libref stores the product into `y`,
* READS IT BACK, and stores the sum -- so at bf16 the product is narrowed before the add sees it.
* That is not an artefact of writing it as two statements: it is what a fused kernel does, because
* the product has to be stored anyway. Reproduced here in a hot buffer rather than through the
* operand, which is the same arithmetic without the second pass over memory. */
AVX_KERNEL(scale_rows) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *sc = &a->t[1], *y = &a->t[3];
const RadTensor* ad = rad_arg_in(a, 2);
const int64_t n = p_int(a, "n", numel(y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(x) < rows * n || numel(sc) < rows) return RAD_E_SHAPE;
if (ad && numel(ad) < rows * n) return RAD_E_SHAPE;
const char* act = p_str(a, "act", "none");
const bool sig = act && !std::strcmp(act, "sigmoid");
if (act && std::strcmp(act, "sigmoid") && std::strcmp(act, "none")) return RAD_E_INVAL;
const int64_t ss = laststride(sc);
const size_t tmpb = (size_t)n * sizeof(float) + 64;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
const float v0 = ldt(sc, r * ss);
/* The SCALAR sigmoid, through the ABI's arithmetic and not the vector polynomial: one
* value per row, so there is nothing to vectorise, and going through the same expf the
* oracle does removes a source of disagreement for free. */
const float v = sig ? 1.0f / (1.0f + std::exp(-v0)) : v0;
float* sx = scratch_f32((size_t)n);
float* sy = scratch_f32_b((size_t)n);
const float* xr = in_row(x, rowoff(x, r, n), n, sx);
const vf vv = vf_set1(v);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) vf_storeu(sy + i, vf_mul(vf_loadu(xr + i), vv));
for (; i < n; ++i) sy[i] = xr[i] * v;
if (ad) {
void* tp = scratch_raw(tmpb);
roundtrip(y->dtype, sy, n, tp);
float* sa = scratch_f32_c((size_t)n);
const float* av = in_row(ad, rowoff(ad, r, n), n, sa);
i = 0;
for (; i + VF_N <= n; i += VF_N)
vf_storeu(sy + i, vf_add(vf_loadu(sy + i), vf_loadu(av + i)));
for (; i < n; ++i) sy[i] += av[i];
}
out_row(y, rowoff(y, r, n), n, sy);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ silu_mul */
/* y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The gate is the FIRST half, which is the
* order rad-convert fuses gate and up into one weight in, so the two conventions cannot drift.
*
* THE bf16 OUTPUT TAKES A CHEAPER SILU, and that is a precision argument rather than a
* punt: vf_silu's degree-5 minimax exp plus a full division is ~0.6 ulp, while a bf16 store
* rounds at 3e-3 -- the output cannot carry what the exact path computes. The fast form is
* vf_silu_fast (avx_vec.h -- shared with the conv kernels since, same rule: keyed on the
* OUTPUT dtype, twentyfold inside the bf16 bucket), and f32 outputs keep the exact path.
* Local to ops whose product is consumed once -- shared vf_sigmoid feeds gate chains whose
* errors accumulate. */
AVX_KERNEL(silu_mul) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *gu = &a->t[0], *y = &a->t[1];
const int64_t n = p_int(a, "n", numel(y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(gu) < rows * 2 * n) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
/* One in_row over the WHOLE 2n row rather than two over its halves: the two halves are
* adjacent in memory and one conversion of 2n beats two of n by the call overhead and by
* keeping the hardware prefetcher on a single stream. */
float* s = scratch_f32((size_t)(2 * n));
float* sy = scratch_f32_b((size_t)n);
const float* g = in_row(gu, rowoff(gu, r, 2 * n), 2 * n, s);
const float* u = g + n;
#if AVX_LEVEL >= 2
/* The fast silu is a precision decision keyed on the OUTPUT dtype (see above): a bf16
* store cannot carry 6e-5, an f32 one is held at 1e-6. */
if (y->dtype == RAD_BF16) {
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N)
vf_storeu(sy + i, vf_mul(vf_silu_fast(vf_loadu(g + i)), vf_loadu(u + i)));
for (; i < n; ++i) {
const float gi = g[i];
sy[i] = (gi / (1.0f + std::exp(-gi))) * u[i];
}
out_row(y, rowoff(y, r, n), n, sy);
continue;
}
#endif
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N)
vf_storeu(sy + i, vf_mul(vf_silu(vf_loadu(g + i)), vf_loadu(u + i)));
for (; i < n; ++i) {
const float gi = g[i];
sy[i] = (gi / (1.0f + std::exp(-gi))) * u[i];
}
out_row(y, rowoff(y, r, n), n, sy);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gelu / silu / sigmoid
*
* These run over the whole tensor rather than row by row -- libref's `unary` does the same -- so
* the blocking is over a fixed tile that stays in L1 rather than over a row whose length the op
* does not know.
*
* GELU IS THE ONE OP HERE WITH A SCALAR INNER LOOP AND IT IS DELIBERATE. libref computes
* 0.5*x*(1 + erf(x/sqrt2)) with libm's erff, and the kbench tolerance for a `*`/f32 op is 1e-5 --
* which a minimax erf polynomial can meet, and which is not the point: the polynomial would put a
* second definition of gelu in the tree whose agreement with the first is a property of the
* coefficients. The dtype switch is still hoisted, so this is far from libref's speed even
* scalar; if gelu ever appears on a hot path in a model this project serves, the polynomial is
* the obvious next step and --bench gelu is where it would be justified. Qwen and Gemma are silu
* throughout, so today it does not. */
enum { UN_GELU = 0, UN_SILU = 1, UN_SIGMOID = 2 };
template <int WHICH>
static int unary(const RadArgs* a) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
const int64_t nel = numel(y);
if (nel <= 0 || numel(x) < nel) return RAD_E_SHAPE;
/* The strided case falls back to element-at-a-time, as libref does: `offlin` has to be
* evaluated per element there and no amount of vectorisation survives it. */
if (!dense_row(x) || !dense_row(y) || !rad_tensor_is_contiguous(x) ||
!rad_tensor_is_contiguous(y)) {
AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN)
for (int64_t i = 0; i < nel; ++i) {
const float v = ldt(x, offlin(x, i));
float o;
if (WHICH == UN_GELU) o = 0.5f * v * (1.0f + std::erf(v * 0.70710678118654752f));
else if (WHICH == UN_SILU) o = v / (1.0f + std::exp(-v));
else o = 1.0f / (1.0f + std::exp(-v));
stt(y, offlin(y, i), o);
}
return RAD_OK;
}
const int64_t TILE = 4096;
const int64_t ntile = (nel + TILE - 1) / TILE;
AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN)
for (int64_t t = 0; t < ntile; ++t) {
const int64_t off = t * TILE;
const int64_t m = (nel - off) < TILE ? (nel - off) : TILE;
float* s = scratch_f32((size_t)TILE);
float* so = scratch_f32_b((size_t)TILE);
const float* v = in_row(x, off, m, s);
int64_t i = 0;
if (WHICH != UN_GELU) {
for (; i + VF_N <= m; i += VF_N) {
vf u = vf_loadu(v + i);
vf_storeu(so + i, WHICH == UN_SILU ? vf_silu(u) : vf_sigmoid(u));
}
}
for (; i < m; ++i) {
const float u = v[i];
if (WHICH == UN_GELU) so[i] = 0.5f * u * (1.0f + std::erf(u * 0.70710678118654752f));
else if (WHICH == UN_SILU) so[i] = u / (1.0f + std::exp(-u));
else so[i] = 1.0f / (1.0f + std::exp(-u));
}
out_row(y, off, m, so);
}
return RAD_OK;
}
AVX_KERNEL(gelu) { return unary<UN_GELU>(a); }
AVX_KERNEL(silu) { return unary<UN_SILU>(a); }
AVX_KERNEL(sigmoid) { return unary<UN_SIGMOID>(a); }
/* ------------------------------------------------------------------ gather_rows */
/* y[i, :] = x[idx[i], :]. A negative index writes a ZERO ROW -- the padding rule embed_lookup
* follows, and what a step with fewer sampled rows than the buffer's extent leaves behind. An
* index at or past x's row count is RAD_E_INVAL and is checked BEFORE the loop, because an OpenMP
* body cannot return. */
AVX_KERNEL(gather_rows) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *idx = &a->t[1], *y = &a->t[2];
const int64_t n = p_int(a, "n", y->rank >= 1 ? y->shape[y->rank - 1] : 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t M = rows_of(y, n);
const int64_t src_rows = rows_of(x, n);
if (M <= 0 || src_rows <= 0 || numel(idx) < M) return RAD_E_SHAPE;
for (int64_t m = 0; m < M; ++m)
if (ldi(idx, offlin(idx, m)) >= src_rows) return RAD_E_INVAL;
/* A ROW COPY, NOT A CONVERSION, when the dtypes match -- which they always do for a gather.
* memcpy on a whole row beats a widen/narrow round trip by the width of the dtype, and a
* gather that changed the bits of what it moved would be a cast wearing a gather's name. */
const bool same = x->dtype == y->dtype && dense_row(x) && dense_row(y);
const size_t rowb = same ? (size_t)((rad_dtype_bits(x->dtype) * n) / 8) : 0;
AVX_PARALLEL_FOR_IF(M * n >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
const int64_t r = ldi(idx, offlin(idx, m));
const int64_t yb = rowoff(y, m, n), ys = laststride(y);
if (r < 0) {
if (same) std::memset((void*)byte_at(y->data, y->dtype, yb), 0, rowb);
else for (int64_t i = 0; i < n; ++i) stt(y, yb + i * ys, 0.0f);
continue;
}
const int64_t xb = rowoff(x, r, n);
if (same) {
std::memcpy((void*)byte_at(y->data, y->dtype, yb),
byte_at(x->data, x->dtype, xb), rowb);
} else {
float* s = scratch_f32((size_t)n);
out_row(y, yb, n, in_row(x, xb, n, s));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ scatter_rows */
/* x[idx[i], :] = v[i, :], the mirror of gather_rows. `x` is INOUT and the write is PARTIAL: a row
* no index names keeps what it held, and a NEGATIVE index writes nothing, as a negative one reads
* a zero row on the gather side. Indices are distinct by contract (RAD_OPD_F_IDX_UNIQUE), which is
* what lets the rows go to the threads in any order. */
AVX_KERNEL(scatter_rows) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *v = &a->t[0], *idx = &a->t[1], *x = &a->t[2];
const int64_t n = p_int(a, "n", v->rank >= 1 ? v->shape[v->rank - 1] : 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t M = rows_of(v, n);
const int64_t dst_rows = rows_of(x, n);
if (M <= 0 || dst_rows <= 0 || numel(idx) < M) return RAD_E_SHAPE;
for (int64_t m = 0; m < M; ++m)
if (ldi(idx, offlin(idx, m)) >= dst_rows) return RAD_E_INVAL;
/* A row copy when the dtypes match, for gather_rows' reason. */
const bool same = v->dtype == x->dtype && dense_row(v) && dense_row(x);
const size_t rowb = same ? (size_t)((rad_dtype_bits(x->dtype) * n) / 8) : 0;
AVX_PARALLEL_FOR_IF(M * n >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
const int64_t r = ldi(idx, offlin(idx, m));
if (r < 0) continue;
const int64_t vb = rowoff(v, m, n), xb = rowoff(x, r, n);
if (same) {
std::memcpy((void*)byte_at(x->data, x->dtype, xb), byte_at(v->data, v->dtype, vb),
rowb);
} else {
float* s = scratch_f32((size_t)n);
out_row(x, xb, n, in_row(v, vb, n, s));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ cast */
/* The tensors carry their own dtypes and those are what the bytes actually are; `from`/`to` are in
* the schema because the SELECTOR needs them, and a disagreement between the parameter and the
* tensor is a caller bug this cannot diagnose better than the caller can. libref says the same.
*
* Integer pairs go through the INTEGER path, so a token id or a block index above 2^24 survives a
* cast that f32 would round. That is not a tolerance question -- it is the difference between a
* token id and a different token id. */
AVX_KERNEL(cast) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
const int64_t nel = numel(y);
if (nel <= 0 || numel(x) < nel) return RAD_E_SHAPE;
const bool int_pair = (x->dtype == RAD_I32 || x->dtype == RAD_I64 || x->dtype == RAD_U32 ||
x->dtype == RAD_I16) &&
(y->dtype == RAD_I32 || y->dtype == RAD_I64 || y->dtype == RAD_U32 ||
y->dtype == RAD_I16);
if (int_pair || !rad_tensor_is_contiguous(x) || !rad_tensor_is_contiguous(y)) {
AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN)
for (int64_t i = 0; i < nel; ++i) {
if (int_pair) st_int_dt(y->dtype, y->data, offlin(y, i),
ld_int_dt(x->dtype, x->data, offlin(x, i)));
else stt(y, offlin(y, i), ldt(x, offlin(x, i)));
}
return RAD_OK;
}
const int64_t TILE = 8192;
const int64_t ntile = (nel + TILE - 1) / TILE;
AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN)
for (int64_t t = 0; t < ntile; ++t) {
const int64_t off = t * TILE;
const int64_t m = (nel - off) < TILE ? (nel - off) : TILE;
float* s = scratch_f32((size_t)TILE);
out_row(y, off, m, in_row(x, off, m, s));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ softmax */
/* Max-subtracted, f32, over the last n elements of a row. The max subtraction is not an
* optimisation: without it a 60-nat logit range overflows, and every kernel this is checked beside
* does it, so doing it differently would be a difference larger than rounding.
*
* THE ROUND TRIP IS THE CONTRACT. libref writes the exponentials to `y`, reads them back, and
* multiplies by 1/sum -- so a bf16 output carries two roundings. This does the same arithmetic in
* a hot scratch buffer instead of through the output operand: identical result, one pass over
* memory instead of three. */
AVX_KERNEL(softmax) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
const int64_t n = p_int(a, "n", numel(y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(x) < rows * n) return RAD_E_SHAPE;
const size_t tmpb = (size_t)n * 8 + 64;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* s = scratch_f32((size_t)n);
float* e = scratch_f32_b((size_t)n);
void* tp = scratch_raw(tmpb);
const float* v = in_row(x, rowoff(x, r, n), n, s);
const float mx = row_max(v, n);
const vf vmx = vf_set1(mx);
vf acc = vf_zero();
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) {
vf t = vf_exp(vf_sub(vf_loadu(v + i), vmx));
vf_storeu(e + i, t);
acc = vf_add(acc, t);
}
float sum = vf_hsum(acc);
for (; i < n; ++i) { e[i] = std::exp(v[i] - mx); sum += e[i]; }
roundtrip(y->dtype, e, n, tp);
const vf inv = vf_set1(1.0f / sum);
i = 0;
for (; i + VF_N <= n; i += VF_N) vf_storeu(e + i, vf_mul(vf_loadu(e + i), inv));
for (; i < n; ++i) e[i] *= (1.0f / sum);
out_row(y, rowoff(y, r, n), n, e);
}
return RAD_OK;
}
+1349
View File
File diff suppressed because it is too large. Load diff
+718
View File
@@ -0,0 +1,718 @@
/* avx_gemm.cpp -- the GEMM family and the two vocabulary edges.
*
* nt: C[M,N] = A[M,K] @ B[N,K]^T
*
* B is stored TRANSPOSED because that is the layout every weight in a transformer already has, so
* both operands are k-contiguous and the inner loop is a DOT PRODUCT over k rather than an outer
* product over n. That single fact decides the whole shape of this file, and it is worth being
* explicit about what it costs, because the textbook GEMM does the opposite.
*
* ============================== WHY DOT PRODUCT AND NOT OUTER PRODUCT ==============================
*
* The classical high-performance GEMM (Goto's, and every BLAS since) packs B into panels laid out
* so the inner loop broadcasts one A element against a VECTOR of n, accumulating C[m, n0:n0+w] in
* registers with no horizontal reduction anywhere. It is the right shape when you may choose B's
* layout.
*
* Here B's layout is given, it is k-contiguous, and a transformer weight is READ ONCE PER LAUNCH --
* there is no second GEMM against the same weight to amortise a pack over. Packing B into n-major
* panels would mean touching the largest operand twice to save horizontal reductions that only
* happen once per output element. At decode (M = 1) the whole GEMM is a matvec: the weight is
* streamed exactly once, the arithmetic intensity is 2 flops a byte, and nothing about the
* instruction mix matters because the memory system is the wall. At prefill the register blocking
* below recovers most of what a packed form would give.
*
* So: REGISTER-BLOCKED DOT PRODUCT. MR rows of A against NR rows of B, MR*NR vector accumulators
* live across the whole k loop, MR + NR vector loads per k step, and the horizontal reduction paid
* once per output element rather than once per k step.
*
* ============================== THE BLOCK SIZE IS THE REGISTER FILE, AND IT WAS SWEPT ==============================
*
* MEASURED, gemm_nt bf16 at M=512, N=2048, K=2048, one thread, on the part libavx/README.md names:
*
* AVX-512, 32 ZMM 4x4 23.2 ms 4x6 22.1 ms <-- chosen
* 6x4 24.2 ms 6x6 24.0 ms
* 8x4 23.8 ms 8x2 35.2 ms 12x2 34.1 ms
* AVX2/AVX, 16 YMM 3x3 34.4 ms 2x6 30.7 ms <-- chosen
* 2x5 31.9 ms 2x4 34.8 ms 2x3 40.5 ms
* 3x4 58.4 ms 4x3 58.1 ms
*
* TWO THINGS IN THAT TABLE ARE WORTH MORE THAN THE CHOICE. The first is the cliff: 3x4 and 4x3 at
* AVX2 are 58 ms against 31-34 for everything around them, because 12 accumulators plus 3 or 4 A
* vectors plus one B vector is 16 or 17 live in a 16-register file -- the spill lands INSIDE the k
* loop and costs 1.9x. That is why this is written out per level rather than derived from a
* formula, and why the numbers sit next to the code.
*
* The second is that WIDER IN N BEAT WIDER IN M at both levels, at equal arithmetic intensity:
* 2x6 and 3x3 both load 8 vectors for 12 and 9 FMAs respectively -- intensity 1.5 either way -- and
* 2x6 is 11% faster. The B vector is loaded once and reused across the MR inner iterations, so a
* small MR keeps fewer values live and schedules better. Nothing about the flop count predicts
* this; it came out of the sweep.
*
* scalar stays 2x2, where "vector" is one float and the blocking only helps the load/store
* scheduler.
*
* ============================== ONE MICROKERNEL, NOT TWENTY-EIGHT ==============================
*
* libref templates its inner loop on (A dtype, B dtype) and selects through a function pointer,
* because for it the per-element dtype switch WOULD be the cost -- one element is read per FLOP.
* That is 16 instantiations for the plain family and 28 for the quantised one.
*
* This plugin instead PACKS TO f32 and has ONE microkernel:
*
* A is widened once into a contiguous [M, K] f32 buffer -- M*K conversions
* each B row is widened once, per n-block, into a thread-local buffer -- N*K conversions
*
* The conversion count is the same as the fused form's (every element of both operands is
* converted exactly once either way); what it buys is that W4, W2, MXFP4, fp8 and i8 all arrive at
* the same code, so the packed-nibble unpack is written once (avx_support.cpp) and the microkernel
* never sees a dtype. 28 instantiations x 4 ISA levels of hand-written vector code is not a
* maintainable object, and the ones nobody runs would be the ones that are wrong.
*
* What it costs is an L1 round trip: the packed rows are written and read back. Against an operand
* that came from L2 or DRAM -- which a weight always did -- that is not measurable, and the
* exception is stated where it happens (an f32 contiguous A is used in place, unpacked).
*
* THE MEMORY THIS COSTS IS BOUNDED BY THE M BLOCK below -- the pack is MB*K floats, not M*K -- and
* it is not blocked over K. That is a deliberate omission: K-blocking would bound the pack further
* but would force the C accumulator into memory, because the k reduction could then no longer live
* in registers across the whole launch. C is M*N floats, larger than the pack at every shape this
* plugin sees, and another pass over it.
*
* ============================== PARALLELISM IS OVER N ==============================
*
* A decode step is M = 1 and a verify step is M <= 64, so an M-major split leaves all but one core
* idle on exactly the shape the engine spends its life in. N is thousands in every GEMM a
* transformer issues. libref made the same choice for the same reason. Each thread owns whole
* output elements, so the summation order does not depend on the thread count and two runs at
* different loads are bit-identical.
*/
#include "avx_vec.h"
#include "avx_common.h"
#include "avx_rows.h"
#include <vector>
using namespace avx;
#include "avx_had.h"
/* ================================================================== register blocking */
#if AVX_LEVEL == 3
constexpr int64_t MR = 4, NR = 6;
#elif AVX_LEVEL == 2 || AVX_LEVEL == 1
constexpr int64_t MR = 2, NR = 6;
#else
constexpr int64_t MR = 2, NR = 2;
#endif
/* MR x NR dot products over [k0, k1), accumulated into `out` (which is ADDED to, not overwritten,
* so the grouped GEMM can call this per group).
*
* The tail is summed separately and added to the horizontal reduction rather than folded into a
* masked vector: the two give different orders and the masked form is only free at AVX-512. One
* order, four levels. */
template <int MB_, int NB_>
static inline void dot_block(const float* A, int64_t lda, const float* B, int64_t ldb,
int64_t k0, int64_t k1, float out[MB_][NB_]) {
vf acc[MB_][NB_];
for (int i = 0; i < MB_; ++i)
for (int j = 0; j < NB_; ++j) acc[i][j] = vf_zero();
int64_t k = k0;
for (; k + VF_N <= k1; k += VF_N) {
vf av[MB_];
for (int i = 0; i < MB_; ++i) av[i] = vf_loadu(A + i * lda + k);
for (int j = 0; j < NB_; ++j) {
const vf bv = vf_loadu(B + j * ldb + k);
for (int i = 0; i < MB_; ++i) acc[i][j] = vf_fma(av[i], bv, acc[i][j]);
}
}
for (int i = 0; i < MB_; ++i)
for (int j = 0; j < NB_; ++j) {
float s = vf_hsum(acc[i][j]);
for (int64_t t = k; t < k1; ++t) s += A[i * lda + t] * B[j * ldb + t];
out[i][j] += s;
}
}
/* One dot product, for the ragged edge of the M and N loops. Four accumulators, which is what
* covers the FMA latency; the edge is at most MR-1 by NR-1 blocks of a launch, so its cost is
* noise, but writing it as a scalar loop would make a narrow GEMM (N < NR) run scalar throughout
* and a draft head's lm_head is exactly that shape. */
static inline float dot1(const float* a, const float* b, int64_t k0, int64_t k1) {
vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero();
int64_t k = k0;
for (; k + 4 * VF_N <= k1; k += 4 * VF_N) {
a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0);
a1 = vf_fma(vf_loadu(a + k + VF_N), vf_loadu(b + k + VF_N), a1);
a2 = vf_fma(vf_loadu(a + k + 2 * VF_N), vf_loadu(b + k + 2 * VF_N), a2);
a3 = vf_fma(vf_loadu(a + k + 3 * VF_N), vf_loadu(b + k + 3 * VF_N), a3);
}
for (; k + VF_N <= k1; k += VF_N) a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0);
float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3)));
for (; k < k1; ++k) s += a[k] * b[k];
return s;
}
/* ================================================================== operand readings
* libref/ref_gemm.h's, and they are copied for the same reason avx_common.h copies the addressing
* helpers: they are the CONTRACT for which bytes an operand's (row, col) lives at, not a
* convenience. `row_stride` (avx_common.h) in particular is the one that makes an oracle wrong
* when it is wrong -- a rank-3 [tokens, heads, width] activation read as [tokens, heads*width] has
* a row stride that is the product of the trailing dimensions and NOT stride[rank-2], and taking
* the head stride instead lands row 0 correctly and starts every row after it `width` elements
* in. */
struct Mat { const RadTensor* t; int64_t rs, cs; };
static inline Mat as_mat(const RadTensor* t, int64_t cols) {
Mat m{ t, cols, 1 };
if (t->rank < 2) return m;
m.cs = t->stride[t->rank - 1];
m.rs = row_stride(t, cols);
return m;
}
/* A quantised operand's scale stream. libref/ref_gemm.h is the definition, including the `rblk`
* rule that makes a DeepSeek-style [ceil(N/128)][ceil(K/128)] block grid readable: without it a
* 17408-row weight's 136-row scale plane is read as if it had 17408 rows and lands on groups = 0,
* which is a plausible wrong number rather than a diagnosable failure. */
struct Scales {
const void* p;
uint32_t dt;
int64_t rs, cs, group, rblk;
bool e8m0;
inline float grp(int64_t row, int64_t g) const {
const int64_t i = (rblk > 1 ? row / rblk : row) * rs + g * cs;
if (e8m0) {
const uint8_t e = ((const uint8_t*)p)[i];
return e == 0xff ? std::nanf("") : std::ldexp(1.0f, (int)e - 127);
}
return rad_load_f32(p, dt, i);
}
};
static Scales make_scales(const RadTensor* s, int64_t rows, int64_t K, bool mxfp4_weight) {
Scales q{};
q.rblk = 1;
if (!s || !s->data || rows <= 0 || numel(s) <= 0) {
q.p = nullptr; q.group = K; q.dt = RAD_F32; return q;
}
q.p = s->data;
q.dt = s->dtype;
/* libref's reading, block for block: a rank-2 stream with fewer rows than the operand is a
* block grid whatever the remainder, and a flat stream shorter than the row count is one
* scale per block of rows rather than a per-row stream to read past its end. */
int64_t groups = 0;
if (s->rank >= 2) {
const int64_t srows = s->shape[s->rank - 2];
q.rblk = srows >= rows ? 1 : grid_block(rows, srows);
groups = s->shape[s->rank - 1];
q.rs = s->stride[s->rank - 2];
q.cs = s->stride[s->rank - 1];
} else {
const int64_t nel = numel(s);
if (nel >= rows) { groups = nel / rows; q.rs = groups; }
else { groups = 1; q.rblk = grid_block(rows, nel); q.rs = 1; }
q.cs = 1;
}
q.group = grid_block(K, groups);
q.e8m0 = mxfp4_weight && (s->dtype == RAD_U8);
return q;
}
/* ================================================================== packing
* A row of an operand, widened into f32 and made contiguous. Returns the caller's own pointer when
* the operand is ALREADY dense f32 -- the one case where the pack is skipped entirely, and the
* reason a f32 GEMM does not pay for the generality. */
static const float* pack_rows(const Mat& m, int64_t r0, int64_t nrows, int64_t K, float* dst,
int64_t ldd) {
const RadTensor* t = m.t;
if (m.cs == 1 && t->dtype == RAD_F32 && m.rs == ldd)
return (const float*)t->data + r0 * m.rs;
for (int64_t r = 0; r < nrows; ++r) {
const int64_t base = (r0 + r) * m.rs;
if (m.cs == 1) {
const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1
: (t->dtype == RAD_I2) ? 3 : 0;
if (!sub || (base & sub) == 0) {
row_to_f32(t->dtype, byte_at(t->data, t->dtype, base), dst + r * ldd, K);
continue;
}
}
for (int64_t k = 0; k < K; ++k)
dst[r * ldd + k] = ld_elem(t->data, t->dtype, base + k * m.cs);
}
return dst;
}
/* ================================================================== the driver
*
* `SB`/`SA` null means the unquantised family, which is the same loop with one group of width K
* and both scales 1 -- so there is one driver and not two. The grouped form accumulates the
* sub-sum from the RAW CODES and scales once at the end of the group, which is what an int8 WMMA
* kernel does and what libref does; folding the scales into every product instead would be a
* different number in the last bits and the checker would blame the kernel for the choice. */
static int gemm_drive(const Mat& ma, const Mat& mb, const Scales* SA, const Scales* SB,
const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N,
int64_t K) {
const int64_t ys_r = row_stride(Y, N);
const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
const int64_t g = (SB && SB->p && SB->group > 0) ? SB->group : K;
const int64_t ngrp = (K + g - 1) / g;
/* An activation grid FINER than the weight's cannot have its scale hoisted out of the group.
* No format in this project has one; the branch exists so that a format that did would be
* refused rather than silently mis-scaled. */
const bool coarse_a = !SA || !SA->p || SA->group >= g;
if (!coarse_a) return RAD_E_UNSUPPORTED;
/* ================================================== THE M BLOCK, AND A NULL RESULT
*
* The loop nest below is (M block) x (N block) x (K). With the N loop outermost and the whole
* of A packed, every one of the N/NR n-blocks walks the ENTIRE packed A, so at M=512, K=2048
* that is a 4 MiB panel re-read 341 times: 1.4 GiB of traffic to do 4.3 GFLOP. Blocking M so
* the panel stays resident is the textbook fix, and the traffic argument predicts a large win.
*
* MEASURED, AND THE PREDICTION DOES NOT HOLD HERE. gemm_nt bf16 at M=512, N=2048, K=2048,
* AVX-512, one thread, sweeping the panel target:
*
* 128 KiB 26.0 ms 4 MiB 25.4 ms
* 256 KiB 23.4 ms 16 MiB 25.4 ms
* 1 MiB 24.0 ms 256 MiB 25.0 ms (= no blocking at this shape)
*
* Six percent, not the several-fold the traffic argument implies -- and at M=64 it is WORSE
* (2.85 ms unblocked against 2.91 at 256 KiB), because there the block splits a batch that did
* not need splitting and B gets packed twice.
*
* THE REASON IS THE PART. The measurement above comes from one with 128 MiB of L3, where the
* 4 MiB A panel never leaves cache however many times it is walked -- so the traffic the
* blocking removes is served at L3 bandwidth and not DRAM's. On a part with a 32 MiB L3
* the same argument still holds; on one with 8 MiB the blocking is the several-fold win the
* theory predicts. It is kept because it is never much worse and is much better on hardware
* the measurement above cannot represent -- but it is recorded here as a SIX PERCENT effect on
* a large-cache part, and not as the fix it looks like.
*
* THE BLOCK SIZE IS COMPUTED FROM K, NOT TUNED: the panel is MB x K floats against a fixed
* byte target. There is nothing to search -- unlike a GPU tile it does not interact with an
* occupancy limit -- which is why avx_registry.cpp declares no tunable axes. The target is
* stated rather than probed from CPUID because the cache descriptors there are a fiction on
* more parts than they are a fact, and the sweep above shows the curve is flat enough that
* being wrong about it costs ten percent rather than an order. */
enum { AVX_L2_PANEL = 256 * 1024 };
int64_t MB = (int64_t)AVX_L2_PANEL / ((int64_t)K * (int64_t)sizeof(float));
if (MB < MR) MB = MR;
if (MB > M) MB = M;
const int64_t lda = K;
float* apack = (float*)scratch_raw((size_t)MB * (size_t)K * sizeof(float) + 64);
const int64_t nblocks = (N + NR - 1) / NR;
for (int64_t mb0 = 0; mb0 < M; mb0 += MB) {
const int64_t mrows = (M - mb0) < MB ? (M - mb0) : MB;
/* Packed on the calling thread, before the parallel region: every worker reads it, and
* nothing inside the region touches this arena, so the pointer cannot move under them. */
const float* Ap = pack_rows(ma, mb0, mrows, K, apack, lda);
AVX_PARALLEL_FOR_IF(mrows * N * K >= 65536)
for (int64_t nb = 0; nb < nblocks; ++nb) {
const int64_t n0 = nb * NR;
const int64_t nn = (N - n0) < NR ? (N - n0) : NR;
const int64_t ldb = K;
float* bbuf = scratch_f32((size_t)NR * (size_t)K);
const float* Bp = pack_rows(mb, n0, nn, K, bbuf, ldb);
for (int64_t m0 = 0; m0 < mrows; m0 += MR) {
const int64_t mm = (mrows - m0) < MR ? (mrows - m0) : MR;
float acc[MR][NR];
for (int i = 0; i < MR; ++i)
for (int j = 0; j < NR; ++j) acc[i][j] = 0.0f;
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < K) ? k0 + g : K;
if (mm == MR && nn == NR) {
float sub[MR][NR];
for (int i = 0; i < MR; ++i)
for (int j = 0; j < NR; ++j) sub[i][j] = 0.0f;
dot_block<MR, NR>(Ap + m0 * lda, lda, Bp, ldb, k0, k1, sub);
for (int j = 0; j < NR; ++j) {
const float sb = (SB && SB->p) ? SB->grp(n0 + j, gi) : 1.0f;
for (int i = 0; i < MR; ++i) {
const float sa = (SA && SA->p)
? SA->grp(mb0 + m0 + i, k0 / SA->group) : 1.0f;
acc[i][j] += sub[i][j] * sa * sb;
}
}
} else {
for (int64_t j = 0; j < nn; ++j) {
const float sb = (SB && SB->p) ? SB->grp(n0 + j, gi) : 1.0f;
for (int64_t i = 0; i < mm; ++i) {
const float sa = (SA && SA->p)
? SA->grp(mb0 + m0 + i, k0 / SA->group) : 1.0f;
acc[i][j] +=
dot1(Ap + (m0 + i) * lda, Bp + j * ldb, k0, k1) * sa * sb;
}
}
}
}
for (int64_t i = 0; i < mm; ++i)
for (int64_t j = 0; j < nn; ++j) {
float v = acc[i][j];
if (bias) v += ldt(bias, (n0 + j) * laststride(bias));
stt(Y, (mb0 + m0 + i) * ys_r + (n0 + j) * ys_c, v);
}
}
}
}
return RAD_OK;
}
/* Shared entry for gemm_nt / gemm_nt_bias / logits_gemm. `nkey`/`kkey` name which parameters carry
* N and K, because logits_gemm spells them n_vocab and n_embd. */
/* gemm_nt_bias's epilogue (docs/OPS.md): an activation of the stored product, then a residual,
* each step read back from and stored to the output's dtype -- the unfused chain, as libref has it. */
static void gemm_epilogue(const RadTensor* Y, const RadTensor* res, int act, int64_t M, int64_t N) {
const int64_t ys = laststride(Y), yr = Y->rank >= 2 ? Y->stride[Y->rank - 2] : N;
const int64_t rs = res ? laststride(res) : 0, rr = res && res->rank >= 2 ? res->stride[res->rank - 2] : N;
AVX_PARALLEL_FOR_IF(M * N >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m)
for (int64_t n = 0; n < N; ++n) {
const int64_t o = m * yr + n * ys;
float v = ldt(Y, o);
if (act == 1) { v = 0.5f * v * (1.0f + std::erf(v * 0.70710678118654752f)); stt(Y, o, v); }
else if (act == 2) {
v = 0.5f * v * (1.0f + std::tanh(0.7978845608028654f * (v + 0.044715f * v * v * v)));
stt(Y, o, v);
}
if (res) stt(Y, o, ldt(res, m * rr + n * rs) + ldt(Y, o));
}
}
static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, const char* kkey) {
/* gemm_nt_bias is a, b, bias, res?, y; the other two are a, b, y. */
const int nt = bias_operand ? 5 : 3;
if (a->n_t < nt || !a->t[0].data || !a->t[1].data || !a->t[nt - 1].data) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[nt - 1];
const RadTensor* bias = bias_operand ? rad_arg_in(a, 2) : nullptr;
const RadTensor* res = bias_operand ? rad_arg_in(a, 3) : nullptr;
static const char* kActs[] = { "none", "gelu", "gelu_tanh" };
const int act = bias_operand ? p_enum(a, "act", kActs, 3, 0) : 0;
const int64_t K = p_int(a, kkey, B->rank >= 2 ? B->shape[B->rank - 1] : 0);
const int64_t N = p_int(a, nkey, B->rank >= 2 ? B->shape[B->rank - 2] : 0);
if (K <= 0 || N <= 0) return RAD_E_SHAPE;
const int64_t M = numel(Y) / N;
if (M <= 0) return RAD_E_SHAPE;
if (numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE;
if (bias && numel(bias) < N) return RAD_E_SHAPE;
if (res && numel(res) < M * N) return RAD_E_SHAPE;
const Mat ma = as_mat(A, K), mb = as_mat(B, K);
const int st = gemm_drive(ma, mb, nullptr, nullptr, Y, bias, M, N, K);
if (st < 0) return st;
if (act || res) gemm_epilogue(Y, res, act, M, N);
return RAD_OK;
}
static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) {
const int nt = bias_operand ? 6 : 5;
if (a->n_t < nt || !a->t[0].data || !a->t[2].data || !a->t[nt - 1].data) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[2], *Y = &a->t[nt - 1];
const RadTensor* as_ = rad_arg_in(a, 1);
const RadTensor* bs_ = rad_arg_in(a, 3);
const RadTensor* bias = bias_operand ? rad_arg_in(a, 4) : nullptr;
const int64_t K = p_int(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0);
const int64_t N = p_int(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0);
if (K <= 0 || N <= 0) return RAD_E_SHAPE;
const int64_t M = numel(Y) / N;
if (M <= 0) return RAD_E_SHAPE;
if (numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE;
if (bias && numel(bias) < N) return RAD_E_SHAPE;
const bool mx = B->dtype == RAD_FP4E2M1;
Scales SA = make_scales(as_, M, K, false);
Scales SB = make_scales(bs_, N, K, mx);
/* `group` is what the SELECTOR matches on; the loop uses the group the scale stream actually
* implies. They agree in every well-formed call, and where they do not the stream is the one
* that describes the bytes -- so a disagreement is refused rather than silently resolved. */
const int64_t gp = p_int(a, "group", 0);
if (gp > 0 && SB.p && SB.group != gp) return RAD_E_SHAPE;
const Mat ma = as_mat(A, K), mb = as_mat(B, K);
return gemm_drive(ma, mb, &SA, &SB, Y, bias, M, N, K);
}
AVX_KERNEL(gemm_nt) { return gemm_nt_impl(a, false, "N", "K"); }
AVX_KERNEL(gemm_nt_bias) { return gemm_nt_impl(a, true, "N", "K"); }
AVX_KERNEL(gemm_nt_q) { return gemm_ntq_impl(a, false); }
AVX_KERNEL(gemm_nt_q_bias) { return gemm_ntq_impl(a, true); }
/* ------------------------------------------------------------------ gemm_nt_q_gated */
/* gemm_nt_q over a [N, K] gate_up plane -- N is the WEIGHT's rows, twice the fused width, gate half
* first -- with gated_quant_fp8 as the epilogue; the output is [M, N/2].
*
* BYTE-IDENTICAL TO THE PAIR IT STANDS FOR, gemm_nt_q into a bf16 [M, N] tensor and then
* gated_quant_fp8 over it. The product is gemm_drive's, the same driver at the same blocking; both
* halves are narrowed to bf16 by the ABI's own converter, which is what gemm_nt_q's element store
* does to a bf16 output; and the gate and the codes are avx_had.h's, which gated_quant_fp8 runs.
* Taking either half off the f32 accumulator instead would be a different function.
*
* The f32 plane between the two is materialised whole, in a buffer the calling thread keeps: the
* driver parallelises over the plane's columns, and the epilogue over its rows. `act` is REQUIRED
* here where the quantiser defaults it -- an implementation may compile one gate, and a default
* would let it resolve for the other. */
AVX_KERNEL(gemm_nt_q_gated) {
if (a->n_t < 6) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[2], *q = &a->t[4], *s = &a->t[5];
const RadTensor* as_ = rad_arg_in(a, 1);
const RadTensor* bs_ = rad_arg_in(a, 3);
const RadTensor* ob = rad_arg_in(a, 6);
if (!A->data || !B->data || !q->data || !s->data) return RAD_E_INVAL;
const int64_t K = p_int(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0);
const int64_t N = p_int(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0);
if (K <= 0 || N <= 0 || (N & 1)) return RAD_E_SHAPE;
const int64_t n = N / 2;
static const char* kActs[] = { "silu", "sigmoid" };
const int act = p_enum(a, "act", kActs, 2, -1);
if (act != 0 && act != 1) return RAD_E_INVAL;
int64_t g = p_int(a, "group", 0);
if (g <= 0 || g > n) g = n;
const int64_t ngrp = (n + g - 1) / g;
const int64_t M = numel(q) / n;
if (M <= 0 || numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE;
if (numel(s) < M * ngrp) return RAD_E_SHAPE;
if (ob && numel(ob) < M * n) return RAD_E_SHAPE;
const bool mx = B->dtype == RAD_FP4E2M1;
const Scales SA = make_scales(as_, M, K, false);
const Scales SB = make_scales(bs_, N, K, mx);
const Mat ma = as_mat(A, K), mb = as_mat(B, K);
static thread_local std::vector<float> plane;
if (plane.size() < (size_t)(M * N)) plane.resize((size_t)(M * N));
RadTensor Y{};
Y.data = plane.data();
Y.dtype = RAD_F32;
Y.rank = 2;
Y.shape[0] = M; Y.shape[1] = N;
Y.stride[0] = N; Y.stride[1] = 1;
const int rc = gemm_drive(ma, mb, &SA, &SB, &Y, nullptr, M, N, K);
if (rc != RAD_OK) return rc;
const float* P = plane.data();
AVX_PARALLEL_FOR_IF(M * N >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
float* row = scratch_f32((size_t)N);
float* out = scratch_f32_b((size_t)n);
float* tmp = scratch_f32_c((size_t)n);
for (int64_t j = 0; j < N; ++j) row[j] = rad_bf16_to_f32(rad_f32_to_bf16(P[m * N + j]));
gate_bf16(row, row + n, out, n, act, tmp);
fp8_emit(out, tmp, n, g, q, s, ob, m);
}
return RAD_OK;
}
/* The same arithmetic as gemm_nt, and a separate op anyway: lm_head is its own access class
* (RAD_ACCESS_VOCAB) and the sampler wants to fuse against it, so the two have to be selectable
* apart even when one kernel serves both. N and K are spelled n_vocab and n_embd. */
AVX_KERNEL(logits_gemm) { return gemm_nt_impl(a, false, "n_vocab", "n_embd"); }
/* ================================================================== the vocabulary edges
*
* A gather, not a GEMM. A NEGATIVE token id writes a ZERO ROW -- the padding convention a batch
* with a short sequence needs. `vocab_offset` makes the table this rank's slice of a vocab-parallel
* embedding: ids stay GLOBAL, one outside the slice writes a zero row, and summing the ranks
* reconstructs x.
*
* WITHOUT AN OFFSET AN ID AT OR ABOVE n_vocab STILL FAILS THE LAUNCH, because there it is a caller
* bug rather than another rank's token and a plausible embedding is the worst possible answer.
* With one, this kernel cannot know the global vocabulary, so the bound is the caller's. */
template <bool QUANT>
static int embed_impl(const RadArgs* a) {
const int nt = QUANT ? 4 : 3;
/* embed_lookup_q's scale (operand 2) is optional; everything else must be there. */
for (int i = 0; i < nt; ++i)
if (!(QUANT && i == 2) && !rad_arg_in(a, i)) return RAD_E_INVAL;
const RadTensor* tok = &a->t[0];
const RadTensor* wte = &a->t[1];
const RadTensor* sc = QUANT ? &a->t[2] : nullptr;
const RadTensor* x = &a->t[nt - 1];
const int64_t n_embd = p_int(a, "n_embd", wte->rank >= 2 ? wte->shape[wte->rank - 1] : 0);
const int64_t n_vocab = p_int(a, "n_vocab", wte->rank >= 2 ? wte->shape[wte->rank - 2] : 0);
const int64_t voff = p_int(a, "vocab_offset", 0);
if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return RAD_E_SHAPE;
const int64_t M = numel(x) / n_embd;
if (M <= 0 || numel(tok) < M || numel(wte) < n_vocab * n_embd) return RAD_E_SHAPE;
/* An absent scale is one (ref_embed_lookup_q says why the op allows it). */
const float scale = QUANT && sc->data && numel(sc) >= 1 ? ldt(sc, 0) : 1.0f;
/* Validated before the loop, because an OpenMP body cannot return. */
if (voff == 0)
for (int64_t m = 0; m < M; ++m)
if (ldi(tok, offlin(tok, m)) >= n_vocab) return RAD_E_INVAL;
const int64_t ws = wte->rank >= 2 ? wte->stride[wte->rank - 2] : n_embd;
const int64_t wc = wte->rank >= 2 ? wte->stride[wte->rank - 1] : 1;
/* A ROW COPY WHEN NOTHING HAS TO CHANGE, which for the unquantised gather is the usual case:
* the table and the activation are the same dtype and a memcpy moves the row at the width of
* the machine instead of through an f32 round trip that would also re-round it. */
const bool copy = !QUANT && wte->dtype == x->dtype && wc == 1 && laststride(x) == 1;
const size_t rowb = copy ? (size_t)((rad_dtype_bits(x->dtype) * n_embd) / 8) : 0;
AVX_PARALLEL_FOR_IF(M * n_embd >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
const int64_t id = ldi(tok, offlin(tok, m)) - voff;
const int64_t xb = rowoff(x, m, n_embd), xs = laststride(x);
const bool have_row = id >= 0 && id < n_vocab;
if (copy) {
void* dst = (void*)byte_at(x->data, x->dtype, xb);
if (have_row) std::memcpy(dst, byte_at(wte->data, wte->dtype, id * ws), rowb);
else std::memset(dst, 0, rowb);
continue;
}
float* s = scratch_f32((size_t)n_embd);
if (!have_row) {
for (int64_t i = 0; i < n_embd; ++i) s[i] = 0.0f;
} else if (wc == 1) {
row_to_f32(wte->dtype, byte_at(wte->data, wte->dtype, id * ws), s, n_embd);
if (QUANT) {
const vf vs = vf_set1(scale);
int64_t i = 0;
for (; i + VF_N <= n_embd; i += VF_N) vf_storeu(s + i, vf_mul(vf_loadu(s + i), vs));
for (; i < n_embd; ++i) s[i] *= scale;
}
} else {
for (int64_t i = 0; i < n_embd; ++i)
s[i] = ld_elem(wte->data, wte->dtype, id * ws + i * wc) * scale;
}
if (xs == 1) out_row(x, xb, n_embd, s);
else for (int64_t i = 0; i < n_embd; ++i) stt(x, xb + i * xs, s[i]);
}
return RAD_OK;
}
AVX_KERNEL(embed_lookup) { return embed_impl<false>(a); }
/* ================================================================== the E4M3 table into bf16
*
* The form a model serves -- an E4M3 table, a bf16 activation -- is a gather whose rows are usually
* not in memory, and avx_ngram.cpp is where they come from: a row cache shared by every thread, a
* direct read for each miss, a reader a step ahead. What stays here is the part that is this
* level's: turning a row of codes into bf16 through the call's 256-entry table.
*
* AT AVX-512 THE TABLE LIVES IN EIGHT REGISTERS. 256 bf16 are 512 bytes; vpermt2w indexes 64 words
* across a register pair, so four of them look every code up in its quarter and the code's top two
* bits pick the quarter -- a dozen instructions for 32 codes, against 32 dependent loads. Below
* AVX-512 the table has no in-register form (vpshufb indexes 16 bytes and a gather issues one load
* a lane, the null result in README.md), so those levels look a code up at a time.
*
* EVERY ROW IS A CACHE MISS, so each row's lines are requested kAhead rows before its decode:
* a batch is thousands of rows scattered over the row cache, and a decode that waited for each
* row's lines in turn would spend its time on the memory latency rather than the lookups. */
static void decode_e4m3_rows(const uint8_t* const* src, uint16_t* const* dst, int64_t count,
int64_t n, const uint16_t* lut) {
constexpr int64_t kAhead = 8;
#if AVX_LEVEL >= 3
__m512i t[8];
for (int k = 0; k < 8; ++k) t[k] = _mm512_loadu_si512((const void*)(lut + 32 * k));
const __m512i bit6 = _mm512_set1_epi16(0x40), bit7 = _mm512_set1_epi16(0x80);
auto pick = [&](__m512i ix) {
const __m512i q0 = _mm512_permutex2var_epi16(t[0], ix, t[1]);
const __m512i q1 = _mm512_permutex2var_epi16(t[2], ix, t[3]);
const __m512i q2 = _mm512_permutex2var_epi16(t[4], ix, t[5]);
const __m512i q3 = _mm512_permutex2var_epi16(t[6], ix, t[7]);
const __mmask32 h6 = _mm512_test_epi16_mask(ix, bit6);
const __mmask32 h7 = _mm512_test_epi16_mask(ix, bit7);
return _mm512_mask_blend_epi16(h7, _mm512_mask_blend_epi16(h6, q0, q1),
_mm512_mask_blend_epi16(h6, q2, q3));
};
#endif
for (int64_t r = 0; r < count; ++r) {
if (r + kAhead < count) {
const uintptr_t p = (uintptr_t)src[r + kAhead];
for (uintptr_t q = p & ~(uintptr_t)63; q < p + (uintptr_t)n; q += 64)
__builtin_prefetch((const void*)q);
}
const uint8_t* s = src[r];
uint16_t* d = dst[r];
#if AVX_LEVEL >= 3
int64_t i = 0;
for (; i + 32 <= n; i += 32) {
const __m512i ix = _mm512_cvtepu8_epi16(_mm256_loadu_si256((const __m256i*)(s + i)));
_mm512_storeu_si512((void*)(d + i), pick(ix));
}
if (i < n) {
const __mmask32 k = (__mmask32)((1u << (n - i)) - 1u);
const __m512i ix = _mm512_cvtepu8_epi16(_mm256_maskz_loadu_epi8(k, s + i));
_mm512_mask_storeu_epi16((void*)(d + i), k, pick(ix));
}
#else
for (int64_t i = 0; i < n; ++i) d[i] = lut[s[i]];
#endif
}
}
/* A bf16 table's rows ARE their output: the decode is a copy, and the row cache in front of it is
* the whole of the work, as it is for the E4M3 table. */
static void decode_bf16_rows(const uint8_t* const* src, uint16_t* const* dst, int64_t count,
int64_t n, const uint16_t*) {
for (int64_t r = 0; r < count; ++r) std::memcpy(dst[r], src[r], (size_t)n * sizeof(uint16_t));
}
/* The call in avx_ngram.cpp's form, or false: i32 ids, a dense E4M3 table with its scale or a
* dense bf16 table without one, bf16 rows at one pitch. */
static bool rows_form(const RadArgs* a, RowGather* g) {
/* The scale is optional, so it is not part of what must be present. */
if (!rad_arg_in(a, 0) || !rad_arg_in(a, 1) || !rad_arg_in(a, 3)) return false;
const RadTensor* tok = &a->t[0];
const RadTensor* wte = &a->t[1];
const RadTensor* sc = &a->t[2];
const RadTensor* x = &a->t[3];
if (tok->dtype != RAD_I32 || !rad_tensor_is_contiguous(tok)) return false;
if (!rad_tensor_is_contiguous(wte)) return false;
const bool e4m3 = wte->dtype == RAD_F8E4M3;
if (!e4m3 && wte->dtype != RAD_BF16) return false;
const bool scaled = sc->data && numel(sc) >= 1;
if (x->dtype != RAD_BF16 || scaled != e4m3) return false;
const int64_t n_embd = p_int(a, "n_embd", wte->rank >= 2 ? wte->shape[wte->rank - 1] : 0);
const int64_t n_vocab = p_int(a, "n_vocab", wte->rank >= 2 ? wte->shape[wte->rank - 2] : 0);
if (n_embd <= 0 || n_vocab <= 0) return false;
int64_t ld = -1;
if (rad_tensor_is_contiguous(x)) ld = n_embd;
else if (x->rank == 2 && x->shape[1] == n_embd && x->stride[1] == 1) ld = x->stride[0];
if (ld < n_embd) return false;
g->ids = (const int32_t*)tok->data;
g->M = numel(x) / n_embd;
g->tab = (const uint8_t*)wte->data;
g->n_vocab = n_vocab;
g->n_embd = n_embd;
g->voff = p_int(a, "vocab_offset", 0);
g->scale = e4m3 ? ldt(sc, 0) : 1.0f;
g->row_bytes = e4m3 ? n_embd : 2 * n_embd;
g->out = (uint16_t*)x->data;
g->x_ld = ld;
const RadTensor* ahd = rad_arg_in(a, 4);
const bool ahead = ahd && ahd->dtype == RAD_I32 && rad_tensor_is_contiguous(ahd) && numel(ahd);
g->ahead = ahead ? (const int32_t*)ahd->data : nullptr;
g->n_ahead = ahead ? numel(ahd) : 0;
g->rank = a->rank;
g->world_size = a->world_size;
return true;
}
AVX_KERNEL(embed_lookup_q) {
RowGather g;
if (!rows_form(a, &g)) return embed_impl<true>(a);
if (g.voff < 0 || g.M <= 0 || numel(&a->t[0]) < g.M || numel(&a->t[1]) < g.n_vocab * g.n_embd)
return RAD_E_SHAPE;
/* Checked before the gather, not inside it: a refusal halfway through would leave the output
* half written and the step would carry on over it. The bound is embed_impl's -- with an offset
* an id outside this rank's slice is another rank's row and writes a zero one. */
if (g.voff == 0)
for (int64_t m = 0; m < g.M; ++m)
if ((int64_t)g.ids[m] >= g.n_vocab) return RAD_E_INVAL;
return row_gather(g, g.row_bytes == g.n_embd ? decode_e4m3_rows : decode_bf16_rows);
}
+149
View File
@@ -0,0 +1,149 @@
/* avx_had.h -- the Hadamard rotation, the fp8 group quantiser and the epilogue the fp8 fusions
* share, for the kernels that emit a rotated or block-scaled fp8 row: had_quant_act_fp8, the fused
* quantisers (avx_quant.cpp), gemm_nt_q_gated (avx_gemm.cpp) and hc_read's rotated twin
* (avx_hc.cpp). Compiled per level with the file that includes it; include it after avx_vec.h and
* avx_common.h, with `using namespace avx` in effect. */
#ifndef RAD_AVX_HAD_H
#define RAD_AVX_HAD_H
static inline bool pow2(int64_t v) { return v > 0 && (v & (v - 1)) == 0; }
/* The widest rotation this plugin performs. libr4d caps `had` at 512 -- a power of two dividing
* the per-rank K, and 8704 admits no more -- so 4096 is four doublings of headroom, and it is
* libref's cap too so the two agree about what they refuse. A wider request returns
* RAD_E_UNSUPPORTED BY NAME rather than silently rotating a narrower block: a half-applied
* rotation is numerically plausible and completely wrong. */
enum { AVX_HAD_MAX = 4096 };
/* ================================================================== the butterfly
* One stride of the transform over a g-element block. `h` is the stride; the caller runs it
* ascending from 1. */
#if AVX_LEVEL >= 1
/* The partner of each lane under a swap at stride `h`, for h < VF_N, and the mask of lanes that
* take the SUM (the ones with (i & h) == 0; the others take partner - self, which is the
* subtraction with the operands the right way round). */
static inline void fwht_small(float* v, int64_t g, int64_t h) {
for (int64_t b = 0; b < g; b += VF_N) {
vf x = vf_loadu(v + b);
vf p;
#if AVX_LEVEL == 3
__mmask16 m;
switch (h) {
case 1: p = _mm512_permute_ps(x, 0xB1); m = 0x5555; break;
case 2: p = _mm512_permute_ps(x, 0x4E); m = 0x3333; break;
case 4: p = _mm512_shuffle_f32x4(x, x, 0xB1); m = 0x0F0F; break;
default:p = _mm512_shuffle_f32x4(x, x, 0x4E); m = 0x00FF; break; /* h == 8 */
}
/* sum where (i & h) == 0, partner - self elsewhere. One blend, no branch per lane. */
vf_storeu(v + b, _mm512_mask_blend_ps(m, _mm512_sub_ps(p, x), _mm512_add_ps(x, p)));
#else
switch (h) {
case 1: p = _mm256_permute_ps(x, 0xB1); break;
case 2: p = _mm256_permute_ps(x, 0x4E); break;
default: p = _mm256_permute2f128_ps(x, x, 0x01); break; /* h == 4 */
}
const __m256 sum = _mm256_add_ps(x, p), dif = _mm256_sub_ps(p, x);
__m256 r;
switch (h) {
case 1: r = _mm256_blend_ps(dif, sum, 0x55); break;
case 2: r = _mm256_blend_ps(dif, sum, 0x33); break;
default: r = _mm256_blend_ps(dif, sum, 0x0F); break;
}
vf_storeu(v + b, r);
#endif
}
}
#endif
static void fwht(float* v, int64_t g) {
for (int64_t h = 1; h < g; h <<= 1) {
#if AVX_LEVEL >= 1
if (g >= VF_N && h >= VF_N) {
for (int64_t i = 0; i < g; i += VF_N)
if ((i & h) == 0) {
const vf a = vf_loadu(v + i), b = vf_loadu(v + i + h);
vf_storeu(v + i, vf_add(a, b));
vf_storeu(v + i + h, vf_sub(a, b));
}
continue;
}
if (g >= VF_N) { fwht_small(v, g, h); continue; }
#endif
for (int64_t i = 0; i < g; ++i)
if ((i & h) == 0) {
const float a = v[i], b = v[i + h];
v[i] = a + b;
v[i + h] = a - b;
}
}
}
/* Rotate a whole row of `n` elements in blocks of `g`, in place. */
static inline void fwht_row(float* v, int64_t n, int64_t g) {
for (int64_t b = 0; b < n; b += g) fwht(v + b, g);
}
/* ================================================================== the fp8 group
* out[k0, k1) = v[k0, k1) / scale, clamped to E4M3's finite range, with scale = amax / 448 (1 for an
* all-zero group). */
static inline void fp8_group(const float* v, float* out, int64_t k0, int64_t k1, float* scale_out) {
const float amax = row_amax(v + k0, k1 - k0);
const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float inv = 1.0f / sc;
const vf vi = vf_set1(inv), hi = vf_set1(448.0f), lo = vf_set1(-448.0f);
int64_t i = k0;
for (; i + VF_N <= k1; i += VF_N)
vf_storeu(out + i, vf_min(vf_max(vf_mul(vf_loadu(v + i), vi), lo), hi));
for (; i < k1; ++i) {
float t = v[i] * inv;
out[i] = t > 448.0f ? 448.0f : (t < -448.0f ? -448.0f : t);
}
*scale_out = sc;
}
/* ================================================================== the fp8 fusions' epilogue
*
* A fused fp8 op stands in for a pair whose first half writes a bf16 tensor and whose second half
* quantises the bytes it reads back. So the codes are taken over the bf16-NARROWED value whatever
* the activation dtype, and `out_bf16` holds exactly that value -- libref's contract for all three
* (ref_quant.cpp), and the reason the helpers below narrow before they quantise. */
/* v[0, n) narrowed to bf16 and read back, in place. `tmp` holds n floats, which is room for the n
* bf16 in between. */
static inline void narrow_bf16(float* v, int64_t n, float* tmp) {
row_from_f32(RAD_BF16, v, tmp, n);
row_to_f32(RAD_BF16, tmp, v, n);
}
/* out = act(gate) * up, narrowed to bf16: act 0 is silu (down_proj's input), 1 sigmoid (a gated
* attention o_proj's). `tmp` holds n floats. */
static inline void gate_bf16(const float* gv, const float* uv, float* out, int64_t n, int act,
float* tmp) {
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) {
const vf gt = vf_loadu(gv + i);
vf_storeu(out + i, vf_mul(act == 1 ? vf_sigmoid(gt) : vf_silu(gt), vf_loadu(uv + i)));
}
for (; i < n; ++i) {
const float sg = 1.0f / (1.0f + std::exp(-gv[i]));
out[i] = (act == 1 ? sg : gv[i] * sg) * uv[i];
}
narrow_bf16(out, n, tmp);
}
/* Row r of the codes `q` and their group scales `s` over v[0, n), in groups of `g` with a ragged
* last one; and v itself into `ob` when a caller asked for it. `codes` holds n floats. */
static inline void fp8_emit(const float* v, float* codes, int64_t n, int64_t g, const RadTensor* q,
const RadTensor* s, const RadTensor* ob, int64_t r) {
if (ob) out_row(ob, rowoff(ob, r, n), n, v);
const int64_t ngrp = (n + g - 1) / g;
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
float sc;
fp8_group(v, codes, k0, k1, &sc);
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
out_row(q, rowoff(q, r, n), n, codes);
}
#endif /* RAD_AVX_HAD_H */
+495
View File
@@ -0,0 +1,495 @@
/* avx_harness.h -- opening a plugin, sizing its operands, drawing them, and the geometry table.
*
* SHARED BY rad-avx-check AND rad-avx-bench, AND THAT SHARING IS THE POINT. A benchmark taken at a
* different extent from the correctness check is a measurement of something else, and two copies
* of a geometry table drift the moment one of them gains a case. tools/opshapes.h makes exactly
* this argument for rad-kbench and rad-tune; the same argument applies one level down.
*
* Header-only and included by two translation units, so everything here is `static` or `inline`.
* Neither binary links either plugin: both dlopen by path, which is what makes the claim be about
* the .so the engine would load rather than about a differently-inlined copy of the same source.
*/
#ifndef RAD_AVX_HARNESS_H
#define RAD_AVX_HARNESS_H
#include "rad_abi.h"
#include "rad_plugin.h"
#include <dlfcn.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
/* ================================================================== a loaded plugin */
struct Lib {
void* h = nullptr;
std::string path;
const RadPluginInfo* info = nullptr;
int (*kernel_count)() = nullptr;
const RadKernelInfo* (*kernel_at)(int) = nullptr;
int (*schema_count)() = nullptr;
const RadOpSchema* (*schema_at)(int) = nullptr;
int (*plugin_open)() = nullptr;
/* libavx's own, and absent from any other plugin -- which is how a caller learns whether it
* can sweep ISA levels at all rather than assuming it is looking at libavx. */
int (*isa_force)(int) = nullptr;
int (*isa_detect)() = nullptr;
const char* (*isa_name)(int) = nullptr;
bool open(const char* p) {
path = p;
h = dlopen(p, RTLD_NOW | RTLD_LOCAL);
if (!h) { std::fprintf(stderr, "dlopen %s: %s\n", p, dlerror()); return false; }
auto sym = [&](const char* n) { return dlsym(h, n); };
auto abi = (uint32_t (*)())sym("rad_plugin_abi_version");
auto inf = (const RadPluginInfo* (*)())sym("rad_plugin_info");
kernel_count = (int (*)())sym("rad_kernel_count");
kernel_at = (const RadKernelInfo* (*)(int))sym("rad_kernel_at");
schema_count = (int (*)())sym("rad_kernel_schema_count");
schema_at = (const RadOpSchema* (*)(int))sym("rad_kernel_schema_at");
plugin_open = (int (*)())sym("rad_plugin_open");
isa_force = (int (*)(int))sym("avx_isa_force");
isa_detect = (int (*)())sym("avx_isa_detect");
isa_name = (const char* (*)(int))sym("avx_isa_name");
if (!abi || !inf || !kernel_count || !kernel_at || !schema_count || !schema_at) {
std::fprintf(stderr, "%s: not a kernel plugin (missing exports)\n", p);
return false;
}
if (abi() != RAD_ABI_VERSION) {
/* THE LOADER'S RULE, REPRODUCED: a plugin that does not report exactly this version is
* refused by name with both versions printed. A harness that shrugged at it would be
* measuring a plugin the engine will not load. */
std::fprintf(stderr, "%s: ABI %u, this tool is built for %u\n", p, abi(),
RAD_ABI_VERSION);
return false;
}
info = inf();
if (plugin_open && plugin_open() < 0) {
std::fprintf(stderr, "%s: rad_plugin_open failed\n", p);
return false;
}
return true;
}
const RadKernelInfo* row(const char* op) const {
for (int i = 0, n = kernel_count(); i < n; ++i) {
const RadKernelInfo* k = kernel_at(i);
if (k && k->op && std::strcmp(k->op, op) == 0) return k;
}
return nullptr;
}
const RadOpSchema* schema(const char* op) const {
for (int i = 0, n = schema_count(); i < n; ++i) {
const RadOpSchema* s = schema_at(i);
if (s && s->op && std::strcmp(s->op, op) == 0) return s;
}
return nullptr;
}
};
/* ================================================================== the draw
*
* The laws are RadOpdDesc's (rad_abi.h) and they are not decoration. A gated-delta-net `g` is an
* intra-chunk cumulative sum of log-decays; fed normals, the ORACLE overflows to 2e38 while the
* kernel does something else and the comparison measures the test rather than the kernel. The same
* is true of a sigmoid gate, a unit-triangular factor, a unit-norm key, and of every index
* operand -- a KV slot indexes n_blocks * block_size and a block-table entry indexes n_blocks, and
* drawing either from the wrong range tests out-of-range handling and calls the result
* correctness. rad_abi.h and tools/kfixture.cpp both record having been bitten by each of these.
*/
static inline uint64_t hsplitmix(uint64_t& x) {
uint64_t z = (x += 0x9E3779B97F4A7C15ull);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
return z ^ (z >> 31);
}
static inline void fill_normal(float* v, int64_t n, uint64_t seed, float sigma) {
uint64_t s = seed ? seed : 1;
for (int64_t i = 0; i < n; i += 2) {
/* Box-Muller off two splitmix draws. u1 is nudged off zero so the log is finite. */
const double u1 = ((hsplitmix(s) >> 40) + 1) * (1.0 / 16777216.0);
const double u2 = ((hsplitmix(s) >> 40)) * (1.0 / 16777216.0);
const double r = std::sqrt(-2.0 * std::log(u1));
const double th = 6.283185307179586 * u2;
v[i] = (float)(r * std::cos(th)) * sigma;
if (i + 1 < n) v[i + 1] = (float)(r * std::sin(th)) * sigma;
}
}
struct Opd {
RadOpdDesc d{};
bool absent = false;
int role = RAD_OPD_IN;
int64_t n = 0;
std::vector<uint8_t> master, a, b; /* the drawn bytes, then one copy per side */
};
static inline int64_t desc_numel(const RadOpdDesc& d) {
int64_t n = 1;
for (uint32_t i = 0; i < d.rank; ++i) n *= d.shape[i];
return n;
}
static inline size_t dt_bytes(uint32_t dt, int64_t n) {
return (size_t)((n * rad_dtype_bits(dt) + 7) / 8);
}
/* W4 / W2 / MXFP4 have no store side in the ABI's accessor, and the packed grids are WEIGHT
* operands a fixture would lay out rather than draw. Writing the CODE directly is the honest
* alternative: both plugins decode the same symmetric two's-complement nibble
* (libref/ref_common.h), so the bytes mean the same thing to both sides, which is the only
* property the comparison needs. */
static inline void h_narrow(const float* src, uint32_t dt, int64_t n, void* dst) {
if (dt == RAD_I4 || dt == RAD_FP4E2M1) {
uint8_t* b = (uint8_t*)dst;
std::memset(b, 0, dt_bytes(dt, n));
for (int64_t i = 0; i < n; ++i) {
int c = (int)std::lrintf(src[i] * 3.0f);
c = c < -8 ? -8 : (c > 7 ? 7 : c);
b[i >> 1] |= (uint8_t)(((uint8_t)((c + 8) & 0xf)) << (4 * (i & 1)));
}
return;
}
if (dt == RAD_I2) {
uint8_t* b = (uint8_t*)dst;
std::memset(b, 0, dt_bytes(dt, n));
for (int64_t i = 0; i < n; ++i) {
int c = (int)std::lrintf(src[i]);
c = c < -2 ? -2 : (c > 1 ? 1 : c);
b[i >> 2] |= (uint8_t)(((uint8_t)((c + 2) & 0x3)) << (2 * (i & 3)));
}
return;
}
for (int64_t i = 0; i < n; ++i) rad_store_f32(dst, dt, i, src[i]);
}
static inline void h_widen(const void* src, uint32_t dt, int64_t n, float* dst) {
if (dt == RAD_I4) {
for (int64_t i = 0; i < n; ++i) {
const uint8_t by = ((const uint8_t*)src)[i >> 1];
const uint8_t nb = (i & 1) ? (uint8_t)(by >> 4) : (uint8_t)(by & 0xf);
dst[i] = (float)((int)(nb ^ 0x8u) - 8);
}
return;
}
if (dt == RAD_I2) {
for (int64_t i = 0; i < n; ++i) {
const uint8_t by = ((const uint8_t*)src)[i >> 2];
const uint8_t c = (uint8_t)((by >> (2 * (i & 3))) & 0x3u);
dst[i] = (float)((int)(c ^ 0x2u) - 2);
}
return;
}
if (dt == RAD_FP4E2M1) {
static const float mag[8] = { 0, 0.5f, 1, 1.5f, 2, 3, 4, 6 };
for (int64_t i = 0; i < n; ++i) {
const uint8_t by = ((const uint8_t*)src)[i >> 1];
const uint8_t nb = (i & 1) ? (uint8_t)(by >> 4) : (uint8_t)(by & 0xf);
dst[i] = (nb & 8u) ? -mag[nb & 7u] : mag[nb & 7u];
}
return;
}
for (int64_t i = 0; i < n; ++i) dst[i] = rad_load_f32(src, dt, i);
}
static inline void h_draw(std::vector<Opd>& o, size_t k, int64_t M, uint64_t seed) {
Opd& d = o[k];
const int64_t n = d.n;
d.master.assign(dt_bytes(d.d.dtype, n > 0 ? n : 0), 0);
if (n <= 0 || d.absent) return;
if (d.role != RAD_OPD_IN && d.role != RAD_OPD_INOUT && d.role != RAD_OPD_WEIGHT) return;
std::vector<float> tmp((size_t)n, 0.0f);
const bool is_index = d.d.fill == RAD_FILL_INDEX;
const bool idx_cu = (d.d.flags & RAD_OPD_F_IDX_CU) != 0;
const bool idx_uniq = (d.d.flags & RAD_OPD_F_IDX_UNIQUE) != 0;
if (d.role == RAD_OPD_WEIGHT && !is_index) {
/* 0.02 sigma, and it is not cosmetic: a checkpoint's weights are that size, and drawing
* them at unit variance puts an fp8 quantiser's amax three orders of magnitude off where a
* real one sits -- so the case would measure the quantiser on data no model produces. */
fill_normal(tmp.data(), n, seed, 0.02f);
} else if (is_index && idx_cu) {
/* Cumulative sequence lengths, [0 .. T]: the batch's shape, not a draw. */
const int64_t S = n > 1 ? n - 1 : 1;
for (int64_t i = 0; i < n; ++i) tmp[(size_t)i] = (float)((i * M) / S);
} else if (is_index && d.d.idx_const >= 0) {
for (int64_t i = 0; i < n; ++i) tmp[(size_t)i] = (float)d.d.idx_const;
} else if (is_index && idx_uniq) {
/* A scatter's destinations, distinct: two tokens on one slot is a race the two
* implementations resolve differently, so the comparison would measure the scheduler. */
uint64_t s2 = seed;
const int64_t range = d.d.idx_max > 0 ? d.d.idx_max : n;
std::vector<int32_t> pool((size_t)range);
for (int64_t i = 0; i < range; ++i) pool[(size_t)i] = (int32_t)i;
for (int64_t i = 0; i < n && i < range; ++i) {
const int64_t j = i + (int64_t)(hsplitmix(s2) % (uint64_t)(range - i));
std::swap(pool[(size_t)i], pool[(size_t)j]);
tmp[(size_t)i] = (float)pool[(size_t)i];
}
for (int64_t i = range; i < n; ++i) tmp[(size_t)i] = -1.0f;
} else if (is_index) {
uint64_t s2 = seed;
int64_t rows = 32000;
if (k > 0 && o[k - 1].d.rank > 0) rows = o[k - 1].d.shape[0];
if (d.d.idx_max > 0) rows = d.d.idx_max;
if (rows <= 0) rows = 1;
for (int64_t i = 0; i < n; ++i) tmp[(size_t)i] = (float)(hsplitmix(s2) % (uint64_t)rows);
} else {
fill_normal(tmp.data(), n, seed, 1.0f);
if (d.d.fill == RAD_FILL_SIGMOID) {
for (int64_t i = 0; i < n; ++i)
tmp[(size_t)i] = 1.0f / (1.0f + std::exp(-tmp[(size_t)i]));
} else if (d.d.fill == RAD_FILL_TRI_LOWER) {
/* UNIT DIAGONAL, SMALL OFF-DIAGONAL. `A` is the chunked delta rule's intra-chunk
* matrix I + tril(diag(beta) K K^T, -1), unit lower triangular by construction, and
* its inverse is bounded only because of that. A normal on the diagonal makes the
* inverse enormous, and what the comparison then reports is the condition number of
* the TEST. */
const int64_t ch = d.d.fill_chunk > 0 ? d.d.fill_chunk : 1;
const int64_t heads = d.d.rank >= 3 ? d.d.shape[1] : 1;
const int64_t rows = (heads * ch) != 0 ? n / (heads * ch) : n;
for (int64_t t = 0; t < rows; ++t)
for (int64_t h = 0; h < heads; ++h)
for (int64_t j = 0; j < ch; ++j) {
const size_t i = (size_t)((t * heads + h) * ch + j);
const int64_t diag = t % ch;
if (j > diag) tmp[i] = 0.0f;
else if (j == diag) tmp[i] = 1.0f;
else tmp[i] *= 0.25f;
}
} else if (d.d.fill == RAD_FILL_GATE_CUMSUM) {
const int64_t heads = d.d.rank >= 2 ? d.d.shape[d.d.rank - 1] : 1;
const int64_t rows = heads > 0 ? n / heads : n;
const int64_t ch = d.d.fill_chunk > 0 ? d.d.fill_chunk : rows;
for (int64_t h = 0; h < heads; ++h) {
float acc = 0.0f;
for (int64_t t = 0; t < rows; ++t) {
if (t % ch == 0) acc = 0.0f;
acc -= std::log1p(std::exp(tmp[(size_t)(t * heads + h)]));
tmp[(size_t)(t * heads + h)] = acc;
}
}
} else if (d.d.fill == RAD_FILL_UNIT_ROW) {
const int64_t w = d.d.rank ? d.d.shape[d.d.rank - 1] : n;
if (w > 0)
for (int64_t r = 0; r + w <= n; r += w) {
double ss = 0;
for (int64_t i = 0; i < w; ++i)
ss += (double)tmp[(size_t)(r + i)] * (double)tmp[(size_t)(r + i)];
const float inv = ss > 0 ? (float)(1.0 / std::sqrt(ss)) : 0.0f;
for (int64_t i = 0; i < w; ++i) tmp[(size_t)(r + i)] *= inv;
}
}
}
h_narrow(tmp.data(), d.d.dtype, n, d.master.data());
}
/* ================================================================== the geometry table
*
* THE ONE PLACE THESE TOOLS KNOW ANYTHING ABOUT AN OP, and it is a PARAMETER list rather than a
* shape: the shapes come from libref's own `opd_shape`. The values are chosen to be small but not
* degenerate -- a row wider than any vector, a row count above one, a group that divides, and
* where the op allows it a row length that does NOT divide the vector width, because the tail is
* where a hand-vectorised kernel is wrong.
*/
struct P { const char* k; int kind; long long i; const char* s; double d; };
static inline RadParam h_mk(const P& p) {
RadParam r{};
r.key = p.k; r.kind = p.kind; r.ival = p.i; r.sval = p.s; r.dval = p.d;
return r;
}
#define HI(k, v) P{ k, RAD_P_INT, (long long)(v), nullptr, 0.0 }
#define HS(k, v) P{ k, RAD_P_STR, 0, v, 0.0 }
#define HF(k, v) P{ k, RAD_P_F64, 0, nullptr, (double)(v) }
struct Case {
const char* op;
std::vector<P> p;
/* Bytes moved and flops done, for the bench's rate columns. 0 means "do not report a rate":
* an op whose cost is not a simple function of its geometry gets a time and no invented
* denominator. */
double bytes = 0, flops = 0;
/* A case worth TIMING at a real model shape and not worth checking there. Correctness is a
* property of the arithmetic and a 640-wide row exercises every path a 2048-wide one does, so
* the checker would spend minutes inside libref to learn nothing; speed is not, because it is
* the cache hierarchy that decides it and a shape that fits L1 answers a different question.
* The same split tools/kfixture.h draws, and for the same reason. rad-avx-check skips these. */
bool speed_only = false;
};
/* THE TOTAL TOKEN COUNT OF THE BATCH, which is what the cumulative-length draw divides across the
* sequences and what no operand carries.
*
* IT IS NOT ALWAYS THE RANGED PARAMETER, and that distinction cost four silently skipped ops. An
* op banded on `M` is banded on the TOTAL -- `gdn_conv_prep` sizes its activation [M, conv_dim] and
* its cu spans M. An op banded on `q_len` is banded on the PER-SEQUENCE length: `gdn_conv_update`
* sizes its activation [n_seq * q_len, conv_dim], because a decode step presents q_len candidate
* rows for each of n_seq sequences. Drawing cu to sum to q_len there gives a batch whose cu says
* two tokens over operands sized for four, and libref recomputes its head count from
* numel(q) / (T * head_k) -- which comes out double, makes conv_dim double, and refuses the launch
* with RAD_E_SHAPE. The case was then SKIPPED, and a skip with no reason printed is indistinguishable
* from an op that has no case at all.
*
* `attn_paged` is also banded on `q_len` and is unaffected only because libref describes it at one
* sequence; the rule below is right for both. */
static inline int64_t case_M(const Case& c) {
int64_t n_seq = 1;
for (const P& p : c.p) if (std::strcmp(p.k, "n_seq") == 0 && p.i > 0) n_seq = p.i;
for (const P& p : c.p) if (std::strcmp(p.k, "M") == 0) return p.i;
for (const P& p : c.p) if (std::strcmp(p.k, "q_len") == 0) return p.i * n_seq;
for (const P& p : c.p) if (std::strcmp(p.k, "numel") == 0) return p.i;
return 1;
}
static inline const char* case_dtype(const Case& c) {
static const char* keys[] = { "dtype", "q_dtype", "kv_dtype", "to" };
for (const char* k : keys)
for (const P& p : c.p)
if (std::strcmp(p.k, k) == 0 && p.kind == RAD_P_STR) return p.s;
return "*";
}
static inline long long case_geti(const Case& c, const char* k, long long dflt) {
for (const P& p : c.p) if (std::strcmp(p.k, k) == 0) return p.i;
return dflt;
}
/* A one-line rendering of a case, so a failure names a geometry a reader can reproduce. */
static inline std::string case_str(const Case& c) {
std::string s;
for (const P& p : c.p) {
char buf[96];
if (p.kind == RAD_P_STR) std::snprintf(buf, sizeof buf, "%s=%s ", p.k, p.s ? p.s : "");
else if (p.kind == RAD_P_F64) std::snprintf(buf, sizeof buf, "%s=%g ", p.k, p.d);
else std::snprintf(buf, sizeof buf, "%s=%lld ", p.k, p.i);
s += buf;
}
if (!s.empty()) s.pop_back();
return s;
}
/* ================================================================== a prepared case
* Operands sized by the ORACLE's description, drawn once, and copied into one buffer per side.
* The two plugins must see byte-identical inputs or the comparison is noise; drawing twice from
* one seed would work too and would be one more place for the two to diverge. */
struct Prepared {
bool ok = false;
bool skipped = false; /* the oracle declined this geometry -- a real answer */
std::vector<RadParam> params;
std::vector<Opd> opd;
const RadOpSchema* schema = nullptr;
std::vector<RadTensor> ta, tb;
RadArgs aa{}, ab{};
std::vector<uint8_t> sa, sb;
};
static inline void h_build_tensors(std::vector<Opd>& opd, bool side_a,
std::vector<RadTensor>* out) {
out->assign(opd.size(), RadTensor{});
for (size_t i = 0; i < opd.size(); ++i) {
RadTensor& x = (*out)[i];
if (opd[i].absent) { x.data = nullptr; continue; }
x.data = (side_a ? opd[i].a : opd[i].b).data();
x.dtype = opd[i].d.dtype;
x.rank = opd[i].d.rank;
int64_t acc = 1;
for (int k = (int)x.rank - 1; k >= 0; --k) {
x.shape[k] = opd[i].d.shape[k];
x.stride[k] = acc;
acc *= x.shape[k];
}
}
}
/* `describe` is the kernel whose opd_shape is asked. A correctness check passes the ORACLE's (the
* two sides must be handed the same bytes, and where they could disagree about an extent the
* reference semantics define the op); a benchmark of a kernel with no oracle passes its own.
* rad-kbench makes the same distinction for the same reason, in tools/opshapes.h. */
static inline Prepared h_prepare(const Lib& oracle, const RadKernelInfo* describe, const Case& c,
const RadKernelInfo* ka, const RadKernelInfo* kb) {
Prepared pr;
pr.schema = oracle.schema(c.op);
if (!pr.schema || !describe || !describe->opd_shape) { pr.skipped = true; return pr; }
pr.params.reserve(c.p.size());
for (const P& p : c.p) pr.params.push_back(h_mk(p));
pr.opd.assign((size_t)pr.schema->n_operands, Opd{});
for (int i = 0; i < pr.schema->n_operands; ++i) {
RadOpdDesc d{};
d.idx_const = -1; /* the ABI's "draw", so a hook that leaves it alone means default */
if (describe->opd_shape(pr.params.data(), (int)pr.params.size(), i, &d) < 0) {
pr.skipped = true;
return pr;
}
Opd& o = pr.opd[(size_t)i];
o.d = d;
o.absent = (d.flags & RAD_OPD_F_ABSENT) != 0;
o.role = pr.schema->operands[i].role;
o.n = o.absent ? 0 : desc_numel(d);
/* A rank the ABI cannot express is a hook bug, not a declined geometry, and it must not
* become a zero-extent buffer that every comparison then passes vacuously. */
if (!o.absent && (d.rank == 0 || d.rank > RAD_MAX_RANK)) { pr.skipped = true; return pr; }
}
uint64_t seed = 0x9E3779B9ull;
for (const P& p : c.p) {
seed = seed * 1000003ull + (uint64_t)p.i;
if (p.s) for (const char* s = p.s; *s; ++s) seed = seed * 131ull + (unsigned char)*s;
}
for (size_t k = 0; k < pr.opd.size(); ++k) {
uint64_t s = seed ^ (0x100000001b3ull * (k + 1));
h_draw(pr.opd, k, case_M(c), s ? s : 1);
pr.opd[k].a = pr.opd[k].master;
pr.opd[k].b = pr.opd[k].master;
}
h_build_tensors(pr.opd, true, &pr.ta);
h_build_tensors(pr.opd, false, &pr.tb);
pr.aa.t = pr.ta.data(); pr.aa.n_t = (int)pr.ta.size();
pr.aa.p = pr.params.data(); pr.aa.n_p = (int)pr.params.size();
pr.aa.rank = 0; pr.aa.world_size = 1;
pr.ab = pr.aa;
pr.ab.t = pr.tb.data();
/* The scratch hook is honoured rather than assumed away: a kernel that grew one and was handed
* null would fault, and the fault would read as a kernel bug. */
if (ka && ka->scratch) {
const int64_t n = ka->scratch(&pr.aa);
if (n > 0) { pr.sa.assign((size_t)n, 0); pr.aa.scratch = pr.sa.data(); pr.aa.scratch_bytes = n; }
}
if (kb && kb->scratch) {
const int64_t n = kb->scratch(&pr.ab);
if (n > 0) { pr.sb.assign((size_t)n, 0); pr.ab.scratch = pr.sb.data(); pr.ab.scratch_bytes = n; }
}
pr.ok = true;
return pr;
}
/* Restore both sides to the drawn bytes. A benchmark that loops a launch must do this between
* iterations for any op with an INOUT operand, or it is timing a different computation each time
* -- a twenty-iteration loop over `rope` leaves the tensor rotated twenty-one times, which a
* checker then reports as a large error against a kernel that is correct (tools/opshapes.h and
* rad-kbench make the same point). */
static inline void h_reset(Prepared& pr) {
for (Opd& o : pr.opd) {
if (o.absent || o.n <= 0) continue;
if (o.role == RAD_OPD_INOUT || o.role == RAD_OPD_OUT) {
std::memcpy(o.a.data(), o.master.data(), o.master.size());
std::memcpy(o.b.data(), o.master.data(), o.master.size());
}
}
}
std::vector<Case> build_cases();
#endif /* RAD_AVX_HARNESS_H */
+494
View File
@@ -0,0 +1,494 @@
/* avx_hc.cpp -- the GATED RESIDUAL pair and the MTP head's entry.
*
* ============================== WHAT THE GATED RESIDUAL IS ==============================
*
* Qwen4-Exp's replacement for a pre-norm and a residual add. The residual stream is `hc` times as
* wide as the model -- hidden 2560 at hc 4 is a 10240-wide stream carried through every layer,
* entered as hc identical copies of the embedding and collapsed once at the end. Every block reads
* a 2560 mix of the four and writes its output back into all four, and BOTH the read's mix and the
* write's per-stream gain are data-dependent, which is what "gated" means here.
*
* hc_read N = grouped_rmsnorm(h) one rsqrt per n-wide stream, one gain of
* hc*n over all of them, `1 + w`
* g = sigmoid(W_up @ silu(W_down @ N / hc))
* x = mean_over_streams(g * N)
* inj[s] = 2 * sigmoid(W_inj[s] . N / hc)
* hc_write h[s] += inj[s] * y
*
* THREE FACTS THAT ARE NOT DERIVABLE FROM THE OTHERS, and a second implementation has to match all
* three (docs/OPS.md states them and they are restated here because each is a silent failure):
*
* THE WRITE READS THE UNNORMED `h`, NOT `N`. The normalisation is consumed by the block input
* and the gates and never enters the stream. Writing into `N` instead re-normalises the residual
* at every one of 96 connections, diverges within a few layers, and still produces fluent text.
*
* THE MIX IS A MEAN, NOT A SUM -- `.mean(dim=-2)` over the hc dimension.
*
* THERE IS A SEPARATE `/ hc` INSIDE EACH GATE ARGUMENT, before the silu and before the inject
* sigmoid. Three divisions by hc in total, none implied by the others.
*
* ============================== THE ROUNDING IS PART OF THE OP ==============================
*
* The arithmetic here is f32, but the REFERENCE MODEL's is not: torch's grouped norm returns
* `.type_as(x)`, so both matrix products and the final multiply read a bf16 `N`. libref rounds
* once per element for that reason and so does this -- through the row converter rather than
* element by element, which is the same value and one pass. The same applies to the silu output,
* the sigmoid gate, and to `x` before the optional fp8 quantiser reads it back.
*
* ============================== THE WEIGHTS ARE WIDENED ONCE PER LAUNCH ==============================
*
* This is the structural change from libref, and it is worth more here than vectorisation. Every
* product below contracts a WEIGHT against a per-token vector -- `down` is [lowrank, hc*n], `up` is
* [hc*n, lowrank], `inject_w` is [hc, hc*n] -- and libref reads those weights through `ldt` inside
* the token loop, so a 2048-row prefill chunk converts the same 10240-wide weight row 2048 times.
* Widening all three into one scratch block before the token loop makes every dot product a
* straight f32 vector reduction and converts each weight element exactly once.
*
* ONE scratch_raw CALL FOR ALL OF THEM, because the arena grows: a second call at a larger size
* frees the first block, and every worker thread would then be reading a dangling weight.
*/
#include "avx_vec.h"
#include "avx_common.h"
using namespace avx;
#include "avx_had.h"
/* A single value narrowed to a tensor's dtype and read back -- the scalar form of the rounding
* rule above, for the handful of places where it lands on one number rather than a row. */
static inline float narrow1(uint32_t dt, float v) {
uint32_t buf[2] = { 0, 0 };
rad_store_f32(buf, dt, 0, v);
return rad_load_f32(buf, dt, 0);
}
/* A weight plane widened into f32, row-major and contiguous. `rows` x `cols` of the operand read
* the way libref reads it (rowoff / laststride), so a strided or rank-3 weight lands correctly. */
static void widen_plane(const RadTensor* t, int64_t rows, int64_t cols, float* dst) {
const int64_t st = laststride(t);
for (int64_t r = 0; r < rows; ++r) {
const int64_t b = rowoff(t, r, cols);
if (st == 1) row_to_f32(t->dtype, byte_at(t->data, t->dtype, b), dst + r * cols, cols);
else for (int64_t i = 0; i < cols; ++i) dst[r * cols + i] = ldt(t, b + i * st);
}
}
static inline float dotf(const float* a, const float* b, int64_t n) {
vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero();
int64_t i = 0;
for (; i + 4 * VF_N <= n; i += 4 * VF_N) {
a0 = vf_fma(vf_loadu(a + i), vf_loadu(b + i), a0);
a1 = vf_fma(vf_loadu(a + i + VF_N), vf_loadu(b + i + VF_N), a1);
a2 = vf_fma(vf_loadu(a + i + 2 * VF_N), vf_loadu(b + i + 2 * VF_N), a2);
a3 = vf_fma(vf_loadu(a + i + 3 * VF_N), vf_loadu(b + i + 3 * VF_N), a3);
}
for (; i + VF_N <= n; i += VF_N) a0 = vf_fma(vf_loadu(a + i), vf_loadu(b + i), a0);
float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3)));
for (; i < n; ++i) s += a[i] * b[i];
return s;
}
/* THE SUM OF SQUARES IS ACCUMULATED IN f64 HERE AND IN f32 IN avx_norm.cpp, and that is libref's
* split reproduced rather than an inconsistency. `rmsnorm` accumulates in f32 because it is the
* op every fast kernel is checked against and an oracle tighter than the thing it certifies turns
* a tolerance into a guess; the gated residual's norm is an INTERNAL step of a fused op that no
* kernel computes separately, so libref takes the tighter accumulation there and this matches it.
* Not vectorised: it is one reduction per stream against two matrix products that dominate, and a
* vector f64 path would be a fifth numeric convention in the file. */
static float rsqrt_meansq_f64(const float* v, int64_t n, float eps) {
double ss = 0.0;
for (int64_t i = 0; i < n; ++i) ss += (double)v[i] * (double)v[i];
return 1.0f / std::sqrt((float)(ss / (double)n) + eps);
}
/* ------------------------------------------------------------------ hc_enter */
/* THE WIDE STREAM'S FIRST VALUE: hc identical copies of the embedding. One launch for the whole
* step. It exists rather than being folded into the embedding lookup because the lookup's weight
* is [vocab, n] and its output width is n -- a wide output would be a different op with a
* different weight shape. The streams are identical here and diverge at the first connection,
* because each block writes into all of them with a different per-branch gain. */
AVX_KERNEL(hc_enter) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor* x = &a->t[0];
const RadTensor* h = &a->t[1];
const int64_t n = p_int(a, "n", 0);
const int64_t hc = p_int(a, "hc", 0);
if (n <= 0 || hc <= 1) return RAD_E_SHAPE;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(h) < rows * hc * n) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(rows * hc * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), hb = rowoff(h, r, hc * n);
const int64_t hs = laststride(h);
float* buf = scratch_f32((size_t)n);
const float* v = in_row(x, xb, n, buf);
/* The copy is per STREAM and contiguous, where libref's inner loop is over i with the
* stream inside it -- which writes with a stride of n and defeats the store buffer. Same
* bytes, one stream at a time. */
if (hs == 1) for (int64_t c = 0; c < hc; ++c) out_row(h, hb + c * n, n, v);
else for (int64_t c = 0; c < hc; ++c)
for (int64_t i = 0; i < n; ++i) stt(h, hb + (c * n + i) * hs, v[i]);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ hc_read */
AVX_KERNEL(hc_read) {
/* NOT `rad_args_have(a, 6)`: operand 4 is the OPTIONAL inject weight, and a prefix test would
* refuse the final mixer -- the one connection that has none. The required ones are 0..3 and 5. */
if (a->n_t < 6) return RAD_E_INVAL;
if (!rad_arg_in(a, 0) || !rad_arg_in(a, 1) || !rad_arg_in(a, 2) || !rad_arg_in(a, 3) ||
!rad_arg_in(a, 5)) return RAD_E_INVAL;
const RadTensor* h = &a->t[0];
const RadTensor* w = &a->t[1];
const RadTensor* down = &a->t[2];
const RadTensor* up = &a->t[3];
const RadTensor* injw = rad_arg_in(a, 4); /* absent on the final mixer */
const RadTensor* x = &a->t[5];
const RadTensor* inj = rad_arg_in(a, 6);
const RadTensor* q = rad_arg_in(a, 7);
const RadTensor* s = rad_arg_in(a, 8);
const RadTensor* rq = rad_arg_in(a, 9); /* the ROTATED fp8 form, for a w4a8h consumer */
const RadTensor* rs = rad_arg_in(a, 10);
const int64_t n = p_int(a, "n", 0);
const int64_t hc = p_int(a, "hc", 0);
const int64_t lr = p_int(a, "lowrank", 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
if (n <= 0 || hc <= 1 || lr <= 0) return RAD_E_SHAPE;
const int64_t hn = hc * n;
const int64_t rows = numel(h) / hn;
if (rows <= 0 || numel(x) < rows * n || numel(w) < hn ||
numel(down) < lr * hn || numel(up) < hn * lr) return RAD_E_SHAPE;
if (injw && numel(injw) < hc * hn) return RAD_E_SHAPE;
/* `inj` is what the paired hc_write consumes, so an inject WEIGHT with no inject OUTPUT is a
* caller that computed hc scalars and threw them away -- refused rather than ignored. */
if (injw && (!inj || !inj->data || numel(inj) < rows * hc)) return RAD_E_SHAPE;
int64_t g = 0, ngrp = 0;
if (q && q->data) {
g = p_int(a, "group", 0);
if (g <= 0 || g > n) g = n;
ngrp = (n + g - 1) / g;
if (numel(q) < rows * n || !s || !s->data || numel(s) < rows * ngrp) return RAD_E_SHAPE;
}
/* The rotated form rotates each scale group whole, so the group must tile the row exactly and
* be a power of two: a block that straddled the end of the row would mix real values with
* padding, and no weight block was rotated that way. It is had_quant_act_fp8 of the stored `x`
* -- the operand's consumer cannot tell which op wrote it. */
int64_t rg = 0;
if (rq && rq->data) {
rg = p_int(a, "group", 0);
if (!pow2(rg) || n % rg != 0 || !rs || !rs->data || numel(rq) < rows * n ||
numel(rs) < rows * (n / rg))
return RAD_E_SHAPE;
if (rg > AVX_HAD_MAX) return RAD_E_UNSUPPORTED;
}
/* The gain and all three weight planes, widened once. See the header on why this is one call. */
auto pad = [](size_t v) { return (v + 15) & ~(size_t)15; };
const size_t o_gain = 0;
const size_t o_down = pad(o_gain + (size_t)hn);
const size_t o_up = pad(o_down + (size_t)lr * (size_t)hn);
const size_t o_inj = pad(o_up + (size_t)hn * (size_t)lr);
const size_t total = o_inj + (injw ? (size_t)hc * (size_t)hn : 0) + 16;
float* blk = (float*)scratch_raw(total * sizeof(float));
float* gain = blk + o_gain;
float* dn = blk + o_down;
float* upw = blk + o_up;
float* iw = blk + o_inj;
{
const int64_t ws = laststride(w);
if (ws == 1) row_to_f32(w->dtype, w->data, gain, hn);
else for (int64_t i = 0; i < hn; ++i) gain[i] = ldt(w, i * ws);
if (wadd != 0.0f) for (int64_t i = 0; i < hn; ++i) gain[i] += wadd;
}
widen_plane(down, lr, hn, dn);
widen_plane(up, hn, lr, upw);
if (injw) widen_plane(injw, hc, hn, iw);
AVX_PARALLEL_FOR_IF(rows >= 2)
for (int64_t r = 0; r < rows; ++r) {
const int64_t hb = rowoff(h, r, hn), xb = rowoff(x, r, n);
const int64_t xs = laststride(x);
float* N = scratch_f32((size_t)hn);
float* tmp = scratch_f32_b((size_t)hn);
float* dv = scratch_f32_c((size_t)(lr + n) + 16);
float* xv = dv + lr + 8;
/* ---- the grouped norm: one rsqrt per stream over its own n, then the full-width gain,
* then a single round trip through h's dtype for the whole wide row. */
const float* hv = in_row(h, hb, hn, tmp);
for (int64_t c = 0; c < hc; ++c) {
const float sc = rsqrt_meansq_f64(hv + c * n, n, eps);
const vf vs = vf_set1(sc);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N)
vf_storeu(N + c * n + i,
vf_mul(vf_mul(vf_loadu(hv + c * n + i), vs), vf_loadu(gain + c * n + i)));
for (; i < n; ++i) N[c * n + i] = hv[c * n + i] * sc * gain[c * n + i];
}
if (h->dtype != RAD_F32) {
row_from_f32(h->dtype, N, tmp, hn);
row_to_f32(h->dtype, tmp, N, hn);
}
/* ---- the read gate: hc*n -> lowrank -> hc*n, silu between and sigmoid after. */
for (int64_t j = 0; j < lr; ++j) {
const float t = dotf(N, dn + j * hn, hn) / (float)hc;
dv[j] = narrow1(down->dtype, t / (1.0f + std::exp(-t))); /* silu */
}
/* ---- the mix, and the MEAN over the streams. */
const float invhc = 1.0f / (float)hc;
for (int64_t i = 0; i < n; ++i) {
float acc = 0.0f;
for (int64_t c = 0; c < hc; ++c) {
const int64_t row = c * n + i;
const float gv = dotf(dv, upw + row * lr, lr);
acc += narrow1(up->dtype, 1.0f / (1.0f + std::exp(-gv))) * N[row];
}
xv[i] = acc * invhc;
}
if (xs == 1) out_row(x, xb, n, xv);
else for (int64_t i = 0; i < n; ++i) stt(x, xb + i * xs, xv[i]);
/* ---- the per-branch write gates. */
if (injw && inj) {
const int64_t ib = rowoff(inj, r, hc), is = laststride(inj);
for (int64_t c = 0; c < hc; ++c) {
const float acc = dotf(N, iw + c * hn, hn) * invhc;
stt(inj, ib + c * is, 2.0f / (1.0f + std::exp(-acc)));
}
}
/* ---- the optional fp8 form of x, READ BACK FROM WHAT WAS STORED. `x` is narrowed to its
* own dtype first and the codes come from the narrowed value, not from the accumulator,
* because that is what a fused kernel necessarily does and the two have to agree bit for
* bit. The round trip is done in this buffer rather than by re-reading the operand: same
* arithmetic, and it does not depend on the store having retired. */
if (((q && q->data) || rg) && x->dtype != RAD_F32) {
row_from_f32(x->dtype, xv, tmp, n);
row_to_f32(x->dtype, tmp, xv, n);
}
if (q && q->data) {
const int64_t qb = rowoff(q, r, n), qs = laststride(q);
float* qv = N; /* N is dead from here; the codes reuse its storage. */
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
const float amax = row_amax(xv + k0, k1 - k0);
const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float invs = 1.0f / sc;
const vf vi = vf_set1(invs), hi = vf_set1(448.0f), lo = vf_set1(-448.0f);
int64_t i = k0;
for (; i + VF_N <= k1; i += VF_N)
vf_storeu(qv + i, vf_min(vf_max(vf_mul(vf_loadu(xv + i), vi), lo), hi));
for (; i < k1; ++i) {
float v = xv[i] * invs;
qv[i] = v > 448.0f ? 448.0f : (v < -448.0f ? -448.0f : v);
}
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
if (qs == 1) out_row(q, qb, n, qv);
else for (int64_t i = 0; i < n; ++i) stt(q, qb + i * qs, qv[i]);
}
/* ---- the optional ROTATED fp8 form of x, from the same stored values. */
if (rg) {
float* rv = N; /* N and tmp are dead once the plain codes are stored. */
float* rc = tmp;
std::memcpy(rv, xv, (size_t)n * sizeof(float));
fwht_row(rv, n, rg);
const int64_t rgrp = n / rg;
for (int64_t gi = 0; gi < rgrp; ++gi) {
float sc;
fp8_group(rv, rc, gi * rg, gi * rg + rg, &sc);
stt(rs, rowoff(rs, r, rgrp) + gi * laststride(rs), sc);
}
const int64_t qb = rowoff(rq, r, n), qs = laststride(rq);
if (qs == 1) out_row(rq, qb, n, rc);
else for (int64_t i = 0; i < n; ++i) stt(rq, qb + i * qs, rc[i]);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ hc_write */
/* `h[s] += inj[s] * y` for each of the hc streams, in place. `h` is the only output and it is the
* stream the paired read was handed, UNNORMED and unchanged by it. */
AVX_KERNEL(hc_write) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor* y = &a->t[0];
const RadTensor* inj = &a->t[1];
const RadTensor* h = &a->t[2];
const int64_t n = p_int(a, "n", 0);
const int64_t hc = p_int(a, "hc", 0);
if (n <= 0 || hc <= 1) return RAD_E_SHAPE;
const int64_t hn = hc * n;
const int64_t rows = numel(y) / n;
if (rows <= 0 || numel(h) < rows * hn || numel(inj) < rows * hc) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(rows * hn >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
const int64_t yb = rowoff(y, r, n), hb = rowoff(h, r, hn), ib = rowoff(inj, r, hc);
const int64_t hs = laststride(h), is = laststride(inj);
float* yv = scratch_f32((size_t)n);
float* hv = scratch_f32_b((size_t)n);
const float* yy = in_row(y, yb, n, yv);
for (int64_t c = 0; c < hc; ++c) {
const float gain = ldt(inj, ib + c * is);
if (hs != 1) {
for (int64_t i = 0; i < n; ++i) {
const int64_t j = hb + (c * n + i) * hs;
stt(h, j, ldt(h, j) + gain * yy[i]);
}
continue;
}
const float* cur = in_row(h, hb + c * n, n, hv);
if (cur != hv) std::memcpy(hv, cur, (size_t)n * sizeof(float));
const vf vg = vf_set1(gain);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N)
vf_storeu(hv + i, vf_fma(vg, vf_loadu(yy + i), vf_loadu(hv + i)));
for (; i < n; ++i) hv[i] += gain * yy[i];
out_row(h, hb + c * n, n, hv);
}
}
return RAD_OK;
}
/* ================================================================== mtp_enter
*
* THE MULTI-TOKEN-PREDICTION HEAD'S ENTRY, for a model whose residual stream is `hc` wide.
*
* A pre-norm MTP head joins the trunk's hidden state and the next token's embedding with ONE `fc`
* over their concatenation. Qwen4-Exp's cannot: its hidden state is the WIDE stream and the
* checkpoint carries TWO square matrices, so the hidden half is `fc_h` applied to EACH of the hc
* sub-streams and the embedding half is one n-wide product added into all of them.
*
* ne[j] = e[j] * rsqrt(mean(e^2) + eps) * (w_e[j] + wadd)
* fe[i] = sum_j fc_e[i][j] * ne[j]
* nh[k][j] = h[k*n+j] * rs[k] * (w_h[k*n+j] + wadd)
* x[k*n+i] = sum_j fc_h[i][j] * nh[k][j] + fe[i]
*
* `ngroup` IS THE ONE THING THE CHECKPOINT DOES NOT SAY: a [hc*n] gain fits both a grouped norm
* (hc rsqrts) and a flat one (a single rsqrt over the wide row). Both are self-consistent and no
* per-op oracle can tell them apart; the cheap empirical answer is the draft acceptance rate, so
* the choice is carried as a parameter and asked once at declare.
*
* ============================== IT IS A GEMM AND IS RUN AS ONE ==============================
*
* libref computes this token by token, converting `fc_h` and `fc_e` out of their stored dtype
* inside the innermost loop -- so an [n, n] weight is converted `rows * hc` times. Restructured
* here as what it is: the norms are materialised into a PANEL first ([rows*hc, n] for the hidden
* half, [rows, n] for the embedding), and then the loop runs over the OUTPUT COLUMN i, packing
* `fc_h` row i and `fc_e` row i once and contracting them against every panel row.
*
* That is the same choice avx_gemm.cpp makes and for the same reason -- but note what it does NOT
* do: it does not pre-widen the whole [n, n] weight, which at n = 2560 would be 26 MiB per matrix.
* One row at a time, thread-local, is bounded by n floats and the weight is still read exactly
* once. The panel is the thing that had to be materialised, and it is rows*hc*n -- 328 KiB on a
* draft round, which is what this op is for.
*/
AVX_KERNEL(mtp_enter) {
if (!rad_args_have(a, 7)) return RAD_E_INVAL;
const RadTensor* h = &a->t[0];
const RadTensor* e = &a->t[1];
const RadTensor* w_h = &a->t[2];
const RadTensor* w_e = &a->t[3];
const RadTensor* fc_h = &a->t[4];
const RadTensor* fc_e = &a->t[5];
const RadTensor* x = &a->t[6];
const int64_t n = p_int(a, "n", 0);
const int64_t hc = p_int(a, "hc", 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
const int64_t ngroup = p_int(a, "ngroup", hc);
if (n <= 0 || hc <= 1) return RAD_E_SHAPE;
if (ngroup != 1 && ngroup != hc) return RAD_E_SHAPE;
const int64_t hn = hc * n;
const int64_t rows = numel(h) / hn;
if (rows <= 0 || numel(e) < rows * n || numel(x) < rows * hn) return RAD_E_SHAPE;
if (numel(w_h) < hn || numel(w_e) < n) return RAD_E_SHAPE;
if (numel(fc_h) < n * n || numel(fc_e) < n * n) return RAD_E_SHAPE;
auto pad = [](size_t v) { return (v + 15) & ~(size_t)15; };
const size_t o_gh = 0;
const size_t o_ge = pad(o_gh + (size_t)hn);
const size_t o_nh = pad(o_ge + (size_t)n);
const size_t o_ne = pad(o_nh + (size_t)rows * (size_t)hn);
const size_t total = o_ne + (size_t)rows * (size_t)n + 16;
float* blk = (float*)scratch_raw(total * sizeof(float));
float* gh = blk + o_gh;
float* ge = blk + o_ge;
float* nh = blk + o_nh; /* [rows * hc, n] */
float* ne = blk + o_ne; /* [rows, n] */
{
const int64_t whs = laststride(w_h), wes = laststride(w_e);
if (whs == 1) row_to_f32(w_h->dtype, w_h->data, gh, hn);
else for (int64_t i = 0; i < hn; ++i) gh[i] = ldt(w_h, i * whs);
if (wes == 1) row_to_f32(w_e->dtype, w_e->data, ge, n);
else for (int64_t i = 0; i < n; ++i) ge[i] = ldt(w_e, i * wes);
if (wadd != 0.0f) {
for (int64_t i = 0; i < hn; ++i) gh[i] += wadd;
for (int64_t i = 0; i < n; ++i) ge[i] += wadd;
}
}
/* Phase one: the two norms, into the panel. Both are rounded to their source tensor's dtype,
* which is what `.type_as(x)` does in the reference model and what the products then read. */
AVX_PARALLEL_FOR_IF(rows * hn >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* buf = scratch_f32((size_t)hn);
float* tmp = scratch_f32_b((size_t)hn);
const float* ev = in_row(e, rowoff(e, r, n), n, buf);
const float rse = rsqrt_meansq_f64(ev, n, eps);
float* dst_e = ne + r * n;
for (int64_t i = 0; i < n; ++i) dst_e[i] = ev[i] * rse * ge[i];
if (e->dtype != RAD_F32) {
row_from_f32(e->dtype, dst_e, tmp, n);
row_to_f32(e->dtype, tmp, dst_e, n);
}
const float* hv = in_row(h, rowoff(h, r, hn), hn, buf);
const float flat = (ngroup == 1) ? rsqrt_meansq_f64(hv, hn, eps) : 0.0f;
float* dst_h = nh + r * hn;
for (int64_t c = 0; c < hc; ++c) {
const float sc = (ngroup == 1) ? flat : rsqrt_meansq_f64(hv + c * n, n, eps);
for (int64_t i = 0; i < n; ++i)
dst_h[c * n + i] = hv[c * n + i] * sc * gh[c * n + i];
}
if (h->dtype != RAD_F32) {
row_from_f32(h->dtype, dst_h, tmp, hn);
row_to_f32(h->dtype, tmp, dst_h, hn);
}
}
/* Phase two: one output column at a time, so each weight row is widened exactly once. */
const int64_t xs = laststride(x);
AVX_PARALLEL_FOR_IF(rows * hc * n >= AVX_PAR_MIN)
for (int64_t i = 0; i < n; ++i) {
float* fh = scratch_f32((size_t)n);
float* fe = scratch_f32_b((size_t)n);
const int64_t fhb = rowoff(fc_h, i, n), fhs = laststride(fc_h);
const int64_t feb = rowoff(fc_e, i, n), fes = laststride(fc_e);
if (fhs == 1) row_to_f32(fc_h->dtype, byte_at(fc_h->data, fc_h->dtype, fhb), fh, n);
else for (int64_t j = 0; j < n; ++j) fh[j] = ldt(fc_h, fhb + j * fhs);
if (fes == 1) row_to_f32(fc_e->dtype, byte_at(fc_e->data, fc_e->dtype, feb), fe, n);
else for (int64_t j = 0; j < n; ++j) fe[j] = ldt(fc_e, feb + j * fes);
for (int64_t r = 0; r < rows; ++r) {
const float fev = dotf(fe, ne + r * n, n);
const int64_t xb = rowoff(x, r, hn);
for (int64_t c = 0; c < hc; ++c)
stt(x, xb + (c * n + i) * xs, dotf(fh, nh + r * hn + c * n, n) + fev);
}
}
return RAD_OK;
}
+140
View File
@@ -0,0 +1,140 @@
/* avx_isa.h -- what this machine can execute, and the one list of ops the whole plugin is built
* around.
*
* ============================== WHY A DISPATCH AT ALL ==============================
*
* A kernel plugin is a shared object the engine dlopens (spec.md §2). It is shipped, copied,
* copied and run on machines nobody compiled it on, so `-march=native` is not an option here even
* though it is the obvious one: a binary built with it on an AVX-512 part SIGILLs on the first
* vmovdqu64 anywhere older, and the failure is a signal rather than a diagnostic. The
* alternative -- compile everything baseline -- gives up most of the machine: an AVX-512 rmsnorm
* moves 64 bytes a cycle where the SSE2 one moves 16.
*
* So: the kernels are compiled ONCE PER ISA LEVEL into separate objects, each with its own
* -m flags, and ONE baseline-compiled translation unit (avx_dispatch.cpp) picks between them at
* load. Nothing outside those per-level objects may contain an instruction above the baseline,
* which is why the dispatcher, the registry and the schemas are all in files with no -m flags on
* them: a single stray intrinsic in the registry would fault before the dispatch ever ran.
*
* ============================== THE FOUR LEVELS ==============================
*
* AVX_LEVEL_SCALAR (0) x86-64 baseline. SSE2 exists on every x86-64 and the compiler uses it
* for scalar float, but nothing here is hand-vectorised. ALWAYS CORRECT,
* always selectable, and the answer every other level is checked against.
* AVX_LEVEL_AVX (1) AVX. 256-bit FLOAT only -- Sandy/Ivy Bridge have no 256-bit integer
* ALU and no FMA, so the bf16<->f32 conversions in avx_vec.h split into
* two 128-bit halves and every a*b+c is a separate mul and add.
* AVX_LEVEL_AVX2 (2) AVX2 + FMA + F16C. 256-bit integer, vpermd/vpgatherdd, hardware f16.
* This is the level almost every x86 machine made since 2013 runs.
* AVX_LEVEL_AVX512 (3) AVX-512 F/BW/DQ/VL. 512-bit, and -- what actually matters more than the
* width -- 32 architectural vector registers instead of 16, which is what
* lets the GEMM microkernel hold a 12x2 accumulator block in registers,
* and write masks, which remove the scalar tail loop from every op.
*
* AVX-512 IS NOT ONE FEATURE and the check has to be the conjunction: a Knights Landing has F but
* not BW/DQ/VL, and a kernel that tested `avx512f` alone and then used a byte shuffle would fault
* on it. __builtin_cpu_supports is used rather than raw CPUID because it also consults XGETBV --
* a CPU may enumerate AVX-512 while the OS has not enabled the ZMM state, and using it then
* faults. Missing that check is the single most common way a hand-rolled CPUID dispatch is wrong.
*
* ============================== THE OP LIST IS A MACRO ==============================
*
* AVX_OP_LIST below is the only place the op set is written down. It generates the dispatch table
* struct, the four extern table declarations, the baseline thunks the registry rows point at, and
* the harness's op enumeration. Adding an op means adding one line here and one definition per
* level; forgetting either is a link error rather than a row that silently resolves to null.
* libref uses the same technique for its shape hooks (`fn ## _shape`, libref/ref_ops.h).
*/
#ifndef RAD_AVX_ISA_H
#define RAD_AVX_ISA_H
#include "rad_abi.h"
#ifdef __cplusplus
extern "C" {
#endif
enum {
AVX_LEVEL_SCALAR = 0,
AVX_LEVEL_AVX = 1,
AVX_LEVEL_AVX2 = 2,
AVX_LEVEL_AVX512 = 3,
AVX_N_LEVELS = 4
};
/* The highest level this CPU can execute, computed once. Safe to call before rad_plugin_open. */
int avx_isa_detect(void);
/* The level currently selected. Defaults to avx_isa_detect(). */
int avx_isa_level(void);
const char* avx_isa_name(int level);
/* FORCE A LEVEL, FOR THE CHECKER AND FOR NOTHING ELSE.
*
* It is an exported C symbol rather than an environment variable on purpose: this project's rule
* is that an env switch that changes what a kernel computes is exactly the defect that makes "what
* actually ran" unanswerable, and the engine must never be able to reach this. A symbol the test
* binary dlsym's cannot be set by accident in a deployment and does not appear in a shell
* history. Returns the level actually selected, which is
* min(requested, detected) -- asking for a level the machine cannot execute is clamped rather than
* honoured, because honouring it means SIGILL. */
int avx_isa_force(int level);
/* ================================================================== the op list
* X(name) -- `name` is both the op name in the conventional vocabulary (docs/OPS.md) and the
* suffix of every implementation symbol: avx_<name>_sc / _v1 / _v2 / _v3. */
#define AVX_OP_LIST(X) \
/* ---- elementwise and norms */ \
X(rmsnorm) X(rmsnorm_add) X(hc_enter) X(hc_read) \
X(hc_write) X(mtp_enter) X(layernorm) X(add) \
X(grid_embed) \
X(mul) X(silu_mul) X(gelu) X(silu) \
X(sigmoid) X(gather_rows) X(scatter_rows) X(ngram_ids) \
X(ple_gate) X(ple_conv) X(cast) X(softmax) \
X(scale_rows) \
/* ---- quantisation and rotation */ \
X(quant_act_i8) X(had_quant_act_i8) X(quant_act_fp8) X(had_quant_act_fp8) \
X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) X(dequant) \
X(rmsnorm_quant_fp8) X(gated_quant_fp8) \
/* ---- gemm and the vocabulary edges */ \
X(gemm_nt) X(gemm_nt_bias) X(gemm_nt_q) X(gemm_nt_q_bias) \
X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \
/* ---- attention */ \
X(attn_paged) X(attn_dense) X(kv_store) X(rope) \
X(rope_table) X(qk_norm_rope) \
/* ---- mixture of experts */ \
X(router_topk) X(moe_scatter) X(moe_gemm) X(moe_gemm_q) \
X(moe_gather) X(row_topk) X(row_topk_merge) X(logit_rerank) \
/* ---- gated delta net */ \
X(gdn_conv_prep) X(gdn_conv_update) X(gdn_kkt_solve) X(gdn_chunk_scan) \
X(gdn_recurrent_update) X(gdn_conv_recurrent_update) X(gdn_gated_rmsnorm) \
/* ---- collectives */ \
X(all_reduce) X(all_gather) \
/* ---- sampling, and the drafter's token walk */ \
X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \
X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \
X(sample_merge_topk) X(sample_mask) X(sample_pick) X(sample_argmax) \
X(dflash_select)
/* The table one ISA level fills. One member per op, same order as AVX_OP_LIST. A missing
* definition is a link error against the level's own table definition in avx_table.cpp. */
typedef struct AvxKernelTable {
#define AVX_DECL_MEMBER(nm) int (*nm)(const RadArgs*, RadStream);
AVX_OP_LIST(AVX_DECL_MEMBER)
#undef AVX_DECL_MEMBER
} AvxKernelTable;
/* One per level, defined in the level's own object. The dispatcher picks one. */
extern const AvxKernelTable avx_table_sc;
extern const AvxKernelTable avx_table_v1;
extern const AvxKernelTable avx_table_v2;
extern const AvxKernelTable avx_table_v3;
/* The table for a level, or the scalar table if that level was not built. */
const AvxKernelTable* avx_table_for(int level);
/* The live table -- what the thunks call. Repointed by avx_isa_force. */
const AvxKernelTable* avx_table_live(void);
#ifdef __cplusplus
}
#endif
#endif /* RAD_AVX_ISA_H */
+546
View File
@@ -0,0 +1,546 @@
/* avx_misc.cpp -- the PLE pair, the hashed n-gram ids, and the two collectives.
*
* Grouped because none of them is a vector kernel and the reason differs in each case, which is
* worth saying rather than leaving as an absence:
*
* ple_gate IS vectorised, in the two places that carry the work -- the per-stream norms and the
* gated broadcast of `v`. What is not is the dot between the two normed streams, which is
* accumulated in f64 because libref accumulates it in f64 and this is the one op where that
* choice is visible: the dot feeds a SIGNED SQUARE ROOT, which has unbounded relative sensitivity
* near zero, so an f32 reduction of a 10240-wide product would move the gate by more than the
* tolerance on exactly the rows where the gate is near its hinge.
*
* ple_conv is a depthwise convolution of width 4 over a channel, which is 4 multiplies per
* output element with the taps `dilation` apart. The channel loop is the parallel axis and the
* inner one is four terms; there is no vector work in it that the outer parallelism does not
* already have. What it gets instead is the rolling-window rule written out exactly.
*
* ngram_ids is INTEGER HASHING with a data-dependent early cut, and its arithmetic is defined by
* torch's -- a wrapping 64-bit multiply and a FLOORING modulo, neither of which is C's. There is
* nothing here to vectorise and a great deal to get exactly right.
*
* all_reduce / all_gather serve WORLD SIZE 1 and refuse anything wider by name. See the note on
* the collectives below; it is a deliberate limit, not an omission.
*/
#include "avx_vec.h"
#include "avx_common.h"
using namespace avx;
static inline float narrow1(uint32_t dt, float v) {
uint32_t buf[2] = { 0, 0 };
rad_store_f32(buf, dt, 0, v);
return rad_load_f32(buf, dt, 0);
}
/* One group's reciprocal RMS over `n` contiguous f32. f64 accumulation, matching libref's
* `group_rsqrt`: the rsqrt is per n-wide stream while the gain below it spans all hc*n, and that
* asymmetry is the whole of what `group_size` means on Qwen4ExpTextRMSNorm. */
static float group_rsqrt_f64(const float* v, int64_t n, float eps) {
double acc = 0;
for (int64_t d = 0; d < n; ++d) acc += (double)v[d] * (double)v[d];
return (float)(1.0 / std::sqrt(acc / (double)n + (double)eps));
}
/* ------------------------------------------------------------------ ple_gate */
/* k [M][hc*n] key_proj(embedding), UN-normed
* q [M][hc*n] the incoming hyper-connection stream, UN-normed
* v [M][n] value_proj(embedding) -- ONE row, gated differently per stream
* w_key / w_query / w_conv [hc*n] gains
* gv [M][hc*n] out, UN-normed: what the residual add reads
* gvn [M][hc*n] out, normed: what the convolution reads
*
* THE THIRD NORM IS TAKEN OVER WHAT THIS OP ITSELF WROTE, and it is READ BACK rather than carried
* in registers -- which is why the op owns all three norms instead of the graph owning the last
* one. Splitting it would make two definitions of the same rounding.
*
* THE SIGNED SQUARE ROOT IS IN THE REFERENCE'S ORDER: the magnitude is clamped to `gate_eps`, the
* root is taken of the clamped magnitude, and the sign is reapplied afterwards. Clamping after the
* root, or taking the root of the signed value, are both different functions near zero and the
* gate spends its life near zero. */
AVX_KERNEL(ple_gate) {
if (!rad_args_have(a, 8)) return RAD_E_INVAL;
const RadTensor* k = &a->t[0];
const RadTensor* q = &a->t[1];
const RadTensor* v = &a->t[2];
const RadTensor* wk = &a->t[3];
const RadTensor* wq = &a->t[4];
const RadTensor* wc = &a->t[5];
const RadTensor* gv = &a->t[6];
const RadTensor* gvn = &a->t[7];
const int64_t n = p_int(a, "n", 0);
/* `v` is [M, n] and it is the call; `M` is the band. */
const int64_t M = n > 0 ? band_rows(numel(v) / n, p_int(a, "M", 0)) : 0;
const int64_t hc = p_int(a, "hc", 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
/* The floor the gate's magnitude is clamped to before the square root. */
const float geps = p_f32(a, "gate_eps", 1e-6f);
if (M <= 0 || n <= 0 || hc <= 0) return RAD_E_SHAPE;
const int64_t hn = hc * n;
if (numel(k) < M * hn || numel(q) < M * hn || numel(v) < M * n) return RAD_E_SHAPE;
if (numel(wk) < hn || numel(wq) < hn || numel(wc) < hn) return RAD_E_SHAPE;
if (numel(gv) < M * hn || numel(gvn) < M * hn) return RAD_E_SHAPE;
/* The three gains, widened once with `wadd` folded in. One allocation -- the arena grows, so a
* second scratch_raw would free this one under the worker threads. */
float* gains = (float*)scratch_raw((size_t)(3 * hn) * sizeof(float) + 64);
float* gk = gains;
float* gq = gains + hn;
float* gc = gains + 2 * hn;
{
const int64_t sk = laststride(wk), sq = laststride(wq), sc = laststride(wc);
for (int64_t i = 0; i < hn; ++i) {
gk[i] = ldt(wk, i * sk) + wadd;
gq[i] = ldt(wq, i * sq) + wadd;
gc[i] = ldt(wc, i * sc) + wadd;
}
}
const int64_t gls = laststride(gv), gnls = laststride(gvn);
AVX_PARALLEL_FOR_IF(M >= 2)
for (int64_t m = 0; m < M; ++m) {
const int64_t kb = rowoff(k, m, hn), qb = rowoff(q, m, hn), vb = rowoff(v, m, n);
const int64_t gb = rowoff(gv, m, hn), nb = rowoff(gvn, m, hn);
float* kv = scratch_f32((size_t)hn);
float* qv = scratch_f32_b((size_t)hn);
float* out = scratch_f32_c((size_t)(hn + n) + 16);
float* vv = out + hn + 8;
const float* kk = in_row(k, kb, hn, kv);
const float* qq = in_row(q, qb, hn, qv);
const float* v0 = in_row(v, vb, n, vv);
if (v0 != vv) std::memcpy(vv, v0, (size_t)n * sizeof(float));
for (int64_t c = 0; c < hc; ++c) {
const float rk = group_rsqrt_f64(kk + c * n, n, eps);
const float rq = group_rsqrt_f64(qq + c * n, n, eps);
/* f64, and see the file header: the dot feeds a signed square root whose relative
* sensitivity is unbounded near zero. */
double dot = 0;
for (int64_t d = 0; d < n; ++d) {
const int64_t j = c * n + d;
const float a1 = narrow1(k->dtype, kk[j] * rk * gk[j]);
const float b1 = narrow1(q->dtype, qq[j] * rq * gq[j]);
dot += (double)a1 * (double)b1;
}
float s = (float)(dot / std::sqrt((double)n));
const float mag = std::sqrt(std::fabs(s) < geps ? geps : std::fabs(s));
s = s > 0.0f ? mag : (s < 0.0f ? -mag : 0.0f);
const float g = 1.0f / (1.0f + std::exp(-s));
const vf vg = vf_set1(g);
int64_t d = 0;
for (; d + VF_N <= n; d += VF_N)
vf_storeu(out + c * n + d, vf_mul(vg, vf_loadu(vv + d)));
for (; d < n; ++d) out[c * n + d] = g * vv[d];
}
if (gls == 1) out_row(gv, gb, hn, out);
else for (int64_t j = 0; j < hn; ++j) stt(gv, gb + j * gls, out[j]);
/* The third norm, over what was just written -- read BACK through gv's dtype, not carried
* in registers. The round trip is done here rather than by re-reading the operand: same
* arithmetic, and it does not depend on the store having retired. */
if (gv->dtype != RAD_F32) {
row_from_f32(gv->dtype, out, kv, hn);
row_to_f32(gv->dtype, kv, out, hn);
}
for (int64_t c = 0; c < hc; ++c) {
const float r = group_rsqrt_f64(out + c * n, n, eps);
for (int64_t d = 0; d < n; ++d) {
const int64_t j = c * n + d;
qv[j] = narrow1(gvn->dtype, out[j] * r * gc[j]);
}
}
if (gnls == 1) out_row(gvn, nb, hn, qv);
else for (int64_t j = 0; j < hn; ++j) stt(gvn, nb + j * gnls, qv[j]);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ ple_conv */
/* PLE's dilated depthwise convolution, silu AFTER it, and the residual add folded in.
*
* TWO RULES THAT ARE NOT DERIVABLE AND ARE BOTH SILENT WHEN WRONG:
*
* A ZERO `has_init` MEANS THE SLOT HOLDS NO HISTORY -- the window in front of the first token is
* ZEROS, not whatever the slot last held. Without it a fresh sequence landing on a recycled slot
* convolves the previous sequence's tail into its first `(width-1)*dilation` tokens: fluent
* output with the wrong prefix.
*
* `num_accepted` SHIFTS THE READ AND ITS PRESENCE PICKS THE WINDOW LEFT BEHIND -- libref's
* ref_ple.cpp states the contract in full. Present, the step is a decode step whose drafts a
* verify may reject: the history read is shifted down by one and every input of the step follows
* it, so a next step that kept k tokens reads at k - 1 and finds the history ending at the k-th.
* Absent, every token commits and the last (width-1)*dilation inputs land at offset zero. The
* write happens in a SECOND pass after every read is done, because a sequence longer than the
* window would otherwise overwrite history it is still reading. */
AVX_KERNEL(ple_conv) {
if (a->n_t < 9) return RAD_E_INVAL;
const RadTensor* x = rad_arg_in(a, 0);
const RadTensor* w = rad_arg_in(a, 1);
const RadTensor* cs = rad_arg_in(a, 2);
const RadTensor* cu = rad_arg_in(a, 3);
const RadTensor* resid = rad_arg_in(a, 4);
const RadTensor* sidx = rad_arg_in(a, 5);
const RadTensor* hini = rad_arg_in(a, 6);
const RadTensor* nacc = rad_arg_in(a, 7);
const RadTensor* y = rad_arg_in(a, 8);
if (!x || !w || !cs || !cu || !y) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0);
/* `x` is [M, n] and it is the call; `M` is the band. */
const int64_t M = n > 0 ? band_rows(numel(x) / n, p_int(a, "M", 0)) : 0;
const int64_t wid = p_int(a, "width", 0);
const int64_t dil = p_int(a, "dilation", 1);
if (M <= 0 || n <= 0 || wid <= 0 || dil <= 0) return RAD_E_SHAPE;
const int64_t hist_len = (wid - 1) * dil;
/* The read window lives in a stack frame. Nine at this model's shape; the bound is stated so a
* wider one is refused by name rather than overflowing. Same number as libref's. */
enum { kHistMax = 64 };
if (hist_len > kHistMax) return RAD_E_UNSUPPORTED;
const int64_t N = numel(cu) - 1;
if (N <= 0) return RAD_E_SHAPE;
if (numel(x) < M * n || numel(y) < M * n || numel(w) < n * wid) return RAD_E_SHAPE;
if (resid && numel(resid) < M * n) return RAD_E_SHAPE;
const int64_t state_len = cs->rank >= 3 ? cs->shape[cs->rank - 1] : hist_len;
if (cs->data && state_len < hist_len) return RAD_E_SHAPE;
/* Checked for every sequence BEFORE any of them is written: a state too shallow for the offset,
* or for the window a decode step leaves behind, is a caller error, and an OpenMP body cannot
* return. */
for (int64_t s = 0; s < N; ++s) {
const int64_t off = nacc ? ldi(nacc, offlin(nacc, s)) - 1 : 0;
if (off < 0) return RAD_E_INVAL;
if (off + hist_len > state_len) return RAD_E_SHAPE;
const int64_t slen = ldi(cu, offlin(cu, s + 1)) - ldi(cu, offlin(cu, s));
if (nacc && cs->data && hist_len > 0 && slen > 0 && hist_len - 1 + slen > state_len)
return RAD_E_SHAPE;
}
const int64_t xrow = rowoff(x, 1, n), xcol = laststride(x);
const int64_t yrow = rowoff(y, 1, n), ycol = laststride(y);
const int64_t rrow = resid ? rowoff(resid, 1, n) : 0;
const int64_t rcol = resid ? laststride(resid) : 0;
const int64_t wrow = rowoff(w, 1, wid), wcol = laststride(w);
/* [n_slots, n, state_len], tight -- the layout gdn's conv state already uses. */
const int64_t cs_slot = n * state_len, cs_ch = state_len;
AVX_PARALLEL_FOR_IF(N * n >= 64)
for (int64_t sc = 0; sc < N * n; ++sc) {
const int64_t s = sc / n, c = sc % n;
const int64_t bos = ldi(cu, offlin(cu, s));
const int64_t slen = ldi(cu, offlin(cu, s + 1)) - bos;
if (slen <= 0) continue;
const int64_t slot = sidx ? ldi(sidx, offlin(sidx, s)) : s;
if (slot < 0) continue;
const bool warm = !hini || ldi(hini, offlin(hini, s)) != 0;
const int64_t off = nacc ? ldi(nacc, offlin(nacc, s)) - 1 : 0;
float hist[kHistMax];
for (int64_t i = 0; i < hist_len; ++i)
hist[i] = (warm && cs->data) ? ldt(cs, slot * cs_slot + c * cs_ch + off + i) : 0.0f;
/* The taps, read once per channel rather than per output element -- libref reads them
* through `ldt` inside the t loop, which is `slen * width` dtype switches for `width`
* distinct values. In scratch rather than a stack array so `width` carries no bound of its
* own: the only limit this op has is the read window's, stated above. */
float* tap = scratch_f32((size_t)wid);
for (int64_t j = 0; j < wid; ++j) tap[j] = ldt(w, c * wrow + j * wcol);
for (int64_t t = 0; t < slen; ++t) {
float acc = 0.0f;
for (int64_t j = 0; j < wid; ++j) {
const int64_t src = t - hist_len + j * dil;
const float vv = src >= 0 ? ldt(x, (bos + src) * xrow + c * xcol)
: hist[src + hist_len];
acc += vv * tap[j];
}
const float r = resid ? ldt(resid, (bos + t) * rrow + c * rcol) : 0.0f;
stt(y, (bos + t) * yrow + c * ycol, r + acc / (1.0f + std::exp(-acc)));
}
}
if (cs->data && hist_len > 0) {
AVX_PARALLEL_FOR_IF(N * n >= 64)
for (int64_t sc = 0; sc < N * n; ++sc) {
const int64_t s = sc / n, c = sc % n;
const int64_t bos = ldi(cu, offlin(cu, s));
const int64_t slen = ldi(cu, offlin(cu, s + 1)) - bos;
if (slen <= 0) continue;
const int64_t slot = sidx ? ldi(sidx, offlin(sidx, s)) : s;
if (slot < 0) continue;
const bool warm = !hini || ldi(hini, offlin(hini, s)) != 0;
const int64_t off = nacc ? ldi(nacc, offlin(nacc, s)) - 1 : 0;
const int64_t base = slot * cs_slot + c * cs_ch;
float win[kHistMax];
for (int64_t i = 0; i < hist_len; ++i) win[i] = warm ? ldt(cs, base + off + i) : 0.0f;
if (nacc) {
for (int64_t i = 0; i + 1 < hist_len; ++i) stt(cs, base + i, win[i + 1]);
for (int64_t t = 0; t < slen; ++t)
stt(cs, base + hist_len - 1 + t, ldt(x, (bos + t) * xrow + c * xcol));
} else {
float keep[kHistMax];
for (int64_t i = 0; i < hist_len; ++i) {
const int64_t src = slen - hist_len + i;
keep[i] = src >= 0 ? ldt(x, (bos + src) * xrow + c * xcol)
: win[src + hist_len];
}
for (int64_t i = 0; i < hist_len; ++i) stt(cs, base + i, keep[i]);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ ngram_ids
*
* ids[m][h] = (hash of the n-gram ending at m) % vocab[h] + offset[h].
*
* THE ARITHMETIC IS TORCH'S, NOT C's, and both differences bite:
*
* A SIGNED OVERFLOW IS UB IN C++ AND WRAPPING IN TORCH, so the multiply goes through uint64 and
* comes back -- two's complement, which is what an int64 tensor does on every machine this runs
* on.
*
* `torch.remainder` FLOORS WHERE C TRUNCATES, so the modulo is written out rather than left to
* `%`.
*
* On a real checkpoint neither can fire -- the multiplier build bounds every multiplier by
* (2^63-1)//vocab_size, so a real token's product has its sign bit clear and truncating and
* flooring agree on a non-negative dividend. They are here so that a DRAWN case, whose indices no
* vocabulary bounds, gets torch's answer rather than a platform's.
*
* THE EOS RULE IS COLLAPSED: once a shift falls off the front of the sequence, every longer shift
* is EOS too, so the cut is carried rather than re-tested. A COLD slot's window is EOS and not
* zero, because zero is a real token. */
static inline int64_t wrap_mul(int64_t x, int64_t y) {
return (int64_t)((uint64_t)x * (uint64_t)y);
}
static inline int64_t floor_mod(int64_t x, int64_t y) { /* y > 0 */
const int64_t r = x % y;
return r < 0 ? r + y : r;
}
AVX_KERNEL(ngram_ids) {
if (a->n_t < 10) return RAD_E_INVAL;
const RadTensor* tok = rad_arg_in(a, 0);
const RadTensor* st = rad_arg_in(a, 1);
const RadTensor* cu = rad_arg_in(a, 2);
const RadTensor* mult = rad_arg_in(a, 3);
const RadTensor* vsz = rad_arg_in(a, 4);
const RadTensor* off_ = rad_arg_in(a, 5);
const RadTensor* sidx = rad_arg_in(a, 6);
const RadTensor* hini = rad_arg_in(a, 7);
const RadTensor* nacc = rad_arg_in(a, 8);
const RadTensor* ids = rad_arg_in(a, 9);
/* THE PROMPT THAT FOLLOWS, optional: `tok` holds its row count more tokens after the step's,
* continuing the LAST sequence, and their ids go here. The window is the step's own. */
const RadTensor* ahead = a->n_t > 10 ? rad_arg_in(a, 10) : nullptr;
if (!tok || !st || !cu || !mult || !vsz || !off_ || !ids) return RAD_E_INVAL;
const int64_t heads = p_int(a, "heads", 0);
if (heads <= 0) return RAD_E_SHAPE;
/* The token vector is the call and the prompt that follows it; `M` is the band. */
const int64_t A = ahead ? numel(ahead) / heads : 0;
const int64_t M = band_rows(numel(tok) - A, p_int(a, "M", 0));
const int64_t ngram = p_int(a, "ngram", 0);
const int64_t eos = p_int(a, "eos", -1);
if (M <= 0 || heads <= 0 || ngram < 2 || eos < 0) return RAD_E_SHAPE;
/* Heads are `ngram - 1` blocks of `heads_per_ngram`, block b using the (b+2)-gram. */
if (heads % (ngram - 1)) return RAD_E_SHAPE;
const int64_t per = heads / (ngram - 1);
const int64_t ctx = ngram - 1;
if (ngram > 8) return RAD_E_UNSUPPORTED; /* the shift window lives in a stack frame */
if (numel(mult) < ngram || numel(vsz) < heads || numel(off_) < heads) return RAD_E_SHAPE;
if (numel(tok) < M + A || numel(ids) < M * heads) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1;
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t W = st->rank >= 2 ? st->shape[st->rank - 1] : ctx;
if (W < ctx) return RAD_E_SHAPE;
/* The read window, and the window a decode step leaves behind: `ctx - 1` ids of history plus
* every id of the step. */
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t o = nacc ? ldi(nacc, offlin(nacc, s)) - 1 : 0;
if (o < 0) return RAD_E_INVAL;
if (o + ctx > W) return RAD_E_SHAPE;
const int64_t T = ldi(cu, offlin(cu, s + 1)) - ldi(cu, offlin(cu, s));
if (nacc && T > 0 && ctx - 1 + T > W) return RAD_E_SHAPE;
}
const int64_t ids_ld = rowoff(ids, 1, heads);
const int64_t ahd_ld = ahead ? rowoff(ahead, 1, heads) : 0;
/* The per-head tables, read once. libref reads `vocab_sizes` and `offsets` through ld_int
* inside the innermost loop, which is `M * heads` dtype switches for `heads` distinct values. */
int64_t* tab = (int64_t*)scratch_raw((size_t)(2 * heads + ngram) * sizeof(int64_t) + 64);
int64_t* vtab = tab;
int64_t* otab = tab + heads;
int64_t* mtab = tab + 2 * heads;
for (int64_t h = 0; h < heads; ++h) {
vtab[h] = ldi(vsz, h);
otab[h] = ldi(off_, h);
if (vtab[h] <= 0 || otab[h] < 0) return RAD_E_SHAPE;
}
for (int64_t k = 0; k < ngram; ++k) mtab[k] = ldi(mult, k);
/* Serial over sequences, as libref is: each writes its own state slot, the work per sequence is
* a token loop with a handful of integer ops, and a parallel region over a handful of
* sequences would cost more than it saves. */
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t bos = ldi(cu, offlin(cu, s));
const int64_t eot = ldi(cu, offlin(cu, s + 1));
if (bos < 0 || eot < bos || eot > M) return RAD_E_SHAPE;
const int64_t T = eot - bos;
if (T <= 0) continue;
const int64_t slot = sidx ? ldi(sidx, offlin(sidx, s)) : s;
if (slot < 0) continue;
const bool warm = !hini || ldi(hini, offlin(hini, s)) != 0;
const int64_t o = nacc ? ldi(nacc, offlin(nacc, s)) - 1 : 0;
int64_t prev[8];
for (int64_t i = 0; i < ctx; ++i)
prev[i] = warm ? ldi(st, rowoff(st, slot, W) + o + i) : eos;
auto hist = [&](int64_t p) -> int64_t {
return p < ctx ? prev[p] : ldi(tok, offlin(tok, bos + p - ctx));
};
const int64_t reach = T + (ahead && s + 1 == n_seq ? A : 0);
for (int64_t t = 0; t < reach; ++t) {
const int64_t p = ctx + t;
int64_t sh[8];
sh[0] = hist(p);
bool cut = false;
for (int64_t k = 1; k < ngram; ++k) {
if (cut || sh[k - 1] == eos) { cut = true; sh[k] = eos; continue; }
sh[k] = hist(p - k);
}
/* One mix per n-gram order, EXTENDED IN PLACE: the (b+2)-gram's mix is the
* (b+1)-gram's XOR'd with one more term, which saves recomputing the shared prefix. */
int64_t mixed = 0;
int64_t blk = -1;
for (int64_t k = 0; k < ngram; ++k) {
const int64_t term = wrap_mul(sh[k], mtab[k]);
mixed = k == 0 ? term : (mixed ^ term);
if (k == 0) continue; /* a 1-gram addresses no head */
++blk; /* k = 1 is the 2-gram block, k = 2 the 3-gram */
for (int64_t j = 0; j < per; ++j) {
const int64_t h = blk * per + j;
if (t < T)
st_int_dt(ids->dtype, ids->data, (bos + t) * ids_ld + h,
floor_mod(mixed, vtab[h]) + otab[h]);
else
st_int_dt(ahead->dtype, ahead->data, (t - T) * ahd_ld + h,
floor_mod(mixed, vtab[h]) + otab[h]);
}
}
}
/* The window this step leaves behind, written after every read of it is done, in the
* layout ple_conv's state follows: shifted by one with every id of the step behind it when
* `num_accepted` is present, the last `ctx` ids at offset zero when it is not. */
const int64_t base = rowoff(st, slot, W);
if (nacc) {
for (int64_t i = 0; i + 1 < ctx; ++i)
st_int_dt(st->dtype, st->data, base + i, prev[i + 1]);
for (int64_t t = 0; t < T; ++t)
st_int_dt(st->dtype, st->data, base + ctx - 1 + t, ldi(tok, offlin(tok, bos + t)));
} else {
for (int64_t i = 0; i < ctx; ++i) {
const int64_t src = T - ctx + i;
const int64_t vv = src >= 0 ? ldi(tok, offlin(tok, bos + src)) : prev[src + ctx];
st_int_dt(st->dtype, st->data, base + i, vv);
}
}
}
return RAD_OK;
}
/* ================================================================== the collectives
*
* WORLD SIZE 1 ONLY, AND THAT IS A DELIBERATE LIMIT RATHER THAN AN OMISSION.
*
* libref implements the real thing, and it can because of how this engine is shaped: one process,
* one thread per rank, one address space, so a peer's buffer is a POINTER and the whole collective
* is a rendezvous, a read of every rank's pointer, and a second rendezvous before anyone
* overwrites theirs. That makes the host backend a fake multi-device backend, which is genuinely
* useful -- the sharded declare, the collective placement and the distributed top-k can all be
* exercised on a box with no second card.
*
* It is also a piece of SHARED MUTABLE STATE with a barrier, a generation counter and a timeout,
* and there is exactly one of it per process. Two kernel plugins each carrying their own would be
* two rendezvous groups for one world, and which one a rank joined would depend on which plugin
* won selection for that op -- a deadlock that appears only when the hierarchy changes. A CPU
* kernel library has no business owning the wire; libref already owns it and sits below this
* plugin in the hierarchy, so a tensor-parallel host deployment resolves the collectives there and
* everything else here.
*
* So: at world 1 both are the degenerate case and are served exactly. Above 1 this refuses by name
* with RAD_E_UNSUPPORTED, which makes the selector fall through to libref's row rather than
* producing a wrong sum.
*
* `exact` IS HONOURED IN ONE DIRECTION ONLY, as libref does: exact=1 gets the exact sum, and
* exact=0 -- a caller that has declared it will accept a lossy quantised wire -- ALSO gets the
* exact sum, because there is no wire here to quantise. Serving a lossy request exactly is safe;
* the constraint exists so a caller who wanted exactness cannot be handed a lossy result by
* accident, not the reverse. */
AVX_KERNEL(all_reduce) {
if (!rad_args_have(a, 1)) return RAD_E_INVAL;
const RadTensor* x = &a->t[0];
const RadTensor* y = rad_arg_in(a, 1);
/* The message is the operand; `numel` is the band. */
const int64_t nel = band_rows(numel(x), p_int(a, "numel", 0));
if (nel <= 0) return RAD_E_SHAPE;
if (y && numel(y) < nel) return RAD_E_SHAPE;
const int world = (int)p_int(a, "world_size", a->world_size > 0 ? a->world_size : 1);
if (world > 1) return RAD_E_UNSUPPORTED;
/* In place: the answer is already there. With a separate destination it still has to be COPIED
* there, because a caller that passed one reads it and not x. */
if (!y) return RAD_OK;
if (rad_tensor_is_contiguous(x) && rad_tensor_is_contiguous(y)) {
const int64_t TILE = 8192;
for (int64_t off = 0; off < nel; off += TILE) {
const int64_t m = (nel - off) < TILE ? (nel - off) : TILE;
float* s = scratch_f32((size_t)TILE);
out_row(y, off, m, in_row(x, off, m, s));
}
return RAD_OK;
}
for (int64_t i = 0; i < nel; ++i) stt(y, offlin(y, i), ldt(x, offlin(x, i)));
return RAD_OK;
}
AVX_KERNEL(all_gather) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
/* The contribution is the operand; `numel` is the band. */
const int64_t nel = band_rows(numel(x), p_int(a, "numel", 0));
const int world = (int)p_int(a, "world_size", a->world_size > 0 ? a->world_size : 1);
if (nel <= 0 || numel(y) < nel * world) return RAD_E_SHAPE;
if (world > 1) return RAD_E_UNSUPPORTED;
/* THE `row` PLACEMENT DOES NOT MATTER AT WORLD 1 and is still checked, because a caller that
* passes an illegal one at world 1 would get a silent pass here and a refusal at world 2 --
* and the whole value of running a tensor-parallel graph at world 1 is that it is the same
* graph. */
const int64_t row = p_int(a, "row", 0);
if (row < 0 || (row > 0 && nel % row)) return RAD_E_SHAPE;
if (rad_tensor_is_contiguous(x) && rad_tensor_is_contiguous(y) && x->dtype == y->dtype) {
std::memcpy(y->data, x->data, (size_t)((nel * rad_dtype_bits(x->dtype) + 7) / 8));
return RAD_OK;
}
for (int64_t i = 0; i < nel; ++i) stt(y, offlin(y, i), ldt(x, offlin(x, i)));
return RAD_OK;
}
+726
View File
@@ -0,0 +1,726 @@
/* avx_moe.cpp -- routing, the scatter/gather pair, the grouped GEMM, and the exact row top-R.
*
* ============================== WHAT sorted_tok CARRIES ==============================
*
* The FLATTENED (token, slot) index -- token * top_k + slot -- grouped by expert, not the bare
* token id. With the bare id, `moe_gather` would have no way to find which of a token's top_k
* routing weights applies to a row and would have to search. It is also vLLM's
* `sorted_token_ids` convention, so a kernel lifted from there needs no translation.
*
* A slot whose expert id is outside [0, n_expert) is DROPPED: not counted, and the tail from
* expert_offset[n_expert] to M*top_k is filled with -1. A padded batch row has to be expressible.
*
* ============================== THREE ALGORITHMIC CHANGES, NOT JUST VECTORISATION ==============================
*
* This is the file where the reference's asymptotics, rather than its instruction mix, are the
* thing to beat -- so three loops are rewritten rather than widened, and each produces the
* identical answer:
*
* moe_scatter is O(T + n_expert) instead of O(T * n_expert). libref places the rows by looping
* over experts and scanning the whole id array for each one, which is a stable sort and is
* quadratic in the expert count; at 256 experts that is 256 passes over the batch. A single pass
* with a per-expert write cursor is the same stable order -- rows are still appended in
* ascending i within an expert -- for one pass.
*
* moe_gather builds the inverse permutation ONCE, O(T), instead of once per block of tokens.
* libref rebuilds it in blocks into a 4096-entry stack array specifically to avoid allocating,
* and pays (M / block) full passes over sorted_tok for it. The scratch arena removes the reason.
*
* moe_gemm gathers the activation rows into a PANEL per expert and then runs the same
* register-blocked dot product avx_gemm.cpp uses. libref walks output rows and, for each, loops
* over N doing a fresh dot -- which means the expert's weight is re-read from memory once per
* row of that expert. Gathering first makes the weight pass contiguous and shared.
*
* The one thing NOT changed is the ORDER of moe_gather's summation. It is ascending slot j, and
* that is what makes the op reproducible: an implementation that walked the expert-sorted rows
* instead would sum a token's contributions in expert-id order and the two differ in the last bits.
*/
#include "avx_vec.h"
#include "avx_common.h"
#include <algorithm>
#include <cstdlib>
#include <vector>
using namespace avx;
/* ================================================================== operand readings
* avx_gemm.cpp's, and libref/ref_gemm.h's before that. Duplicated here rather than shared through
* a header because these two translation units are compiled four times each and a shared header
* would be a fifth definition to keep in step; the bodies are short and the contract they encode
* is stated where it matters, in avx_gemm.cpp. `row_stride` and `grid_block` are avx_common.h's,
* which every kernel here already shares. */
struct Mat { const RadTensor* t; int64_t rs, cs; };
static inline Mat as_mat(const RadTensor* t, int64_t cols) {
Mat m{ t, cols, 1 };
if (t->rank < 2) return m;
m.cs = t->stride[t->rank - 1];
m.rs = row_stride(t, cols);
return m;
}
struct Scales {
const void* p;
uint32_t dt;
int64_t rs, cs, group, rblk;
inline float grp(int64_t row, int64_t g) const {
return rad_load_f32(p, dt, (rblk > 1 ? row / rblk : row) * rs + g * cs);
}
};
static Scales make_scales(const RadTensor* s, int64_t rows, int64_t K) {
Scales q{};
q.rblk = 1;
if (!s || !s->data || rows <= 0 || numel(s) <= 0) {
q.p = nullptr; q.group = K; q.dt = RAD_F32; return q;
}
q.p = s->data;
q.dt = s->dtype;
int64_t groups = 0;
if (s->rank >= 2) {
const int64_t srows = s->shape[s->rank - 2];
q.rblk = srows >= rows ? 1 : grid_block(rows, srows);
groups = s->shape[s->rank - 1];
q.rs = s->stride[s->rank - 2];
q.cs = s->stride[s->rank - 1];
} else {
const int64_t nel = numel(s);
if (nel >= rows) { groups = nel / rows; q.rs = groups; }
else { groups = 1; q.rblk = grid_block(rows, nel); q.rs = 1; }
q.cs = 1;
}
q.group = grid_block(K, groups);
return q;
}
/* A RAD_OPD_WTAB operand: `data` is a host array of shape[0] pointers, one per expert, and
* stride[0] is 0 to say so. The STACKED form -- a plain rank-3 [n_expert, N, K] with an ordinary
* leading stride -- is accepted too and is what a caller outside the engine hands over, since a
* checker drawing one dense plane has nowhere to put a pointer array. */
static RadTensor expert_entry(const RadTensor* w, int64_t e) {
RadTensor t{};
if (!w || !w->data || w->rank < 2 || e < 0 || e >= w->shape[0]) return t;
t.dtype = w->dtype;
t.rank = w->rank - 1;
for (uint32_t d = 0; d + 1 < w->rank; ++d) {
t.shape[d] = w->shape[d + 1];
t.stride[d] = w->stride[d + 1];
}
if (w->stride[0] == 0) {
void* const* tab = (void* const*)w->data;
t.data = tab[e];
} else {
/* An element offset in a packed dtype can be mid-byte; the stacked form is only ever whole
* planes, so the arithmetic is done in bytes off the leading stride. */
const int64_t bits = rad_dtype_bits(w->dtype);
const int64_t nbits = bits * w->stride[0] * e;
if (bits <= 0 || (nbits & 7)) return t; /* data stays null: unreadable */
t.data = (void*)((const char*)w->data + (nbits >> 3));
}
return t;
}
static void pack_row(const Mat& m, int64_t r, int64_t K, float* dst) {
const RadTensor* t = m.t;
const int64_t base = r * m.rs;
if (m.cs == 1) {
const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1
: (t->dtype == RAD_I2) ? 3 : 0;
if (!sub || (base & sub) == 0) {
row_to_f32(t->dtype, byte_at(t->data, t->dtype, base), dst, K);
return;
}
}
for (int64_t k = 0; k < K; ++k) dst[k] = ld_elem(t->data, t->dtype, base + k * m.cs);
}
static inline float dotf(const float* a, const float* b, int64_t k0, int64_t k1) {
vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero();
int64_t k = k0;
for (; k + 4 * VF_N <= k1; k += 4 * VF_N) {
a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0);
a1 = vf_fma(vf_loadu(a + k + VF_N), vf_loadu(b + k + VF_N), a1);
a2 = vf_fma(vf_loadu(a + k + 2 * VF_N), vf_loadu(b + k + 2 * VF_N), a2);
a3 = vf_fma(vf_loadu(a + k + 3 * VF_N), vf_loadu(b + k + 3 * VF_N), a3);
}
for (; k + VF_N <= k1; k += VF_N) a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0);
float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3)));
for (; k < k1; ++k) s += a[k] * b[k];
return s;
}
/* ------------------------------------------------------------------ router_topk */
/* Softmax over ALL n_expert logits, then the top_k by probability, then -- if `norm` --
* renormalise the kept weights to sum to one. Softmax first and select second is the order
* Mixtral, Qwen3 and every model in this engine's scope use; selecting first and normalising the
* raw logits would be a different router, so the order is part of the op.
*
* The SELECTION runs on the LOGITS, not the probabilities: softmax is monotone, so the order is
* identical and the comparison is exact rather than through an exp. */
AVX_KERNEL(router_topk) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *ids = &a->t[1], *w = &a->t[2];
const int64_t n_expert = p_int(a, "n_expert", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
const int64_t top_k = p_int(a, "top_k", 1);
const int norm = (int)p_int(a, "norm", 0);
if (n_expert <= 0 || top_k <= 0 || top_k > n_expert) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_expert;
if (M <= 0 || numel(ids) < M * top_k || numel(w) < M * top_k) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(M * n_expert >= 1024)
for (int64_t m = 0; m < M; ++m) {
float* buf = scratch_f32((size_t)n_expert);
const float* v = in_row(lg, rowoff(lg, m, n_expert), n_expert, buf);
const float mx = row_max(v, n_expert);
float sum = 0.0f;
for (int64_t e = 0; e < n_expert; ++e) sum += std::exp(v[e] - mx);
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
float pv = INFINITY;
int64_t pi = -1, kept = 0;
float wsum = 0.0f;
for (int64_t r = 0; r < top_k; ++r) {
if (!topk_next_f32(v, n_expert, &pv, &pi)) break;
const float p = std::exp(pv - mx) * inv;
st_int_dt(ids->dtype, ids->data, rowoff(ids, m, top_k) + r * laststride(ids), pi);
stt(w, rowoff(w, m, top_k) + r * laststride(w), p);
wsum += p;
++kept;
}
if (norm && wsum > 0.0f) {
const float n2 = 1.0f / wsum;
for (int64_t r = 0; r < kept; ++r) {
const int64_t off = rowoff(w, m, top_k) + r * laststride(w);
stt(w, off, ldt(w, off) * n2);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ moe_scatter */
/* `protect`: local experts the sort places LAST, in the order listed, the rest closed up -- the
* layout a layer that serves a few experts with a second grouped GEMM needs (libr4d's sort_place).
* Returns false on a list that is not strictly ascending inside [0, n). */
static bool sort_places(const char* s, int64_t n, std::vector<int64_t>* place) {
std::vector<int64_t> prot;
for (const char* c = s ? s : ""; *c;) {
char* end = nullptr;
const long long v = std::strtoll(c, &end, 10);
if (end == c || v < 0 || v >= n || (!prot.empty() && v <= prot.back())) return false;
prot.push_back(v);
c = end;
if (*c == ',') ++c;
else if (*c) return false;
}
place->assign((size_t)n, 0);
int64_t next = 0;
for (int64_t e = 0; e < n; ++e)
if (!std::binary_search(prot.begin(), prot.end(), e)) (*place)[(size_t)e] = next++;
for (size_t j = 0; j < prot.size(); ++j) (*place)[(size_t)prot[j]] = next++;
return true;
}
/* A stable counting sort of the (token, slot) pairs by expert id, in ONE placement pass with a
* per-expert write cursor rather than libref's expert-major rescan. The order is identical: within
* an expert, rows are still appended in ascending i.
*
* Serial on purpose. It is O(T) over a batch's worth of small integers, and a parallel version
* needs a per-thread histogram and a prefix pass to stay stable -- more code than the work it
* saves, and a stability bug there routes a token to a different expert. */
AVX_KERNEL(moe_scatter) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *ids = &a->t[0], *sorted = &a->t[1], *off = &a->t[2], *cnt = &a->t[3];
const int64_t n_expert = p_int(a, "n_expert", 0);
const int64_t top_k = p_int(a, "top_k", 1);
/* THIS RANK'S FIRST EXPERT, subtracted from every routed id so the sort is over local indices
* -- which is what the weight table, the offsets and the GEMM downstream are indexed by. */
const int64_t base = p_int(a, "expert_base", 0);
if (n_expert <= 0 || top_k <= 0 || base < 0) return RAD_E_SHAPE;
const int64_t M = numel(ids) / top_k;
const int64_t T = M * top_k;
if (M <= 0 || numel(sorted) < T) return RAD_E_SHAPE;
if (numel(off) < n_expert + 1 || numel(cnt) < n_expert) return RAD_E_SHAPE;
std::vector<int64_t> place;
if (!sort_places(p_str(a, "protect", nullptr), n_expert, &place)) return RAD_E_SHAPE;
/* A slot's place in the sort, or -1 for an expert outside this call's slice. */
auto at = [&](int64_t i) -> int64_t {
const int64_t e = ldi(ids, offlin(ids, i)) - base;
return (e < 0 || e >= n_expert) ? -1 : place[(size_t)e];
};
int64_t* cur = (int64_t*)scratch_raw((size_t)(n_expert + 1) * sizeof(int64_t));
for (int64_t e = 0; e < n_expert; ++e) cur[e] = 0;
for (int64_t i = 0; i < T; ++i) {
const int64_t e = at(i);
if (e < 0) continue;
++cur[e];
}
for (int64_t e = 0; e < n_expert; ++e)
st_int_dt(cnt->dtype, cnt->data, offlin(cnt, e), cur[e]);
int64_t run = 0;
for (int64_t e = 0; e < n_expert; ++e) {
st_int_dt(off->dtype, off->data, offlin(off, e), run);
const int64_t c = cur[e];
cur[e] = run; /* the cursor becomes the write position */
run += c;
}
st_int_dt(off->dtype, off->data, offlin(off, n_expert), run);
for (int64_t i = run; i < T; ++i)
st_int_dt(sorted->dtype, sorted->data, offlin(sorted, i), -1);
for (int64_t i = 0; i < T; ++i) {
const int64_t e = at(i);
if (e < 0) continue;
st_int_dt(sorted->dtype, sorted->data, offlin(sorted, cur[e]), i);
++cur[e];
}
return RAD_OK;
}
/* ------------------------------------------------------------------ moe_gemm, moe_gemm_q */
/* y[i, :] = a[row(i), :] @ w[e]^T, where e is the expert whose offset range contains i and
* `a_order` picks row(i): `sorted_tok[i] / top_k` when the activation has one row per TOKEN, and i
* itself when it already has one per (token, slot). The output is in SORTED order, which is the
* layout that makes the expert loop contiguous -- the entire point of the scatter. moe_gather puts
* it back.
*
* `a_order` HAS TO BE SAID AND NOT DERIVED. The two grouped GEMMs of one routed block disagree
* about it: gate_up reads the block's input, one row per token; down reads gate_up's output, one
* row per (token, slot). The row count would give it away -- M against M*top_k -- but an operand
* whose meaning changes with its extent is exactly the shape a checker cannot see: if both
* implementations gather they agree with each other, and a harness that sizes the operand the way
* the gather wants never exercises the other reading. */
static int moe_gemm_impl(const RadArgs* a, bool quant) {
const int n_opd = quant ? 9 : 5;
if (!rad_args_have(a, n_opd)) return RAD_E_INVAL;
const RadTensor* A = &a->t[0];
const RadTensor* as_ = quant ? rad_arg_in(a, 1) : nullptr;
const RadTensor* W = &a->t[quant ? 2 : 1];
const RadTensor* ws_ = quant ? rad_arg_in(a, 3) : nullptr;
const RadTensor* sorted = &a->t[quant ? 4 : 2];
const RadTensor* off = &a->t[quant ? 5 : 3];
const RadTensor* Y = &a->t[quant ? 8 : 4];
/* THE QUANTISED ARM'S EXPERTS ARE TWO TABLES BY PARITY, expert e at entry e / 2 of class
* e % 2; the plain arm's are one. */
const bool two = quant;
const RadTensor* W1 = two ? &a->t[6] : W;
const RadTensor* ws1_ = two ? rad_arg_in(a, 7) : nullptr;
const char* ord = p_str(a, "a_order", "token");
const bool sorted_a = ord && std::strcmp(ord, "sorted") == 0;
if (ord && !sorted_a && std::strcmp(ord, "token") != 0) return RAD_E_UNSUPPORTED;
const int64_t N0 = p_int(a, "N", W->rank >= 3 ? W->shape[1] : 0);
const int64_t K0 = p_int(a, "K", W->rank >= 3 ? W->shape[2] : 0);
const int64_t N1 = two ? p_int(a, "N_odd", N0) : N0;
const int64_t K1 = two ? p_int(a, "K_odd", K0) : K0;
const int64_t parts = two ? p_int(a, "parts", 1) : 1;
const int64_t n_expert = p_int(a, "n_expert", W->rank >= 3 ? W->shape[0] : 0);
const int64_t top_k = p_int(a, "top_k", 1);
if (N0 <= 0 || K0 <= 0 || N1 <= 0 || K1 <= 0 || parts <= 0 || n_expert <= 0 || top_k <= 0)
return RAD_E_SHAPE;
if (N0 % parts || N1 % parts) return RAD_E_SHAPE;
/* The output is the wider class's width, the activation the longer class's K. */
const int64_t N = N0 > N1 ? N0 : N1, K = K0 > K1 ? K0 : K1;
const int64_t ne0 = two ? (n_expert + 1) / 2 : n_expert, ne1 = two ? n_expert / 2 : 0;
if (W->rank < 3 || W->shape[0] < ne0) return RAD_E_SHAPE;
if (two && (W1->rank < 3 || W1->shape[0] < ne1)) return RAD_E_SHAPE;
const int64_t T = numel(Y) / N;
if (T <= 0 || numel(sorted) < T || numel(off) < n_expert + 1) return RAD_E_SHAPE;
const int64_t M = T / top_k;
const int64_t AR = sorted_a ? T : M;
if (M <= 0 || numel(A) < AR * K) return RAD_E_SHAPE;
const Mat ma = as_mat(A, K);
const Scales SA = make_scales(as_, AR, K);
const int64_t gp = p_int(a, "group", 0);
if (quant && gp > 0 && SA.p && SA.group != gp) return RAD_E_SHAPE;
const int64_t y_rs = row_stride(Y, N);
const int64_t y_cs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
/* ONE ARENA CALL FOR EVERYTHING THE PARALLEL REGIONS READ, and that is not tidiness. The
* scratch arena GROWS -- a second scratch_raw at a larger size frees the first block and
* returns a new one, so splitting this into two calls leaves every worker thread reading a
* dangling expert table while the main thread walks a valid panel. The layout is computed
* once, 64-aligned between sections so a vector load off the panel is legal. */
const size_t ne = (size_t)n_expert;
auto pad64 = [](size_t x) { return (x + 63) & ~(size_t)63; };
const size_t off_we = 0;
const size_t off_wse = pad64(off_we + ne * sizeof(RadTensor));
const size_t off_mw = pad64(off_wse + ne * sizeof(RadTensor));
const size_t off_sw = pad64(off_mw + ne * sizeof(Mat));
const size_t off_pan = pad64(off_sw + ne * sizeof(Scales));
const size_t off_tok = pad64(off_pan + (size_t)T * (size_t)K * sizeof(float));
const size_t off_exp = pad64(off_tok + (size_t)T * sizeof(int64_t));
uint8_t* base = (uint8_t*)scratch_raw(off_exp + (size_t)T * sizeof(int64_t) + 64);
RadTensor* we = (RadTensor*)(base + off_we);
RadTensor* wse = (RadTensor*)(base + off_wse);
Mat* mw = (Mat*)(base + off_mw);
Scales* SW = (Scales*)(base + off_sw);
float* apanel = (float*)(base + off_pan);
int64_t* atok = (int64_t*)(base + off_tok);
int64_t* aexp = (int64_t*)(base + off_exp);
/* Per-expert readings, built once outside the loops. A null `data` means the operand could not
* be read as a table at all, which is refused BEFORE any parallel region because an OpenMP
* body cannot return. */
for (int64_t e = 0; e < n_expert; ++e) {
const bool odd = two && (e & 1);
const RadTensor* tw = odd ? W1 : W;
const RadTensor* ts = odd ? ws1_ : ws_;
const int64_t ix = two ? e / 2 : e;
const int64_t n = odd ? N1 : N0, k = odd ? K1 : K0;
we[e] = expert_entry(tw, ix);
if (!we[e].data) return RAD_E_STRIDE;
if (we[e].rank < 2 || we[e].shape[0] < n || we[e].shape[1] < k) return RAD_E_SHAPE;
mw[e] = as_mat(&we[e], k);
if (quant && ts) {
wse[e] = expert_entry(ts, ix);
if (!wse[e].data) return RAD_E_STRIDE;
SW[e] = make_scales(&wse[e], n, k);
} else {
SW[e] = make_scales(nullptr, n, k);
}
/* An activation grid FINER than the weight's cannot have its scale hoisted out of the
* group. No format in this project has one; refusing here, before any work, is the honest
* answer and it cannot be done inside the loop because an OpenMP body cannot return. */
const int64_t g = SW[e].p && SW[e].group > 0 ? SW[e].group : k;
if (SA.p && SA.group < g) return RAD_E_UNSUPPORTED;
}
/* THE ACTIVATION PANEL. Every output row's source row is widened into f32 once, here, so the
* dot products below never touch a dtype -- and so the N loop can read the same panel row for
* all its outputs instead of re-converting it N times. Dropped slots are marked with a
* negative token and their output row is zeroed rather than left as stale arena bytes. */
AVX_PARALLEL_FOR_IF(T * K >= AVX_PAR_MIN)
for (int64_t i = 0; i < T; ++i) {
const int64_t flat = ldi(sorted, offlin(sorted, i));
const int64_t tok = flat < 0 ? -1 : (sorted_a ? i : flat / top_k);
atok[i] = (tok >= 0 && tok < AR) ? tok : -1;
if (atok[i] >= 0) pack_row(ma, atok[i], K, apanel + i * K);
}
/* Which expert owns row i, walked once off the offsets rather than binary-searched per
* (row, n) pair -- the rows are expert-sorted, so one linear sweep answers every row. */
{
int64_t e = 0;
for (int64_t i = 0; i < T; ++i) {
while (e + 1 < n_expert && ldi(off, offlin(off, e + 1)) <= i) ++e;
aexp[i] = e;
}
}
/* Output column n is weight row (n / fy) * fc + n % fy of its expert, and zero past a narrower
* class's part. */
const int64_t fy = N / parts;
AVX_PARALLEL_FOR_IF(T * N * K >= AVX_PAR_MIN)
for (int64_t n = 0; n < N; ++n) {
float* bbuf = scratch_f32((size_t)K);
int64_t packed_e = -1;
const int64_t pp = n / fy, j = n - pp * fy;
for (int64_t i = 0; i < T; ++i) {
if (atok[i] < 0) { stt(Y, i * y_rs + n * y_cs, 0.0f); continue; }
const int64_t e = aexp[i];
const bool odd = two && (e & 1);
const int64_t fc = (odd ? N1 : N0) / parts, ke = odd ? K1 : K0;
if (j >= fc) { stt(Y, i * y_rs + n * y_cs, 0.0f); continue; }
const int64_t wr = pp * fc + j;
/* The expert's weight row is packed when the expert CHANGES, which -- because the
* rows are expert-sorted -- is at most n_expert times over the whole i loop. That is
* the win over walking (row, n) and re-reading the weight per row. */
if (e != packed_e) { pack_row(mw[e], wr, ke, bbuf); packed_e = e; }
const Scales& SB = SW[e];
const int64_t g = SB.p && SB.group > 0 ? SB.group : ke;
const int64_t ngrp = (ke + g - 1) / g;
const float* av = apanel + i * K;
float acc = 0.0f;
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < ke) ? k0 + g : ke;
const float sb = SB.p ? SB.grp(wr, gi) : 1.0f;
const float sa = (SA.p && SA.group > 0) ? SA.grp(atok[i], k0 / SA.group) : 1.0f;
acc += dotf(av, bbuf, k0, k1) * sa * sb;
}
stt(Y, i * y_rs + n * y_cs, acc);
}
}
return RAD_OK;
}
AVX_KERNEL(moe_gemm) { return moe_gemm_impl(a, false); }
AVX_KERNEL(moe_gemm_q) { return moe_gemm_impl(a, true); }
/* ------------------------------------------------------------------ moe_gather */
/* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)].
*
* THE SUMMATION ORDER IS ASCENDING SLOT j, which is what makes this reproducible: walking the
* expert-sorted rows instead would sum a token's contributions in expert-id order and the two
* differ in the last bits.
*
* The inverse permutation is built ONCE over the whole batch. libref rebuilds it per block of
* tokens into a fixed stack array specifically to avoid allocating, which costs (M / block) full
* passes over sorted_tok; the scratch arena removes the reason for that. */
AVX_KERNEL(moe_gather) {
if (!rad_args_have(a, 6)) return RAD_E_INVAL;
const RadTensor *ye = &a->t[0], *ew = &a->t[1], *sorted = &a->t[2], *Y = &a->t[5];
/* The shared arm, folded: y = narrow(shared * act(gate)) + narrow(gathered).
* A pair or neither, exactly libref's opening lines. */
const RadTensor *sh = rad_arg_in(a, 3), *sg = rad_arg_in(a, 4);
if ((sh != nullptr) != (sg != nullptr)) return RAD_E_INVAL;
const char* act = p_str(a, "act", "none");
const bool sig = act && !std::strcmp(act, "sigmoid");
if (sh && act && std::strcmp(act, "sigmoid") && std::strcmp(act, "none")) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0);
const int64_t top_k = p_int(a, "top_k", 1);
if (n <= 0 || top_k <= 0) return RAD_E_SHAPE;
const int64_t M = numel(Y) / n;
const int64_t T = M * top_k;
if (M <= 0 || numel(sorted) < T || numel(ew) < T || numel(ye) < T * n) return RAD_E_SHAPE;
int32_t* inv = (int32_t*)scratch_raw((size_t)T * sizeof(int32_t) + 64);
for (int64_t i = 0; i < T; ++i) inv[i] = -1;
for (int64_t i = 0; i < T; ++i) {
const int64_t f = ldi(sorted, offlin(sorted, i));
if (f >= 0 && f < T) inv[f] = (int32_t)i;
}
const int64_t ye_rs = ye->rank >= 2 ? ye->stride[ye->rank - 2] : n;
const int64_t ye_cs = ye->rank >= 2 ? ye->stride[ye->rank - 1] : 1;
/* libref's Y addressing, for the fold below: stride[rank-2]/stride[rank-1], not the
* rowoff/laststride reading out_row uses. The two agree on every rank-2 [M, n] this op is
* described with; the fold uses this one so a hostile higher-rank Y still lands where the
* reference puts it. */
const int64_t y_rs = Y->rank >= 2 ? Y->stride[Y->rank - 2] : n;
const int64_t y_cs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
AVX_PARALLEL_FOR_IF(M * n * top_k >= AVX_PAR_MIN)
for (int64_t t = 0; t < M; ++t) {
float* acc = scratch_f32((size_t)n);
float* row = scratch_f32_b((size_t)n);
for (int64_t c = 0; c < n; ++c) acc[c] = 0.0f;
for (int64_t j = 0; j < top_k; ++j) {
const int32_t i = inv[t * top_k + j];
if (i < 0) continue;
const float w = ldt(ew, rowoff(ew, t, top_k) + j * laststride(ew));
const float* v;
if (ye_cs == 1) {
v = row_f32_in(ye->dtype, byte_at(ye->data, ye->dtype, (int64_t)i * ye_rs), row, n);
} else {
for (int64_t c = 0; c < n; ++c)
row[c] = rad_load_f32(ye->data, ye->dtype, (int64_t)i * ye_rs + c * ye_cs);
v = row;
}
const vf vw = vf_set1(w);
int64_t c = 0;
for (; c + VF_N <= n; c += VF_N)
vf_storeu(acc + c, vf_fma(vw, vf_loadu(v + c), vf_loadu(acc + c)));
for (; c < n; ++c) acc[c] += w * v[c];
}
if (!sh) {
out_row(Y, rowoff(Y, t, n), n, acc);
continue;
}
/* THE NARROWS ARE THE UNFUSED PAIR'S, in libref's order: narrow the gathered row into Y,
* narrow the shared product into Y, narrow their sum. The gate is one scalar per token,
* through the same expf the oracle uses (see scale_rows on why not the vector form). */
const float v0 = ldt(sg, t * laststride(sg));
const float gate = sig ? 1.0f / (1.0f + std::exp(-v0)) : v0;
const int64_t shb = rowoff(sh, t, n), shs = laststride(sh);
for (int64_t c = 0; c < n; ++c) {
const int64_t yo = t * y_rs + c * y_cs;
stt(Y, yo, acc[c]);
const float g = ldt(Y, yo);
stt(Y, yo, ldt(sh, shb + c * shs) * gate);
stt(Y, yo, ldt(Y, yo) + g);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ logit_rerank */
/* R candidate ids rescored against the full-precision head and re-sorted, the second half of a
* coarse top-R. `idx_in` carries GLOBAL ids, `vocab_off` is this rank's first column,
* and an id outside the head's rows becomes a pad that sorts last with -inf.
*
* THE DOTS ARE f32-VECTOR, the reference's are f64-scalar IN ORDER, and that is a tolerance
* question rather than a defect: at K = 2048 the tree differs ~1e-6 relative and the op has no
* tight entry, so it lands in the dtype bucket (1e-5 f32). What is EXACT is the selection --
* descending by value, ties to the lower id, pads dropped -- copied rather than paraphrased,
* because a tie resolved differently from row_topk is a silent routing divergence.
*
* `head` is read FLAT ([NV, K] row-major, unit stride), exactly as the reference reads it: the
* row for candidate id g starts at g * K elements. That is the contract, not a convenience. */
static inline float dotf(const float* a, const float* b, int64_t n) {
vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero();
int64_t k = 0;
for (; k + 4 * VF_N <= n; k += 4 * VF_N) {
a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0);
a1 = vf_fma(vf_loadu(a + k + VF_N), vf_loadu(b + k + VF_N), a1);
a2 = vf_fma(vf_loadu(a + k + 2 * VF_N), vf_loadu(b + k + 2 * VF_N), a2);
a3 = vf_fma(vf_loadu(a + k + 3 * VF_N), vf_loadu(b + k + 3 * VF_N), a3);
}
for (; k + VF_N <= n; k += VF_N) a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0);
float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3)));
for (; k < n; ++k) s += a[k] * b[k];
return s;
}
AVX_KERNEL(logit_rerank) {
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *in = &a->t[2];
const RadTensor *idx = &a->t[3], *val = &a->t[4];
const RadTensor* pairs = (a->n_t > 5 && a->t[5].data) ? &a->t[5] : nullptr;
const int64_t R = p_int(a, "R", 1);
const int64_t K = p_int(a, "n_embd", 0);
const int64_t NV = p_int(a, "n_vocab", 0);
const int64_t voff = p_int(a, "vocab_off", 0);
if (R <= 0 || K <= 0 || NV <= 0) return RAD_E_SHAPE;
const int64_t M = numel(x) / K;
if (M <= 0 || numel(in) < M * R) return RAD_E_SHAPE;
if (numel(idx) < M * R || numel(val) < M * R) return RAD_E_SHAPE;
if (numel(w) < NV * K) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(M * R * K >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
float* xb = scratch_f32((size_t)K);
float* wb = scratch_f32_b((size_t)K);
float* sc = scratch_f32_c((size_t)R);
const float* xv = in_row(x, rowoff(x, m, K), K, xb);
/* ONE raw block, partitioned by hand: the arena has a single slot, so two get() calls
* would hand back the SAME pointer and `used` would clobber `id`. */
int32_t* id = (int32_t*)scratch_raw((size_t)R * sizeof(int32_t) + (size_t)R + 64);
for (int64_t r = 0; r < R; ++r) {
const int64_t g = ldi(in, rowoff(in, m, R) + r * laststride(in));
const int64_t local = g - voff;
if (g < 0 || local < 0 || local >= NV) {
id[r] = -1;
sc[r] = -INFINITY;
continue;
}
row_to_f32(w->dtype, byte_at(w->data, w->dtype, local * K), wb, K);
id[r] = (int32_t)g;
sc[r] = dotf(xv, wb, K);
}
uint8_t* used = (uint8_t*)(id + R);
for (int64_t r = 0; r < R; ++r) used[r] = 0;
for (int64_t o = 0; o < R; ++o) {
int64_t best = -1;
for (int64_t c = 0; c < R; ++c) {
if (used[c] || id[c] < 0) continue;
if (best < 0 || sc[c] > sc[best] ||
(sc[c] == sc[best] && id[c] < id[best])) best = c;
}
const int32_t oid = best >= 0 ? id[best] : -1;
const float ov = best >= 0 ? sc[best] : -INFINITY;
if (best >= 0) used[best] = 1;
st_int_dt(idx->dtype, idx->data, rowoff(idx, m, R) + o * laststride(idx), oid);
stt(val, rowoff(val, m, R) + o * laststride(val), ov);
if (pairs) {
float* p = (float*)pairs->data + (m * R + o) * 2;
std::memcpy(p, &oid, sizeof oid);
p[1] = ov;
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ row_topk */
/* Exact per-row top-R, descending, ties to the lower column. The same selection the router uses,
* exposed as its own op because a drafter's candidate set and a speculative tree both want it
* without a softmax in front.
*
* The vocab-parallel form: `vocab_off` shifts every column reported so a rank's slice reports
* GLOBAL ids, and `pairs` is the [M, R, 2] plane an all_gather moves -- an int32 id bit-copied
* into the first float slot beside its value. Both absent is the ordinary single-rank top-R. */
AVX_KERNEL(row_topk) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *idx = &a->t[1], *val = &a->t[2];
const RadTensor* pairs = rad_arg_in(a, 3);
const int64_t off = p_int(a, "vocab_off", 0);
const int64_t N = p_int(a, "N", x->rank >= 2 ? x->shape[x->rank - 1] : 0);
const int64_t R = p_int(a, "R", 1);
if (N <= 0 || R <= 0) return RAD_E_SHAPE;
const int64_t M = numel(x) / N;
if (M <= 0 || numel(idx) < M * R || numel(val) < M * R) return RAD_E_SHAPE;
if (pairs && (pairs->dtype != RAD_F32 || numel(pairs) < M * R * 2)) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(M * N >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
float* buf = scratch_f32((size_t)N);
const float* v = in_row(x, rowoff(x, m, N), N, buf);
float pv = INFINITY;
int64_t pi = -1;
for (int64_t r = 0; r < R; ++r) {
const bool ok = topk_next_f32(v, N, &pv, &pi);
const int64_t id = ok ? pi + off : -1;
st_int_dt(idx->dtype, idx->data, rowoff(idx, m, R) + r * laststride(idx), id);
stt(val, rowoff(val, m, R) + r * laststride(val), ok ? pv : -INFINITY);
if (pairs) {
float* const q = (float*)pairs->data + (m * R + r) * 2;
const int32_t i32 = (int32_t)id;
std::memcpy(q, &i32, sizeof i32);
q[1] = ok ? pv : -INFINITY;
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ row_topk_merge */
/* The R largest of world_size all-gathered per-rank candidate sets, in the same descending
* (idx, val) form the single-rank path produces.
*
* TIES BREAK ON THE LOWER ID, which is what makes the merge EXACT rather than approximate: a dense
* top-R over the whole vocabulary breaks ties on the lower column, so a merge that broke them on
* rank order would disagree with it exactly when two shards hold the same logit.
*
* A slot the producing rank could not fill carries id -1 and is DROPPED -- a sentinel rather than
* a -inf value, because -inf is a value a masked logit legitimately takes.
*
* LEFT SCALAR, AND THE REASON IS THE SIZE. W*R is 32 entries at world 2 and R 16; the selection
* sort over it is 512 comparisons against a vector setup that would cost more than it saves, and
* the tie rule is a lexicographic compare that no vector max expresses. */
AVX_KERNEL(row_topk_merge) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *g = &a->t[0], *idx = &a->t[1], *val = &a->t[2];
const int64_t R = p_int(a, "R", 1);
const int64_t W = p_int(a, "world_size", 1);
if (R <= 0 || W <= 0) return RAD_E_SHAPE;
/* The rows are the OPERAND'S, not the parameter's: `M` is declared as a band ceiling and the
* gathered plane is narrowed to the rows this step actually has. */
const int64_t M = numel(g) / (W * R * 2);
if (M <= 0) return RAD_E_SHAPE;
if (g->dtype != RAD_F32 || numel(g) < M * W * R * 2) return RAD_E_SHAPE;
if (numel(idx) < M * R || numel(val) < M * R) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(M * W * R * R >= 4096)
for (int64_t m = 0; m < M; ++m) {
const float* const row = (const float*)g->data + m * W * R * 2;
unsigned char* used = (unsigned char*)scratch_f32((size_t)(W * R) / 4 + 4);
for (int64_t c = 0; c < W * R; ++c) used[c] = 0;
for (int64_t r = 0; r < R; ++r) {
int64_t best = -1;
float bv = 0.0f;
int32_t bid = 0;
for (int64_t c = 0; c < W * R; ++c) {
if (used[c]) continue;
int32_t id;
std::memcpy(&id, row + c * 2, sizeof id);
if (id < 0) continue; /* a pad, not a candidate */
const float v = row[c * 2 + 1];
if (best < 0 || v > bv || (v == bv && id < bid)) { best = c; bv = v; bid = id; }
}
if (best >= 0) used[best] = 1;
st_int_dt(idx->dtype, idx->data, rowoff(idx, m, R) + r * laststride(idx),
best >= 0 ? (int64_t)bid : -1);
stt(val, rowoff(val, m, R) + r * laststride(val), best >= 0 ? bv : -INFINITY);
}
}
return RAD_OK;
}
+869
View File
@@ -0,0 +1,869 @@
/* avx_ngram.cpp -- where embed_lookup_q's rows come from, and the table's stored arrangement.
* BASELINE-COMPILED: no -m flags, like avx_dispatch.cpp. Nothing here is vector arithmetic; the
* decode that is arrives from the calling level (avx_rows.h).
*
* ============================== WHY THIS GATHER IS A HOST KERNEL ==============================
*
* An n-gram embedding of 320,001,536 rows of 160 E4M3 is 51.2 GB, read SIXTEEN ROWS A TOKEN, and
* every mechanism for an oversized weight is built for a different shape of access:
*
* Tier::SSD + DeviceStaged stages a WHOLE movement unit into a slab slot and DMAs it. Staging
* 51.2 GB to use 5 KB is not a slow path, it is the wrong shape.
* Site::DeviceZeroCopy wants it in pinned host RAM, which a table this size does not fit.
* hipHostRegister on the map pins, so it would force all 51.2 GB resident. Same wall.
*
* core/format/radfile.cpp mmaps the whole container -- "LOAD IS MAP-AND-GO" -- so the table is at
* a HOST virtual address the moment the model opens, backed by a file on an NVMe. A sparse gather
* of sixteen rows out of 320 million is a caching problem -- nothing can predict which rows are hot
* -- but for a cache of ROWS, not of the 4 KiB pages the OS would keep; see the row cache below.
* (core/place/mover.h rejects mmap for the WEIGHT POOL and that argument does not reach here -- it
* is about SWEEPING a working set, where residency is controlled explicitly.)
*
* So the gather runs on the host, over the container's own mapping, and its [T, n_embd] bf16
* result crosses the link once -- a few kilobytes a token at decode. The placement planner puts an
* op on the host when every WEIGHT operand of it is Site::Host (core/runtime/ctx.cpp), which is why
* the table has to be a weight operand: `gather_rows` takes a plain IN operand and would never
* trigger it. A host op needs a host kernel in a production plugin -- libref is the oracle and
* rad_gate_reference_kernels refuses to serve on it -- and host kernels are this plugin's.
*
* ============================== A SHARED ROW CACHE, AND DIRECT READS FOR ITS MISSES ==============================
*
* The gather is not arithmetic. 160 table bytes decode to 160 bf16 in a few dozen cycles; what a
* row costs is getting its bytes, and at decode most of them have never been read before: eight
* varied sequences want ~487 distinct rows a step, and about half of those are an n-gram hashed for
* the first time (see the trace note below). No cache serves those; they are reads.
*
* THE PAGE CACHE IS THE WRONG CACHE FOR THIS TABLE, twice over. A buffered read of an uncached page
* costs the submitting thread ~4 us -- page allocation, page-cache insertion, block mapping and the
* bio all run inside the submission -- so a call's cold rows are started one after another: ~380 of
* them take ~1.5 ms to submit, and the drive finishes the burst ~0.25 ms after the last one. And it
* caches a 4 KiB page for a 160-byte row that shares its page with nothing else a gather wants, so
* every miss evicts 4 KiB of some other file's cache to keep 160 bytes of this one.
*
* SO THE ROWS HAVE THEIR OWN CACHE, AND A MISS IS A DIRECT READ. RowCache below holds rows, not
* pages, and every thread that gathers from the table shares it. A miss is an O_DIRECT read of the
* aligned span holding the row: ~2 us to submit, nothing inserted anywhere, 512 bytes off the drive
* where a page read takes 4096. At eight varied sequences a cache of 2^19 rows (80 MiB at 160 bytes)
* misses 51.0% of rows, against 50.6% for an unbounded one.
*
* EACH MISS IS READ ONCE, BY WHICHEVER THREAD CLAIMS IT. Every rank gathers every row. A thread
* claims a missing row by marking its slot LOADING, reads it and publishes it READY; a thread that
* finds a row another thread is loading waits for it instead of reading it again. The ranks walk a
* call's rows from different starting points, so each claims about its own share of the misses and
* the cold work is divided between them rather than duplicated -- with no barrier between the
* ranks: a late rank finds the rows already there.
*
* THE FILE COMES FROM THE MAPPING. The table operand is a pointer into the container's mmap and the
* plugin ABI carries no file, so /proc/self/maps says which file and offset back that address, once
* a table. A table no file backs -- a test's heap buffer -- is read as the memory it is. A file on a
* filesystem that cannot do direct I/O is refused. */
#include "avx_rows.h"
#include "avx_common.h"
#include "rad_plugin.h"
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <atomic>
#include <condition_variable>
#include <deque>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#if defined(__linux__)
#include <cerrno>
#include <fcntl.h>
#include <linux/io_uring.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
#endif
namespace {
/* How many rows ahead of the one being looked up or decoded its cache lines are requested. The
* rows are scattered over an 80 MiB cache and the set words over 4 MiB, so every row is a miss to
* L3 or DRAM; a row's lines requested this far ahead arrive while the rows before it are worked on
* instead of one after another. */
constexpr long long kPrefetchRows = 8;
/* One read of a row's aligned span: row m of the call, its key, and its cache slot (-1: the row is
* decoded straight from the read, not kept). */
struct SpanRead {
long long m;
uint64_t key;
int64_t slot;
};
/* A thread's working state for one call, kept between calls so a call allocates nothing once the
* thread has seen its largest. */
struct Gather {
std::vector<int64_t> slot; /* per row: its cache slot */
std::vector<uint8_t> kind; /* per row: a RowCache::Found, or PAD / DONE below */
std::vector<SpanRead> reads; /* the rows this thread reads */
std::vector<long long> waits; /* rows another thread is reading */
std::vector<long long> again; /* rows whose slot changed under the decode */
/* One decode batch: each row's source and destination, and for a row decoded from the cache,
* its call index and the slot word it was read under. */
std::vector<const uint8_t*> src;
std::vector<uint16_t*> dst;
std::vector<long long> dm;
std::vector<uint64_t> dw;
/* The same for rows decoded straight from a read's bounce buffer. */
std::vector<const uint8_t*> bsrc;
std::vector<uint16_t*> bdst;
uint8_t* bounce = nullptr;
size_t bounce_bytes = 0;
enum : uint8_t { PAD = 16, DONE };
uint8_t* bounce_for(size_t bytes) {
if (bytes > bounce_bytes) {
std::free(bounce);
bounce = static_cast<uint8_t*>(std::aligned_alloc(4096, (bytes + 4095) & ~(size_t)4095));
bounce_bytes = bounce ? bytes : 0;
}
return bounce;
}
~Gather() { std::free(bounce); }
};
inline Gather& gather_state() {
static thread_local Gather g;
return g;
}
#if defined(__linux__)
/* The file behind a table: the address range of its mapping, the file offset of that range's first
* byte, and the file opened for direct reads with the granule their offsets and lengths must keep.
* `fd` is -1 for memory no file backs. */
struct TableFile {
const uint8_t* lo = nullptr;
const uint8_t* hi = nullptr;
int fd = -1;
long long off = 0;
long long align = 0;
};
/* The file behind [p, p + n): the mapping holding `p`, extended over the mappings that continue it
* in the same file (a madvise over a sub-range splits one mapping into several). Looked up once per
* table and kept for the life of the process; every rank thread shares the entry and the fd, and a
* read at an explicit offset has no file position to share. */
const TableFile* table_file(const uint8_t* p, long long n, int* err) {
static std::mutex mu;
static std::vector<std::unique_ptr<TableFile>> known;
std::lock_guard<std::mutex> lk(mu);
for (const auto& t : known)
if (p >= t->lo && p + n <= t->hi) return t.get();
auto t = std::make_unique<TableFile>();
t->lo = p;
t->hi = p + n;
std::FILE* f = std::fopen("/proc/self/maps", "re");
if (!f) { *err = RAD_E_IO; return nullptr; }
char line[4352];
bool found = false;
uintptr_t end = 0;
unsigned long long ino = 0, next_off = 0;
std::string path;
while (std::fgets(line, sizeof line, f)) {
unsigned long long lo = 0, hi = 0, off = 0, inode = 0;
char perms[8];
unsigned dmaj = 0, dmin = 0;
int at = 0;
if (std::sscanf(line, "%llx-%llx %7s %llx %x:%x %llu %n", &lo, &hi, perms, &off, &dmaj,
&dmin, &inode, &at) < 7)
continue;
std::string name(line + at);
while (!name.empty() && (name.back() == '\n' || name.back() == ' ')) name.pop_back();
if (!found) {
if ((uintptr_t)p < lo || (uintptr_t)p >= hi) continue;
if (inode == 0 || name.empty() || name[0] != '/') break; /* no file: memory */
found = true;
t->lo = (const uint8_t*)(uintptr_t)lo;
t->off = (long long)off;
end = (uintptr_t)hi;
ino = inode;
next_off = off + (hi - lo);
path = name;
} else if ((uintptr_t)lo == end && inode == ino && name == path && off == next_off) {
end = (uintptr_t)hi;
next_off = off + (hi - lo);
} else {
break;
}
if ((uintptr_t)(p + n) <= end) break;
}
std::fclose(f);
if (found) {
if ((uintptr_t)(p + n) > end) { *err = RAD_E_IO; return nullptr; }
t->hi = (const uint8_t*)end;
t->fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_DIRECT);
struct statx sx;
std::memset(&sx, 0, sizeof sx);
if (t->fd < 0 || ::statx(t->fd, "", AT_EMPTY_PATH, STATX_INO | STATX_DIOALIGN, &sx) != 0 ||
sx.stx_ino != ino || !(sx.stx_mask & STATX_DIOALIGN) || sx.stx_dio_offset_align == 0) {
std::fprintf(stderr, "libavx: %s cannot be read with direct I/O (%s); the n-gram table "
"is read that way\n", path.c_str(),
t->fd < 0 ? std::strerror(errno) : "the filesystem reports no alignment");
if (t->fd >= 0) ::close(t->fd);
*err = RAD_E_UNSUPPORTED;
return nullptr;
}
const long long a = sx.stx_dio_offset_align > sx.stx_dio_mem_align
? sx.stx_dio_offset_align : sx.stx_dio_mem_align;
if (a & (a - 1)) { ::close(t->fd); *err = RAD_E_UNSUPPORTED; return nullptr; }
t->align = a;
}
known.push_back(std::move(t));
return known.back().get();
}
/* ============================== THE ROW CACHE ==============================
*
* Set-associative: a row's key -- its byte offset in the file -- hashes to a set of kWays slots, and
* a slot is one atomic word plus the row's bytes. The word is the slot's whole state:
*
* key << 10 | owner << 2 | state state: EMPTY (word 0), LOADING, READY
*
* owner names the thread loading the row, so a thread that meets its own claim again (a row twice in
* one call) does not wait on itself. A reader of a READY slot copies the bytes and then reads the
* word again: a slot's bytes are only rewritten after its word has left READY, so an unchanged word
* means the copy was that row's (a seqlock). The victim in a full set is chosen by CLOCK over
* per-slot reference bits, kept outside the word so that marking a row used never fails another
* reader's check; a LOADING slot is never a victim.
*
* A set's eight words are one 64-byte line. The arrays are anonymous mappings, so a slot costs
* memory once a row lands in it. */
struct RowCache {
static constexpr int kWays = 8;
static constexpr uint64_t kRows = 1ull << 19;
enum : uint64_t { EMPTY = 0, LOADING = 1, READY = 2 };
const TableFile* tf = nullptr;
long long n = 0;
uint64_t set_mask = 0;
std::atomic<uint64_t>* word = nullptr;
std::atomic<uint8_t>* ref = nullptr;
std::atomic<uint8_t>* hand = nullptr;
uint8_t* data = nullptr;
std::atomic<uint32_t> published{0}; /* bumped, and waited on, as a batch of rows lands */
static uint64_t ready(uint64_t key) { return key << 10 | READY; }
static uint64_t mix(uint64_t x) {
x ^= x >> 30; x *= 0xbf58476d1ce4e5b9ull;
x ^= x >> 27; x *= 0x94d049bb133111ebull;
return x ^ (x >> 31);
}
const void* set_line(uint64_t key) const { return &word[(mix(key) & set_mask) * kWays]; }
enum Found { HIT, CLAIMED, MINE, THEIRS, NONE };
/* The slot holding `key` -- READY (HIT), being loaded by this thread (MINE) or by another
* (THEIRS) -- or a slot claimed for it now (CLAIMED), or none when every slot of its set is
* being loaded. */
Found find_or_claim(uint64_t key, uint64_t me, int64_t* slot) {
const uint64_t set = mix(key) & set_mask;
const uint64_t s0 = set * kWays;
for (;;) {
int64_t victim = -1;
uint64_t vw = 0;
for (int w = 0; w < kWays; ++w) {
const uint64_t x = word[s0 + w].load(std::memory_order_acquire);
if (x != EMPTY && (x >> 10) == key) {
*slot = (int64_t)(s0 + w);
if ((x & 3) == READY) {
ref[s0 + w].store(1, std::memory_order_relaxed);
return HIT;
}
return ((x >> 2) & 255) == me ? MINE : THEIRS;
}
if (x == EMPTY && victim < 0) victim = (int64_t)(s0 + w);
}
/* CLOCK: clear reference bits until a READY slot without one comes round. Two turns
* clear them all, so a victim is found unless every slot is LOADING. */
for (int k = 0; victim < 0 && k < 2 * kWays; ++k) {
const uint8_t h = hand[set].load(std::memory_order_relaxed);
hand[set].store((uint8_t)((h + 1) % kWays), std::memory_order_relaxed);
const uint64_t s = s0 + h % kWays;
const uint64_t x = word[s].load(std::memory_order_acquire);
if ((x & 3) != READY) continue;
if (ref[s].load(std::memory_order_relaxed)) {
ref[s].store(0, std::memory_order_relaxed);
continue;
}
victim = (int64_t)s;
vw = x;
}
if (victim < 0) { *slot = -1; return NONE; }
if (word[victim].compare_exchange_strong(vw, key << 10 | me << 2 | LOADING,
std::memory_order_acq_rel)) {
/* The bytes are rewritten only after this; see the seqlock note above. */
std::atomic_thread_fence(std::memory_order_release);
*slot = victim;
return CLAIMED;
}
/* Another thread changed the set between the look and the claim: look again. */
}
}
};
template <class T>
T* anon_array(size_t count) {
void* p = mmap(nullptr, count * sizeof(T), PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
return p == MAP_FAILED ? nullptr : static_cast<T*>(p);
}
/* The cache for rows of `n` bytes from `tf`, made on first use and kept for the life of the
* process. */
RowCache* row_cache(const TableFile* tf, long long n) {
static std::mutex mu;
static std::vector<std::unique_ptr<RowCache>> caches;
std::lock_guard<std::mutex> lk(mu);
for (const auto& c : caches)
if (c->tf == tf && c->n == n) return c.get();
auto c = std::make_unique<RowCache>();
c->tf = tf;
c->n = n;
c->set_mask = RowCache::kRows / RowCache::kWays - 1;
c->word = anon_array<std::atomic<uint64_t>>(RowCache::kRows);
c->ref = anon_array<std::atomic<uint8_t>>(RowCache::kRows);
c->hand = anon_array<std::atomic<uint8_t>>(RowCache::kRows / RowCache::kWays);
c->data = anon_array<uint8_t>(RowCache::kRows * (size_t)n);
if (!c->word || !c->ref || !c->hand || !c->data) return nullptr;
caches.push_back(std::move(c));
return caches.back().get();
}
/* This thread's owner tag in a LOADING word: distinct for every thread that gathers, 1..255. */
inline uint64_t owner_tag() {
static std::atomic<uint32_t> next{0};
static thread_local const uint32_t me = ++next;
return me <= 255 ? me : 0;
}
struct ReadRing {
static constexpr unsigned kEntries = 4096;
int fd = -1;
unsigned entries = 0;
unsigned *sq_tail = nullptr, *sq_mask = nullptr, *sq_array = nullptr;
unsigned *cq_head = nullptr, *cq_tail = nullptr, *cq_mask = nullptr;
io_uring_sqe *sqes = nullptr;
io_uring_cqe *cqes = nullptr;
void *sq_ring = nullptr, *cq_ring = nullptr;
size_t sq_sz = 0, cq_sz = 0, sqe_sz = 0;
/* One thread submits and reaps (SINGLE_ISSUER), and completions are run when it asks for them
* rather than by interrupting it (DEFER_TASKRUN): the ring is thread-local and the thread only
* ever waits for a batch it has just submitted. */
bool init() {
io_uring_params p;
std::memset(&p, 0, sizeof p);
p.flags = IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN;
const long r = syscall(__NR_io_uring_setup, kEntries, &p);
if (r < 0) return false;
fd = (int)r;
entries = p.sq_entries;
sq_sz = p.sq_off.array + (size_t)p.sq_entries * sizeof(unsigned);
cq_sz = p.cq_off.cqes + (size_t)p.cq_entries * sizeof(io_uring_cqe);
if (p.features & IORING_FEAT_SINGLE_MMAP) {
if (cq_sz > sq_sz) sq_sz = cq_sz;
cq_sz = sq_sz;
}
sq_ring = mmap(nullptr, sq_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE,
fd, IORING_OFF_SQ_RING);
if (sq_ring == MAP_FAILED) { sq_ring = nullptr; shut(); return false; }
cq_ring = (p.features & IORING_FEAT_SINGLE_MMAP)
? sq_ring
: mmap(nullptr, cq_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE,
fd, IORING_OFF_CQ_RING);
if (cq_ring == MAP_FAILED) { cq_ring = nullptr; shut(); return false; }
sqe_sz = (size_t)p.sq_entries * sizeof(io_uring_sqe);
sqes = (io_uring_sqe*)mmap(nullptr, sqe_sz, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQES);
if (sqes == MAP_FAILED) { sqes = nullptr; shut(); return false; }
sq_tail = (unsigned*)((char*)sq_ring + p.sq_off.tail);
sq_mask = (unsigned*)((char*)sq_ring + p.sq_off.ring_mask);
sq_array = (unsigned*)((char*)sq_ring + p.sq_off.array);
cq_head = (unsigned*)((char*)cq_ring + p.cq_off.head);
cq_tail = (unsigned*)((char*)cq_ring + p.cq_off.tail);
cq_mask = (unsigned*)((char*)cq_ring + p.cq_off.ring_mask);
cqes = (io_uring_cqe*)((char*)cq_ring + p.cq_off.cqes);
return true;
}
void shut() {
if (sqes && sqes != MAP_FAILED) munmap(sqes, sqe_sz);
if (cq_ring && cq_ring != sq_ring) munmap(cq_ring, cq_sz);
if (sq_ring) munmap(sq_ring, sq_sz);
if (fd >= 0) ::close(fd);
sqes = nullptr; sq_ring = cq_ring = nullptr; fd = -1;
}
~ReadRing() { shut(); }
/* The aligned span holding each row of `r[0, count)` (count <= entries) into `bounce`, one span
* every `stride` bytes; submitted with one call that also waits for all of them. Every read
* must return its whole span. */
int read_spans(const TableFile& tf, const SpanRead* r, unsigned count, long long n,
long long stride, uint8_t* bounce) {
const long long A = tf.align;
unsigned tail = __atomic_load_n(sq_tail, __ATOMIC_RELAXED);
for (unsigned i = 0; i < count; ++i) {
const long long a = (long long)r[i].key & ~(A - 1);
const long long e = ((long long)r[i].key + n + A - 1) & ~(A - 1);
const unsigned idx = tail & *sq_mask;
io_uring_sqe* s = &sqes[idx];
std::memset(s, 0, sizeof *s);
s->opcode = IORING_OP_READ;
s->fd = tf.fd;
s->off = (uint64_t)a;
s->addr = (uint64_t)(uintptr_t)(bounce + (size_t)i * stride);
s->len = (unsigned)(e - a);
s->user_data = (uint64_t)(e - a);
sq_array[idx] = idx;
++tail;
}
__atomic_store_n(sq_tail, tail, __ATOMIC_RELEASE);
int status = RAD_OK;
unsigned to_submit = count, got = 0;
while (got < count) {
const long rc = syscall(__NR_io_uring_enter, fd, to_submit, count - got,
IORING_ENTER_GETEVENTS, nullptr, (size_t)0);
if (rc < 0 && errno != EINTR && errno != EAGAIN && errno != EBUSY) return RAD_E_IO;
if (rc > 0) to_submit -= (unsigned)rc < to_submit ? (unsigned)rc : to_submit;
unsigned h = __atomic_load_n(cq_head, __ATOMIC_RELAXED);
const unsigned tl = __atomic_load_n(cq_tail, __ATOMIC_ACQUIRE);
for (; h != tl; ++h, ++got) {
const io_uring_cqe& c = cqes[h & *cq_mask];
if (c.res < 0 || (uint64_t)c.res != c.user_data) status = RAD_E_IO;
}
__atomic_store_n(cq_head, h, __ATOMIC_RELEASE);
}
return status;
}
};
/* Thread-local: each rank thread issues its own step, so each gets its own ring and the two never
* contend. Built on that thread's first gather over a file and torn down when the thread exits. */
inline ReadRing* read_ring() {
static thread_local bool tried = false;
static thread_local std::unique_ptr<ReadRing> r;
if (!tried) {
tried = true;
std::unique_ptr<ReadRing> p(new ReadRing());
if (p->init()) r = std::move(p);
}
return r.get();
}
/* Read `reads` through the ring, a batch at a time: a row with a slot is copied into the cache and
* published READY; a row without one is decoded straight into its output row. On a failed read,
* every claim not yet published is given up (its word back to EMPTY) so no other thread waits on
* it. */
int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g,
const std::vector<SpanRead>& reads, long long n, long long ne,
avx::RowDecode decode, const uint16_t* lut, uint16_t* out, long long x_ld) {
const long long A = tf.align;
const long long stride = ((n + A - 1) / A + 1) * A;
const size_t total = reads.size();
for (size_t b = 0; b < total;) {
const unsigned cnt = (unsigned)(total - b < rr.entries ? total - b : rr.entries);
uint8_t* bounce = g.bounce_for((size_t)cnt * (size_t)stride);
const int rs = bounce ? rr.read_spans(tf, &reads[b], cnt, n, stride, bounce) : RAD_E_NOMEM;
if (rs != RAD_OK) {
for (size_t i = b; i < total; ++i)
if (reads[i].slot >= 0)
rc.word[reads[i].slot].store(RowCache::EMPTY, std::memory_order_release);
rc.published.fetch_add(1, std::memory_order_release);
rc.published.notify_all();
return rs;
}
g.bsrc.clear();
g.bdst.clear();
for (unsigned i = 0; i < cnt; ++i) {
const SpanRead& r = reads[b + i];
const uint8_t* row = bounce + (size_t)i * stride + (r.key & (uint64_t)(A - 1));
if (r.slot < 0) {
g.bsrc.push_back(row);
g.bdst.push_back(out + r.m * x_ld);
continue;
}
std::memcpy(rc.data + (size_t)r.slot * (size_t)n, row, (size_t)n);
rc.ref[r.slot].store(1, std::memory_order_relaxed);
rc.word[r.slot].store(RowCache::ready(r.key), std::memory_order_release);
}
rc.published.fetch_add(1, std::memory_order_release);
rc.published.notify_all();
if (!g.bsrc.empty()) decode(g.bsrc.data(), g.bdst.data(), (int64_t)g.bsrc.size(), ne, lut);
b += cnt;
}
return RAD_OK;
}
/* out[m] = the decoded row ids[m] - voff for every m < M, through the cache: find or claim every
* row starting at row `first`, read this thread's claims, wait for the rows other threads are
* reading, then decode everything from the cache. A row whose slot is taken over while it is being
* decoded is read again, without the cache. */
int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowGather& q,
long long first, avx::RowDecode decode, const uint16_t* lut) {
Gather& g = gather_state();
const uint64_t me = owner_tag();
if (!me) return RAD_E_UNSUPPORTED;
/* `n` is a row's BYTES -- what the cache holds and the file offsets step by -- and `ne` its
* elements, what the decode and a padding row write. */
const long long M = q.M, n = q.row_bytes, ne = q.n_embd, x_ld = q.x_ld;
const long long base = tf.off + (long long)(q.tab - tf.lo);
auto row_of = [&](long long m) { return (long long)q.ids[m] - q.voff; };
auto pad = [&](long long id) { return id < 0 || id >= q.n_vocab; };
auto key_of = [&](long long m) { return (uint64_t)(base + row_of(m) * n); };
auto at = [&](long long j) { return first + j < M ? first + j : first + j - M; };
g.slot.resize((size_t)M);
g.kind.resize((size_t)M);
g.reads.clear();
g.waits.clear();
g.again.clear();
for (long long j = 0; j < M; ++j) {
if (j + kPrefetchRows < M) {
const long long mp = at(j + kPrefetchRows);
if (!pad(row_of(mp))) __builtin_prefetch(rc.set_line(key_of(mp)));
}
const long long m = at(j);
if (pad(row_of(m))) { g.kind[m] = Gather::PAD; continue; }
const uint64_t key = key_of(m);
int64_t s = -1;
const RowCache::Found f = rc.find_or_claim(key, me, &s);
g.slot[m] = s;
g.kind[m] = (uint8_t)f;
if (f == RowCache::CLAIMED) g.reads.push_back({m, key, s});
else if (f == RowCache::NONE) { g.reads.push_back({m, key, -1}); g.kind[m] = Gather::DONE; }
else if (f == RowCache::THEIRS) g.waits.push_back(m);
}
int rs = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld);
if (rs != RAD_OK) return rs;
/* The rows another thread claimed: wait for each to turn READY. `published` is read before the
* words, so a batch that lands after the look changes it and the wait returns at once. A claim
* given up (a failed read) or a slot that moved on is read here instead. */
while (!g.waits.empty()) {
const uint32_t e = rc.published.load(std::memory_order_acquire);
size_t keep = 0;
for (long long m : g.waits) {
const uint64_t key = key_of(m);
const uint64_t x = rc.word[g.slot[m]].load(std::memory_order_acquire);
if (x == RowCache::ready(key)) continue;
if ((x & 3) == RowCache::LOADING && (x >> 10) == key) { g.waits[keep++] = m; continue; }
g.again.push_back(m);
g.kind[m] = Gather::DONE;
}
g.waits.resize(keep);
if (keep) rc.published.wait(e, std::memory_order_acquire);
}
/* Every READY row, decoded in one batch: each row's word is read before its bytes and read
* again after all of them (the seqlock above, over the batch), and a row whose word changed in
* between is read again. */
g.src.clear();
g.dst.clear();
g.dm.clear();
g.dw.clear();
for (long long m = 0; m < M; ++m) {
uint16_t* dst = q.out + m * x_ld;
const uint8_t k = g.kind[m];
if (k == Gather::PAD) { std::memset(dst, 0, (size_t)ne * sizeof(uint16_t)); continue; }
if (k == Gather::DONE) continue;
const int64_t s = g.slot[m];
const uint64_t w1 = rc.word[s].load(std::memory_order_acquire);
if (w1 != RowCache::ready(key_of(m))) { g.again.push_back(m); continue; }
g.src.push_back(rc.data + (size_t)s * (size_t)n);
g.dst.push_back(dst);
g.dm.push_back(m);
g.dw.push_back(w1);
}
if (!g.src.empty()) decode(g.src.data(), g.dst.data(), (int64_t)g.src.size(), ne, lut);
std::atomic_thread_fence(std::memory_order_acquire);
for (size_t i = 0; i < g.dm.size(); ++i)
if (rc.word[g.slot[g.dm[i]]].load(std::memory_order_relaxed) != g.dw[i])
g.again.push_back(g.dm[i]);
if (g.again.empty()) return RAD_OK;
g.reads.clear();
for (long long m : g.again) g.reads.push_back({m, key_of(m), -1});
return read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld);
}
/* ============================== THE READER THAT RUNS A STEP AHEAD ==============================
*
* A prefill chunk gathers `heads` rows a token -- 32,768 at a 2048-token chunk -- and on text the
* cache has not seen, most of them are reads from the file: ~30 ms of random reads a chunk on an
* NVMe drive, during which the step's issuing thread waits in this op and the card idles
* behind it. The NEXT chunk's ids are known a step early (RadBatch::n_ahead, ngram_ids'
* `ahead_ids`), so the call hands them to one process-wide reader thread and returns. The reader
* claims each row the cache lacks, reads it and publishes it READY while the chunk runs on the
* card; the next call finds its rows in the cache, or LOADING under the reader's tag, and waits
* for those exactly as it waits for a row the other rank is reading.
*
* Both ranks hand over the same ids, and the second hand-over of a list the reader already has is
* dropped. A failed read gives its claims up (read_and_publish), and the next call reads those
* rows itself. The reader lives as long as the process: it is never joined, so neither it nor its
* queue is ever destroyed under it. */
struct AheadJob {
const TableFile* tf = nullptr;
RowCache* rc = nullptr;
long long n = 0;
std::vector<uint64_t> keys;
};
struct AheadReader {
std::mutex mu;
std::condition_variable cv;
std::deque<AheadJob> q;
uint64_t last = 0; /* the last id list taken, hashed */
void run() {
Gather& g = gather_state();
ReadRing* rr = read_ring();
const uint64_t me = owner_tag();
for (;;) {
AheadJob j;
{
std::unique_lock<std::mutex> lk(mu);
cv.wait(lk, [&] { return !q.empty(); });
j = std::move(q.front());
q.pop_front();
}
if (!rr || !me) continue;
g.reads.clear();
for (size_t i = 0; i < j.keys.size(); ++i) {
if (i + kPrefetchRows < j.keys.size())
__builtin_prefetch(j.rc->set_line(j.keys[i + kPrefetchRows]));
int64_t slot = -1;
if (j.rc->find_or_claim(j.keys[i], me, &slot) == RowCache::CLAIMED)
g.reads.push_back({0, j.keys[i], slot});
}
/* Every read has a slot, so nothing is decoded and there is no output to write. */
(void)read_and_publish(*j.tf, *j.rc, *rr, g, g.reads, j.n, 0, nullptr, nullptr,
nullptr, 0);
}
}
};
AheadReader* ahead_reader() {
static AheadReader* const r = [] {
AheadReader* a = new AheadReader();
std::thread([a] { a->run(); }).detach();
return a;
}();
return r;
}
/* Hand the rows of `q.ahead` -- rows a later call will gather -- to the reader. */
void read_ahead(const TableFile& tf, RowCache& rc, const avx::RowGather& q) {
uint64_t h = 1469598103934665603ull ^ (uint64_t)(uintptr_t)&rc;
for (long long m = 0; m < q.n_ahead; ++m) { h ^= (uint32_t)q.ahead[m]; h *= 1099511628211ull; }
AheadReader* r = ahead_reader();
{
std::lock_guard<std::mutex> lk(r->mu);
if (h == r->last) return;
r->last = h;
}
AheadJob j;
j.tf = &tf;
j.rc = &rc;
j.n = q.row_bytes;
const long long base = tf.off + (long long)(q.tab - tf.lo);
j.keys.reserve((size_t)q.n_ahead);
for (long long m = 0; m < q.n_ahead; ++m) {
const long long id = (long long)q.ahead[m] - q.voff;
if (id >= 0 && id < q.n_vocab) j.keys.push_back((uint64_t)(base + id * q.row_bytes));
}
{
std::lock_guard<std::mutex> lk(r->mu);
r->q.push_back(std::move(j));
}
r->cv.notify_one();
}
/* ============================== THE ROW-ID TRACE ==============================
*
* AVX_PLE_TRACE=<path> appends every row id this op gathers, one per line. Off unless the variable
* is set, and it changes nothing the op computes. Two design questions -- "does the page cache ever
* hit" and "would a userspace cache of 160-byte rows beat it, being 25x denser than a 4 KiB page
* holding one useful row" -- are the SAME question about the n-gram reuse rate, and that is a
* property of the text being generated rather than of this code. This is how to measure it on a
* real generation.
*
* ---- WHAT IT SHOWS ON A PREFILL, WHICH IS WHERE THE ROWS ARE ----------------------------------
*
* A ~24k-token prefill of prose, both ranks traced, with the rows read through the container's
* mapping rather than the row cache (fault counts from /proc/<pid>/stat):
*
* 762,432 rows gathered 277,911 distinct 450,608 MINOR faults 2 MAJOR
*
* THE PAGE CACHE HITS ESSENTIALLY ALWAYS once warm. Two major faults over a whole prefill: what a
* read through the mapping pays instead is PAGE-TABLE POPULATION -- a minor fault to map an
* already-cached page, about 1.2 of them per row gathered, at roughly a microsecond each.
*
* THE DENSITY ARGUMENT HOLDS AND IT IS THE WHOLE PRIZE. The distinct rows a prefill wants land on
* 274,887 distinct 4 KiB pages: 1.011 USEFUL ROWS A PAGE, where a page holds 25. So 44.5 MB of
* wanted row bytes is reached through 1.13 GB of page mapping. The packed row cache above keeps
* only the rows touched and pays no mapping at all.
*
* THE REUSE RATE ALONE DOES NOT CARRY IT. Per rank the same prefill gathers 381,216 rows over
* 277,911 distinct ones -- 1.37x, and 86% of rows are wanted exactly once. A cache justified by
* reuse would be a poor bet; one justified by density is a good one, and those are different
* arguments for the same structure.
*
* ---- AND AT DECODE, WHERE THE STEP WAITS ON IT ------------------------------------------------
*
* Eight varied sequences at a depth-3 verify, one rank traced: a call is 512 rows over ~487
* distinct ones, and 50.6% of those are rows the generation has never asked for before -- the
* floor for any cache. The rest recur within a short window: a row-granular LRU of 10^5 rows misses
* 57.8%, of 4 x 10^5 rows 51.2%, and larger buys nothing. RowCache -- 2^19 rows, eight ways, CLOCK,
* shared by the ranks -- misses 51.0% on the same trace.
*
* (The even split in the raw trace is the two RANKS, not reuse. Both hash the same ids and gather
* the same rows -- see the replication note in arch/common/rad_block_ple.h, which prices that.) */
inline std::FILE* trace_file() {
static thread_local bool tried = false;
static thread_local std::FILE* f = nullptr;
if (!tried) {
tried = true;
const char* p = std::getenv("AVX_PLE_TRACE");
if (p && *p) f = std::fopen(p, "ae");
}
return f;
}
#else /* not Linux: no file reads; a table is read as memory */
struct TableFile { int fd = -1; };
inline const TableFile* table_file(const uint8_t*, long long, int*) { static TableFile m; return &m; }
inline std::FILE* trace_file() { return nullptr; }
#endif
} // namespace
int avx::row_gather(const RowGather& q, RowDecode decode) {
if (!decode || !q.ids || !q.tab || !q.out || q.M <= 0 || q.n_embd <= 0 || q.n_vocab <= 0 ||
q.row_bytes < q.n_embd)
return RAD_E_INVAL;
/* WHAT THIS OP COSTS HAS TWO REGIMES, and a benchmark that repeats one prompt only ever shows
* the cheap one. Greedy repeat traffic walks the SAME n-gram rows every step, so every row is
* already in the row cache and the call reads nothing. Varied serving makes about half of every
* step's rows new, and the call waits on the NVMe for those. /proc/<pid>/io says which regime a
* number came from, and AVX_PLE_TRACE records the rows themselves. */
if (std::FILE* tf = trace_file()) {
for (long long m = 0; m < q.M; ++m)
std::fprintf(tf, "%lld\n", (long long)q.ids[m] - q.voff);
}
/* Every E4M3 code's bf16 at this call's scale, so the decode is a table lookup. The ABI's own
* converters, so the answer is libref's by construction. */
uint16_t lut[256];
for (int b = 0; b < 256; ++b)
lut[b] = rad_f32_to_bf16(rad_fp8e4m3_to_f32((uint8_t)b) * q.scale);
/* The rows: through the shared cache from the file behind the table, or, for a table no file
* backs, from the table itself. The caller has refused an id past the table already; an id
* turned into a file offset has to be one. */
int ferr = RAD_OK;
const TableFile* tfile = table_file(q.tab, q.n_vocab * q.row_bytes, &ferr);
if (!tfile) return ferr;
#if defined(__linux__)
if (tfile->fd >= 0) {
ReadRing* rr = read_ring();
RowCache* rc = row_cache(tfile, q.row_bytes);
if (!rr || !rc) return RAD_E_UNSUPPORTED;
const long long ws = q.world_size > 1 ? q.world_size : 1;
const long long first = q.rank > 0 && q.rank < ws ? q.M * q.rank / ws : 0;
const int rs = gather_rows(*tfile, *rc, *rr, q, first, decode, lut);
if (rs != RAD_OK) return rs;
/* The rows a later call will gather, read while the step runs. After this call's own
* rows, so they never compete with them. */
if (q.ahead && q.n_ahead > 0) read_ahead(*tfile, *rc, q);
return RAD_OK;
}
#endif
Gather& g = gather_state();
g.src.clear();
g.dst.clear();
for (long long m = 0; m < q.M; ++m) {
const long long id = (long long)q.ids[m] - q.voff;
uint16_t* dst = q.out + m * q.x_ld;
if (id < 0 || id >= q.n_vocab) {
std::memset(dst, 0, (size_t)q.n_embd * sizeof(uint16_t));
continue;
}
g.src.push_back(q.tab + id * q.row_bytes);
g.dst.push_back(dst);
}
if (!g.src.empty()) decode(g.src.data(), g.dst.data(), (int64_t)g.src.size(), q.n_embd, lut);
return RAD_OK;
}
/* ============================== THE TABLE'S ENCODING, AND ITS ONE SCALE ==============================
*
* Asked at declare, not by a step (spec §4.3).
*
* The table is E4M3, row-major, with ONE bf16 scale for all of it -- `fp8_e4m3*bf16[*x*]`. That
* is not a simplification of a per-block scheme: it is the shipped format, and the structure of
* the data is why it works. E4M3 carries its own exponent; a row of this table has a dynamic range
* of only about 2.3x; and the error sits on a THREE-OCTAVE PLATEAU in the scale, so any value from
* 2^-13 to 2^-10 gives the same relative L2 error to five digits. A per-row scale would buy a few
* percent of that error for 1.25% more bytes, which is why the format has none. (INT8 in the same
* byte would buy several times more, because it spends all eight bits on resolution rather than
* four on an exponent this data does not need. That is a different format.)
*
* IT IS STORED AS IT IS: the gather reads the canonical rows, and that is what lets the table be
* read in place from the container's mapping -- a relayout would need a copy of 51 GB. So this
* hook only checks, and a table quantised any other way is refused at declare rather than
* gathered as noise. A plain bf16 table -- the checkpoint's own, 102 GB -- is the one other form
* it takes, read the same way with no scale. */
namespace {
enum { EQ_TOK = 0, EQ_WTE, EQ_SCALE, EQ_X, EQ_AHEAD };
} /* namespace */
extern "C" int avx_layout_ngram(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* pl, int n, RadLayout* out) {
(void)out;
if (operand != EQ_WTE && operand != EQ_SCALE) return RAD_E_UNSUPPORTED;
const long long rows = rad_param_geti(p, n_p, "n_vocab", 0);
const long long dim = rad_param_geti(p, n_p, "n_embd", 0);
if (rows <= 0 || dim <= 0) return RAD_E_SHAPE;
/* OR THE TABLE AS THE CHECKPOINT SHIPS IT: plain bf16, no scale -- the gather copies its rows
* through the same cache. It has no scale plane, so only the table is ever asked about. */
if (rad_enc_is(enc, "plain") && enc->n_planes == 1 && enc->plane[0].dtype == RAD_BF16) {
if (operand != EQ_WTE) return RAD_E_DTYPE;
if (n != 1 || !pl) return RAD_E_SHAPE;
if (pl[0].rank != 2 || pl[0].shape[0] != rows || pl[0].shape[1] != dim) return RAD_E_SHAPE;
return RAD_E_UNSUPPORTED;
}
const RadEncPlane* sc = rad_enc_plane(enc, "scale");
if (!rad_enc_is(enc, "affine") || enc->n_planes != 2 || enc->transform[0] ||
enc->plane[0].dtype != RAD_F8E4M3 || !sc || sc->dtype != RAD_BF16 || sc->block[0] != 0 ||
sc->block[1] != 0)
return RAD_E_DTYPE;
if (n != 1 || !pl || !sel) return RAD_E_SHAPE;
const char* want = operand == EQ_WTE ? "codes" : "scale";
if (std::strncmp(enc->plane[sel[0]].role, want, RAD_ENC_STR) != 0) return RAD_E_SHAPE;
const long long r = operand == EQ_WTE ? rows : 1, c = operand == EQ_WTE ? dim : 1;
if (pl[0].rank != 2 || pl[0].shape[0] != r || pl[0].shape[1] != c) return RAD_E_SHAPE;
return RAD_E_UNSUPPORTED;
}
+278
View File
@@ -0,0 +1,278 @@
/* avx_norm.cpp -- rmsnorm, rmsnorm_add and layernorm.
*
* ============================== ONE PASS OVER THE ROW, TWICE ==============================
*
* Every norm here is a REDUCTION followed by a SCALE, which means two passes over the row and no
* way around it: the scale needs a number the whole row contributed to. What can be avoided is
* paying for the dtype conversion twice, and that is the shape of every kernel below -- convert
* the row to f32 ONCE into scratch, reduce out of scratch, scale out of scratch. libref converts
* per element and therefore converts each element three times in rmsnorm_add.
*
* The reduction itself is `row_sumsq` (avx_support.cpp), which is a four-accumulator vector tree.
* That does NOT sum in libref's ascending-index order, and it is the whole reason the bf16
* tolerance for a norm is 4e-3 rather than zero. Stated here because it is the one thing about
* these kernels that a reader should not have to derive: the arithmetic is the same, the ORDER is
* not, and the order is what a tolerance is for.
*
* ============================== THE TWO ROUNDING CONTRACTS ==============================
*
* `wadd` is GemmaRMSNorm's `1 +`, and it is added to the weight in f32 AFTER the weight has been
* widened -- never to the stored bf16 gain. Qwen3.5, Qwen3-Next and Gemma all store a zero-centred
* gain, and forming `1 + w` in bf16 first loses 0.3% per channel. libr4d's fused norms say the
* same thing; this is the third implementation of that sentence and they agree.
*
* `rmsnorm_add` takes the variance from the UNROUNDED f32 sum and the multiply from the sum AFTER
* it has been narrowed into residual_out. That asymmetry is not an accident of libref's loop: it
* is what vLLM's fused_add_rms_norm does, because the residual has to be stored anyway and
* re-reading it is free, and every fused kernel in this project will do it. An implementation that
* kept f32 throughout would be half an ulp better and would fail against every kernel it is meant
* to certify.
*/
#include "avx_vec.h"
#include "avx_common.h"
using namespace avx;
/* The gain row, widened once per LAUNCH rather than once per row.
*
* WHY THIS IS WORTH ITS OWN BUFFER: `w` is the same n elements for every one of `rows` rows, so
* converting it inside the row loop converts it `rows` times -- at a 4096-wide bf16 gain and a
* 2048-token prefill chunk that is 8 M pointless conversions. It cannot go in the thread_local
* scratch, because every thread needs it and they would each build their own; it is built once
* into a caller-provided buffer before the parallel region and read by all of them.
*
* `wadd` is folded in HERE, which is also where it is cheapest: once per element of the gain,
* rather than once per element of the output. */
static void widen_gain(const RadTensor* w, int64_t n, float wadd, float* out) {
const int64_t ws = laststride(w);
if (ws == 1) {
row_to_f32(w->dtype, w->data, out, n);
} else {
for (int64_t i = 0; i < n; ++i) out[i] = ldt(w, i * ws);
}
if (wadd != 0.0f) {
const vf va = vf_set1(wadd);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) vf_storeu(out + i, vf_add(vf_loadu(out + i), va));
for (; i < n; ++i) out[i] += wadd;
}
}
/* ------------------------------------------------------------------ rmsnorm */
/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd) */
AVX_KERNEL(rmsnorm) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *y = &a->t[2];
const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(y) < rows * n || numel(w) < n) return RAD_E_SHAPE;
float* gain = (float*)scratch_raw((size_t)n * sizeof(float));
widen_gain(w, n, wadd, gain);
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* sx = scratch_f32((size_t)n);
float* sy = scratch_f32_b((size_t)n);
const float* v = in_row(x, rowoff(x, r, n), n, sx);
const float ss = row_sumsq(v, n);
const float s = 1.0f / std::sqrt(ss / (float)n + eps);
const vf vs = vf_set1(s);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N)
vf_storeu(sy + i, vf_mul(vf_mul(vf_loadu(v + i), vs), vf_loadu(gain + i)));
for (; i < n; ++i) sy[i] = v[i] * s * gain[i];
out_row(y, rowoff(y, r, n), n, sy);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ rmsnorm_add */
/* residual_out = x + residual; y = rmsnorm(residual_out) * (w + wadd), with the variance from the
* unrounded sum and the multiply from the narrowed one. */
AVX_KERNEL(rmsnorm_add) {
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *res = &a->t[1], *w = &a->t[2], *y = &a->t[3], *ro = &a->t[4];
const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(y) < rows * n || numel(ro) < rows * n ||
numel(res) < rows * n || numel(w) < n) return RAD_E_SHAPE;
float* gain = (float*)scratch_raw((size_t)n * sizeof(float));
widen_gain(w, n, wadd, gain);
const uint32_t ro_dt = ro->dtype;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* sx = scratch_f32((size_t)n);
float* sr = scratch_f32_b((size_t)n);
float* sm = scratch_f32_c((size_t)n);
const float* xv = in_row(x, rowoff(x, r, n), n, sx);
const float* rv = in_row(res, rowoff(res, r, n), n, sr);
vf acc0 = vf_zero(), acc1 = vf_zero();
int64_t i = 0;
for (; i + 2 * VF_N <= n; i += 2 * VF_N) {
vf s0 = vf_add(vf_loadu(xv + i), vf_loadu(rv + i));
vf s1 = vf_add(vf_loadu(xv + i + VF_N), vf_loadu(rv + i + VF_N));
vf_storeu(sm + i, s0);
vf_storeu(sm + i + VF_N, s1);
acc0 = vf_fma(s0, s0, acc0);
acc1 = vf_fma(s1, s1, acc1);
}
float ss = vf_hsum(vf_add(acc0, acc1));
for (; i < n; ++i) { float v = xv[i] + rv[i]; sm[i] = v; ss += v * v; }
/* The residual is written from the UNROUNDED sum... */
out_row(ro, rowoff(ro, r, n), n, sm);
const float s = 1.0f / std::sqrt(ss / (float)n + eps);
/* ...and read back NARROWED for the multiply. Done in registers rather than by re-reading
* the operand: `row_from_f32` then `row_to_f32` over a hot buffer is the same arithmetic
* and does not depend on the store having retired. */
/* `sr` is reused as the narrowing buffer and that is not a shortcut, it is the ONLY slot
* available: `gain` lives in this thread's scratch_raw arena and calling scratch_raw again
* inside the parallel region would grow that arena, free the old block, and leave every
* other thread reading a dangling `gain`. `sr` is n floats -- 4n bytes -- which holds any
* dtype this operand can be, and `rv` (which may or may not be `sr`, depending on whether
* `residual` was already f32) is dead the moment the sum is formed. */
if (ro_dt != RAD_F32) {
row_from_f32(ro_dt, sm, sr, n);
row_to_f32(ro_dt, sr, sm, n);
}
const vf vs = vf_set1(s);
i = 0;
for (; i + VF_N <= n; i += VF_N)
vf_storeu(sm + i, vf_mul(vf_mul(vf_loadu(sm + i), vs), vf_loadu(gain + i)));
for (; i < n; ++i) sm[i] = sm[i] * s * gain[i];
out_row(y, rowoff(y, r, n), n, sm);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ layernorm */
/* y = (x - mean) * rsqrt(var + eps) * w + b, BIASED variance (divide by n), which is what every
* transformer implementation means by layer norm. `b` is optional -- a ViT that dropped its bias
* passes a null operand rather than a zero tensor. */
AVX_KERNEL(layernorm) {
if (a->n_t < 4 || !a->t[0].data || !a->t[1].data || !a->t[3].data) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *y = &a->t[3];
const RadTensor* b = rad_arg_in(a, 2);
const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-5f);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(y) < rows * n || numel(w) < n) return RAD_E_SHAPE;
if (b && numel(b) < n) return RAD_E_SHAPE;
/* Both the gain and the bias are launch-invariant, so both are widened once, into one
* allocation so there is a single scratch_raw call live at a time (avx_common.h: a second call
* may reallocate and invalidate the first pointer). */
float* gb = (float*)scratch_raw((size_t)(2 * n) * sizeof(float));
float* gain = gb;
float* bias = gb + n;
widen_gain(w, n, 0.0f, gain);
if (b) {
const int64_t bs = laststride(b);
if (bs == 1) row_to_f32(b->dtype, b->data, bias, n);
else for (int64_t i = 0; i < n; ++i) bias[i] = ldt(b, i * bs);
}
const bool has_b = b != nullptr;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* sx = scratch_f32((size_t)n);
float* sy = scratch_f32_b((size_t)n);
const float* v = in_row(x, rowoff(x, r, n), n, sx);
/* TWO PASSES, NOT THE ONE-PASS (sum, sumsq) FORM. The single-pass variance
* E[x^2] - E[x]^2 is one reduction instead of two and is catastrophically worse when the
* mean is large relative to the spread -- which is exactly a post-attention residual. What
* it costs here is one extra read of a row that is in L1 by then; what it would buy is a
* cancellation the tolerance would hide until it did not. libref takes the mean first too,
* so this also keeps the two agreeing for the right reason. */
const float mean = row_sum(v, n) / (float)n;
const vf vm = vf_set1(mean);
vf acc = vf_zero();
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) {
vf d = vf_sub(vf_loadu(v + i), vm);
acc = vf_fma(d, d, acc);
}
float ss = vf_hsum(acc);
for (; i < n; ++i) { float d = v[i] - mean; ss += d * d; }
const float s = 1.0f / std::sqrt(ss / (float)n + eps);
const vf vs = vf_set1(s);
i = 0;
for (; i + VF_N <= n; i += VF_N) {
vf t = vf_mul(vf_mul(vf_sub(vf_loadu(v + i), vm), vs), vf_loadu(gain + i));
if (has_b) t = vf_add(t, vf_loadu(bias + i));
vf_storeu(sy + i, t);
}
for (; i < n; ++i) {
float t = (v[i] - mean) * s * gain[i];
if (has_b) t += bias[i];
sy[i] = t;
}
out_row(y, rowoff(y, r, n), n, sy);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ grid_embed */
/* A learned side x side position table resampled bilinearly to each row's grid (corners aligned,
* edge taps clamped) and added in -- libref's grid_embed, operation for operation: the four taps
* summed in f32 in the same order, rounded to x's dtype, then added and rounded again. One row a
* vision-tower patch, off every step path, so it is written for clarity over lanes. */
AVX_KERNEL(grid_embed) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *tab = &a->t[1], *crd = &a->t[2];
const int64_t n = p_int(a, "n", tab->rank ? tab->shape[tab->rank - 1] : 0);
const int64_t side = p_int(a, "side", 0);
if (n <= 0 || side <= 0 || numel(tab) < side * side * n) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < rows)
return RAD_E_SHAPE;
const int64_t cs = crd->stride[0], ms = crd->stride[1];
const int64_t ts = laststride(tab);
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
int64_t g[4];
for (int c = 0; c < 4; ++c) g[c] = ldi(crd, c * cs + r * ms);
int64_t th[2], tw[2];
float wh[2], ww[2];
auto axis = [&](int64_t idx, int64_t size, int64_t* t, float* w) {
const float src = (float)idx * (float)(side - 1) / (float)(size - 1 > 1 ? size - 1 : 1);
const float fl = std::floor(src);
for (int k = 0; k < 2; ++k) {
const int64_t tap = (int64_t)fl + k;
t[k] = tap < 0 ? 0 : (tap > side - 1 ? side - 1 : tap);
const float d = std::fabs(src - fl - (float)k);
w[k] = 1.0f - d > 0.0f ? 1.0f - d : 0.0f;
}
};
axis(g[0], g[2], th, wh);
axis(g[1], g[3], tw, ww);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
for (int64_t i = 0; i < n; ++i) {
float acc = 0.0f;
for (int ki = 0; ki < 2; ++ki)
for (int kj = 0; kj < 2; ++kj)
acc += ldt(tab, rowoff(tab, th[ki] * side + tw[kj], n) + i * ts) *
(wh[ki] * ww[kj]);
float pe = acc;
if (x->dtype == RAD_BF16) pe = rad_bf16_to_f32(rad_f32_to_bf16(pe));
stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe);
}
}
return RAD_OK;
}
+617
View File
@@ -0,0 +1,617 @@
/* avx_quant.cpp -- the quantisers, the rotation, and the Gram accumulator.
*
* ============================== THE WALSH-HADAMARD IS BIT-IDENTICAL, ON PURPOSE ==============================
*
* The rotation is a sequence of butterflies at ascending strides 1, 2, 4, ... g/2, pairing i with
* i + h where (i & h) == 0. The butterfly matrices for different strides COMMUTE -- H is a tensor
* power of the 2x2 Hadamard -- so any order of `h` gives the same transform in exact arithmetic,
* and it is tempting to reorder them for the vectoriser.
*
* That temptation is refused here and the order is libref's exactly, ASCENDING, because commuting
* in exact arithmetic is not the same as commuting in f32: the intermediate values differ and the
* roundings land in different places. Keeping the order means every butterfly is the same add and
* the same subtract on the same two floats as the reference performs, so the rotated block is
* BIT-IDENTICAL and not merely close -- which is what lets the whole rotated-int8 family be held
* at the quantiser tolerance (1e-6) instead of a loosened one. What is vectorised is WHICH LANES a
* butterfly runs on, not the arithmetic:
*
* h >= VF_N the pair (i, i+h) is two whole vectors. One load, one add, one sub, two stores.
* h < VF_N the pair is inside one vector, so the partner is a SWIZZLE of it -- swap adjacent
* lanes, pairs of lanes, 128-bit lanes, 256-bit halves -- and the two results are
* selected by a lane mask. Four such steps at AVX-512, three at AVX2.
*
* Doing the small strides scalar was the obvious first implementation and it is the wrong one: at
* g = 128 and VF_N = 16 that is four scalar passes over 128 elements against three vector passes,
* so the part that was left scalar would be most of the cost.
*
* ============================== THE ROTATION IS PERFORMED ONCE, NOT TWICE ==============================
*
* libref rotates each block twice -- once to find the absolute maximum and once to write the codes
* -- because it has a 4096-float stack frame and no row-sized scratch. That is a factor of two on
* every rotated op and it is pure recomputation: the rotated row is deterministic. Here the whole
* row is rotated once into scratch, the maximum is taken over it, and the codes are written from
* it. Identical arithmetic, half the butterflies.
*
* ============================== THE TWO `group` READINGS, AND THE TWO sqrt(g) CONVENTIONS ==============================
*
* docs/OPS.md is explicit that `group` means two different things in this table and that a kernel
* reading it the other way is WRONG rather than slow:
*
* quant_act_i8, quant_act_fp8, dequant `group` is the number of contiguous elements sharing
* and the fp8 fusions one scale. `scale` is [M, ceil(n/group)].
* every had_* INT8 form `group` is the ROTATION WIDTH and the scale is per ROW,
* carrying the 1/sqrt(group).
* the had_* FP8 forms `group` is BOTH, and there is NO normalisation at all:
* <Hw, Ha> = g <w, a> and the whole factor g is folded
* into the stored weight scale at convert, where dividing
* a bf16 by a power of two is exact. Splitting it as the
* int8 forms do would round amax/7/sqrt(g) into bf16 and
* land ~0.2% of multiplicative error on every group.
*
* Three readings of one parameter name is not a pleasant fact, and it is the vocabulary's rather
* than this plugin's. It is restated here because getting it wrong produces a plausible number.
*/
#include "avx_vec.h"
#include "avx_common.h"
using namespace avx;
#include "avx_had.h"
/* ================================================================== int8 store
* `q` is almost always RAD_I8, in which case the row store is the vectorised cvtps/packs path
* (avx_vec.h) whose rounding is MXCSR round-to-nearest-even and whose saturation is the pack
* instruction's -- exactly libref's nearbyintf-and-clamp, bit for bit. Anything else falls back to
* the generic row store, which is correct and slower. */
static inline void store_codes(const RadTensor* q, int64_t base, int64_t n, const float* v) {
out_row(q, base, n, v);
}
/* Scale a row by a scalar, in place. */
static inline void scale_row(float* v, int64_t n, float s) {
const vf vs = vf_set1(s);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) vf_storeu(v + i, vf_mul(vf_loadu(v + i), vs));
for (; i < n; ++i) v[i] *= s;
}
/* ------------------------------------------------------------------ quant_act_i8 */
/* q = round(x * 127 / amax), scale = amax / 127, per `group` contiguous elements. An all-zero
* group gets scale 0 and codes 0, which dequantises back to zero -- the alternative, a tiny
* epsilon scale, turns a zero row into denormal noise in the GEMM that reads it. */
AVX_KERNEL(quant_act_i8) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(q) < rows * n) return RAD_E_SHAPE;
int64_t g = p_int(a, "group", 0);
if (g <= 0 || g > n) g = n;
const int64_t ngrp = (n + g - 1) / g;
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
/* DENSE-i8 FAST PATH: the per-group scale feeds the int8 encoder directly, with no f32
* scratch round trip between them. */
if (q->dtype == RAD_I8 && dense_row(q)) {
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* buf = scratch_f32((size_t)n);
const float* v = in_row(x, rowoff(x, r, n), n, buf);
int8_t* qb = (int8_t*)byte_at(q->data, q->dtype, rowoff(q, r, n));
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
const float amax = row_amax(v + k0, k1 - k0);
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
cvt_scaled_f32_to_i8(v + k0, inv, qb + k0, k1 - k0);
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), amax / 127.0f);
}
}
return RAD_OK;
}
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* buf = scratch_f32((size_t)n);
const float* v = in_row(x, rowoff(x, r, n), n, buf);
float* w = scratch_f32_b((size_t)n);
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
const float amax = row_amax(v + k0, k1 - k0);
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
const vf vi = vf_set1(inv);
int64_t i = k0;
for (; i + VF_N <= k1; i += VF_N) vf_storeu(w + i, vf_mul(vf_loadu(v + i), vi));
for (; i < k1; ++i) w[i] = v[i] * inv;
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), amax / 127.0f);
}
store_codes(q, rowoff(q, r, n), n, w);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ had_quant_act_i8 */
/* Rotation at width `group`, then symmetric int8 with ONE scale per ROW carrying the
* 1/sqrt(group). The absolute maximum is over the WHOLE rotated row, because the scale is per row. */
AVX_KERNEL(had_quant_act_i8) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
const int64_t n = p_int(a, "n", 0);
const int64_t g = p_int(a, "group", 0);
if (n <= 0 || !pow2(g) || n % g != 0) return RAD_E_SHAPE;
if (g > AVX_HAD_MAX) return RAD_E_UNSUPPORTED;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows) return RAD_E_SHAPE;
const float norm = 1.0f / std::sqrt((float)g);
/* Same dense-i8 fusion as quant_act_i8: the rotation stays, but its output is scaled +
* encoded straight to bytes. The amax here is whole-row (one scale per row), so the fusion
* is a single call rather than per group. */
if (q->dtype == RAD_I8 && dense_row(q)) {
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* buf = scratch_f32((size_t)n);
const float* v = in_row(x, rowoff(x, r, n), n, buf);
if (v != buf) std::memcpy(buf, v, (size_t)n * sizeof(float));
fwht_row(buf, n, g);
const float amax = row_amax(buf, n);
cvt_scaled_f32_to_i8(buf, amax > 0.0f ? 127.0f / amax : 0.0f,
(int8_t*)byte_at(q->data, q->dtype, rowoff(q, r, n)), n);
stt(s, r * laststride(s), amax / 127.0f * norm);
}
return RAD_OK;
}
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* buf = scratch_f32((size_t)n);
/* in_row may hand back the operand's own pointer for a dense f32 input, and the rotation
* is IN PLACE -- so the row is copied into scratch whenever that happened. Rotating the
* caller's activation would be a kernel that destroys its own input. */
const float* v = in_row(x, rowoff(x, r, n), n, buf);
if (v != buf) std::memcpy(buf, v, (size_t)n * sizeof(float));
fwht_row(buf, n, g);
const float amax = row_amax(buf, n);
scale_row(buf, n, amax > 0.0f ? 127.0f / amax : 0.0f);
store_codes(q, rowoff(q, r, n), n, buf);
stt(s, r * laststride(s), amax / 127.0f * norm);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ rmsnorm_had_quant_i8 */
/* The fused rmsnorm + hadamard + quant_act_i8 a w4a8 layer wants where a bf16 layer wants a plain
* rmsnorm.
*
* `residual` PRESENT IS THE fused_add_rms_norm FORM: the add happens first, the sum is written
* back into `residual` (that is what makes it INOUT and what the next layer's shortcut reads), and
* the norm is taken over the sum. The variance comes from the f32 sum and the rotation reads the
* sum back AFTER it has been narrowed to the residual tensor's own dtype -- which is what the pair
* of kernels this replaces does, and matching it is what makes the fused form substitutable for
* that pair.
*
* `out_bf16` is the post-norm, PRE-ROTATION tensor for a layer that also has a bf16 consumer: the
* rotation is an artefact of the int8 path, and a bf16 consumer wants the normalised activation
* rather than a Walsh-Hadamard of it. */
AVX_KERNEL(rmsnorm_had_quant_i8) {
if (a->n_t < 5) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[2], *q = &a->t[3], *s = &a->t[4];
const RadTensor* res = rad_arg_in(a, 1);
const RadTensor* ob = rad_arg_in(a, 5);
if (!x->data || !w->data || !q->data || !s->data) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0);
const int64_t g = p_int(a, "group", 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
if (n <= 0 || !pow2(g) || n % g != 0) return RAD_E_SHAPE;
if (g > AVX_HAD_MAX) return RAD_E_UNSUPPORTED;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows || numel(w) < n) return RAD_E_SHAPE;
if (res && numel(res) < rows * n) return RAD_E_SHAPE;
if (ob && numel(ob) < rows * n) return RAD_E_SHAPE;
const float norm = 1.0f / std::sqrt((float)g);
/* The gain, widened once per launch with `wadd` already folded in -- see avx_norm.cpp on why
* this cannot live in the per-thread scratch. */
float* gain = (float*)scratch_raw((size_t)n * sizeof(float));
{
const int64_t ws = laststride(w);
if (ws == 1) row_to_f32(w->dtype, w->data, gain, n);
else for (int64_t i = 0; i < n; ++i) gain[i] = ldt(w, i * ws);
if (wadd != 0.0f) for (int64_t i = 0; i < n; ++i) gain[i] += wadd;
}
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* src = scratch_f32((size_t)n);
float* buf = scratch_f32_b((size_t)n);
float* tmp = scratch_f32_c((size_t)n);
if (res) {
/* x + residual, stored back, then READ BACK NARROWED -- the round trip is the
* contract. Done through a hot buffer rather than by re-reading the operand: same
* arithmetic, and it does not depend on the store having retired. */
const float* xv = in_row(x, rowoff(x, r, n), n, src);
const float* rv = in_row(res, rowoff(res, r, n), n, tmp);
for (int64_t i = 0; i < n; ++i) buf[i] = xv[i] + rv[i];
out_row(res, rowoff(res, r, n), n, buf);
if (res->dtype != RAD_F32) {
row_from_f32(res->dtype, buf, tmp, n);
row_to_f32(res->dtype, tmp, buf, n);
}
std::memcpy(src, buf, (size_t)n * sizeof(float));
} else {
const float* xv = in_row(x, rowoff(x, r, n), n, src);
if (xv != src) std::memcpy(src, xv, (size_t)n * sizeof(float));
}
const float sc = 1.0f / std::sqrt(row_sumsq(src, n) / (float)n + eps);
const vf vsc = vf_set1(sc);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N)
vf_storeu(buf + i, vf_mul(vf_mul(vf_loadu(src + i), vsc), vf_loadu(gain + i)));
for (; i < n; ++i) buf[i] = src[i] * sc * gain[i];
if (ob) out_row(ob, rowoff(ob, r, n), n, buf); /* post-norm, PRE-rotation */
fwht_row(buf, n, g);
const float amax = row_amax(buf, n);
scale_row(buf, n, amax > 0.0f ? 127.0f / amax : 0.0f);
store_codes(q, rowoff(q, r, n), n, buf);
stt(s, r * laststride(s), amax / 127.0f * norm);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gated_had_quant_i8 */
/* An elementwise gated product, then the rotation and the quantiser. `act` picks between the two
* rotated sites a w4a8 model has: silu(a)*b is down_proj's input, sigmoid(a)*b is o_proj's on a
* gated-attention layer. `mode` is libr4d's integer spelling of the same choice.
*
* `b` ABSENT IS THE PACKED FORM: `a` is [M, 2n], gate first half, up second -- which is what a
* fused gate_up projection produces. Two operands with the second optional is the only shape that
* expresses both readings. */
AVX_KERNEL(gated_had_quant_i8) {
if (a->n_t < 4) return RAD_E_INVAL;
const RadTensor *ga = &a->t[0], *q = &a->t[2], *s = &a->t[3];
const RadTensor* up = rad_arg_in(a, 1);
if (!ga->data || !q->data || !s->data) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0);
const int64_t g = p_int(a, "group", 0);
static const char* kActs[] = { "silu", "sigmoid" };
const int act = p_enum(a, "act", kActs, 2, (int)p_int(a, "mode", 0));
if (n <= 0 || !pow2(g) || n % g != 0) return RAD_E_SHAPE;
if (act != 0 && act != 1) return RAD_E_INVAL;
if (g > AVX_HAD_MAX) return RAD_E_UNSUPPORTED;
const int64_t rows = numel(q) / n;
if (rows <= 0 || numel(s) < rows) return RAD_E_SHAPE;
if (numel(ga) < rows * (up ? n : 2 * n)) return RAD_E_SHAPE;
if (up && numel(up) < rows * n) return RAD_E_SHAPE;
const float norm = 1.0f / std::sqrt((float)g);
const int64_t gw = up ? n : 2 * n;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* gbuf = scratch_f32((size_t)gw);
float* ubuf = scratch_f32_b((size_t)n);
float* out = scratch_f32_c((size_t)n);
const float* gv = in_row(ga, rowoff(ga, r, gw), gw, gbuf);
const float* uv = up ? in_row(up, rowoff(up, r, n), n, ubuf) : gv + n;
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) {
const vf gt = vf_loadu(gv + i);
const vf act_v = (act == 1) ? vf_sigmoid(gt) : vf_silu(gt);
vf_storeu(out + i, vf_mul(act_v, vf_loadu(uv + i)));
}
for (; i < n; ++i) {
const float gt = gv[i];
const float sg = 1.0f / (1.0f + std::exp(-gt));
out[i] = (act == 1 ? sg : gt * sg) * uv[i];
}
fwht_row(out, n, g);
const float amax = row_amax(out, n);
scale_row(out, n, amax > 0.0f ? 127.0f / amax : 0.0f);
store_codes(q, rowoff(q, r, n), n, out);
stt(s, r * laststride(s), amax / 127.0f * norm);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ dequant */
/* q * scale, with the SCALE STREAM'S OWN EXTENT deciding how many groups there are. The inverse of
* quant_act_i8 and NOT of the rotated forms: undoing a rotation is a second Hadamard, and an op
* that silently did one would make `dequant(had_quant(x)) == x` look true when the two have
* different meanings. */
AVX_KERNEL(dequant) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *s = &a->t[1], *y = &a->t[2];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = numel(y) / n;
if (rows <= 0 || numel(q) < rows * n) return RAD_E_SHAPE;
const int64_t ngrp = numel(s) / rows > 0 ? numel(s) / rows : 1;
int64_t g = p_int(a, "group", 0);
if (g <= 0) g = (n + ngrp - 1) / ngrp;
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* buf = scratch_f32((size_t)n);
float* out = scratch_f32_b((size_t)n);
const float* v = in_row(q, rowoff(q, r, n), n, buf);
const int64_t sb = rowoff(s, r, ngrp), ss = laststride(s);
/* GROUP BY GROUP, with the scale hoisted out of the element loop. libref reads the scale
* per element through a divide; the group edge is known here, so the divide happens once
* per group and the body is a vector multiply. Same product, same order. */
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g;
if (k0 >= n) break;
const int64_t k1 = (k0 + g < n) ? k0 + g : n;
const float sc = ldt(s, sb + gi * ss);
const vf vs = vf_set1(sc);
int64_t i = k0;
for (; i + VF_N <= k1; i += VF_N) vf_storeu(out + i, vf_mul(vf_loadu(v + i), vs));
for (; i < k1; ++i) out[i] = v[i] * sc;
}
/* A row longer than the groups describe takes the LAST group's scale, which is libref's
* clamp (`gi < ngrp ? gi : ngrp - 1`) and is what a ragged final group means. */
if (ngrp * g < n) {
const float sc = ldt(s, sb + (ngrp - 1) * ss);
for (int64_t i = ngrp * g; i < n; ++i) out[i] = v[i] * sc;
}
out_row(y, rowoff(y, r, n), n, out);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ quant_act_fp8 */
/* The three choices this shares with libr4d's kernel, none of them derivable:
*
* 448 E4M3's largest finite value, and the scale is `amax / 448` -- a DEQUANT multiplier,
* the same sense as the checkpoint's `weight_scale_inv`, so the GEMM's fold multiplies
* the two scales together and nothing has to be inverted.
* scale 1 for an all-zero group, where amax/448 is zero and its reciprocal infinite. NOT the
* zero scale quant_act_i8 uses: that kernel's consumer reads a per-row int8 scale and
* a zero row is a zero row, while here the GEMM multiplies the two block scales and a
* zero would erase the weight's.
* the clamp is not defensive. amax * (1/scale) is 448 in exact arithmetic and can land an ulp
* above it once the reciprocal is rounded, which encodes as a NaN rather than as the
* largest finite. */
AVX_KERNEL(quant_act_fp8) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(q) < rows * n) return RAD_E_SHAPE;
int64_t g = p_int(a, "group", 0);
if (g <= 0 || g > n) g = n;
const int64_t ngrp = (n + g - 1) / g;
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* buf = scratch_f32((size_t)n);
float* out = scratch_f32_b((size_t)n);
const float* v = in_row(x, rowoff(x, r, n), n, buf);
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
float sc;
fp8_group(v, out, k0, k1, &sc);
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
out_row(q, rowoff(q, r, n), n, out);
}
return RAD_OK;
}
/* ------------------------------------------------------------- rmsnorm_quant_fp8 */
/* RMS norm, an optional residual add, and quant_act_fp8, in one pass.
*
* `residual` PRESENT IS THE fused_add_rms_norm FORM and the add is STORED BEFORE THE VARIANCE READS
* IT: the sum goes back into `residual`, narrowed to that tensor's dtype, and the norm -- variance
* included -- is taken over the narrowed sum. That is the `add` + `rmsnorm` pair, and not
* rmsnorm_add, which takes its variance from the unrounded sum. The normalised row is then narrowed
* to bf16 and the codes taken over it (avx_had.h). */
AVX_KERNEL(rmsnorm_quant_fp8) {
if (a->n_t < 5) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[2], *q = &a->t[3], *s = &a->t[4];
const RadTensor* res = rad_arg_in(a, 1);
const RadTensor* ob = rad_arg_in(a, 5);
if (!x->data || !w->data || !q->data || !s->data) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
if (n <= 0) return RAD_E_SHAPE;
int64_t g = p_int(a, "group", 0);
if (g <= 0 || g > n) g = n;
const int64_t ngrp = (n + g - 1) / g;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows * ngrp || numel(w) < n)
return RAD_E_SHAPE;
if (res && numel(res) < rows * n) return RAD_E_SHAPE;
if (ob && numel(ob) < rows * n) return RAD_E_SHAPE;
/* The gain with `wadd` folded in, widened once on the calling thread -- see avx_norm.cpp on
* why it cannot live in the per-thread scratch. */
float* gain = (float*)scratch_raw((size_t)n * sizeof(float));
{
const int64_t ws = laststride(w);
if (ws == 1) row_to_f32(w->dtype, w->data, gain, n);
else for (int64_t i = 0; i < n; ++i) gain[i] = ldt(w, i * ws);
if (wadd != 0.0f) for (int64_t i = 0; i < n; ++i) gain[i] += wadd;
}
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* src = scratch_f32((size_t)n);
float* buf = scratch_f32_b((size_t)n);
float* tmp = scratch_f32_c((size_t)n);
if (res) {
const float* xv = in_row(x, rowoff(x, r, n), n, src);
const float* rv = in_row(res, rowoff(res, r, n), n, tmp);
for (int64_t i = 0; i < n; ++i) buf[i] = xv[i] + rv[i];
out_row(res, rowoff(res, r, n), n, buf);
if (res->dtype != RAD_F32) {
row_from_f32(res->dtype, buf, tmp, n);
row_to_f32(res->dtype, tmp, buf, n);
}
std::memcpy(src, buf, (size_t)n * sizeof(float));
} else {
const float* xv = in_row(x, rowoff(x, r, n), n, src);
if (xv != src) std::memcpy(src, xv, (size_t)n * sizeof(float));
}
const float sc = 1.0f / std::sqrt(row_sumsq(src, n) / (float)n + eps);
const vf vsc = vf_set1(sc);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N)
vf_storeu(buf + i, vf_mul(vf_mul(vf_loadu(src + i), vsc), vf_loadu(gain + i)));
for (; i < n; ++i) buf[i] = src[i] * sc * gain[i];
narrow_bf16(buf, n, tmp);
fp8_emit(buf, src, n, g, q, s, ob, r);
}
return RAD_OK;
}
/* ------------------------------------------------------------- gated_quant_fp8 */
/* act(gate) * up over a PACKED [M, 2n] gate_up plane, gate half first, then quant_act_fp8 over the
* bf16-narrowed product. `act` is silu or sigmoid, `mode` libr4d's integer spelling of the same
* choice, silu when neither is given. */
AVX_KERNEL(gated_quant_fp8) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *gu = &a->t[0], *q = &a->t[1], *s = &a->t[2];
const RadTensor* ob = rad_arg_in(a, 3);
const int64_t n = p_int(a, "n", 0);
static const char* kActs[] = { "silu", "sigmoid" };
const int act = p_enum(a, "act", kActs, 2, (int)p_int(a, "mode", 0));
if (n <= 0) return RAD_E_SHAPE;
if (act != 0 && act != 1) return RAD_E_INVAL;
int64_t g = p_int(a, "group", 0);
if (g <= 0 || g > n) g = n;
const int64_t ngrp = (n + g - 1) / g;
const int64_t rows = numel(gu) / (2 * n);
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows * ngrp) return RAD_E_SHAPE;
if (ob && numel(ob) < rows * n) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* gbuf = scratch_f32((size_t)(2 * n));
float* out = scratch_f32_b((size_t)n);
float* tmp = scratch_f32_c((size_t)n);
const float* gv = in_row(gu, rowoff(gu, r, 2 * n), 2 * n, gbuf);
gate_bf16(gv, gv + n, out, n, act, tmp);
fp8_emit(out, tmp, n, g, q, s, ob, r);
}
return RAD_OK;
}
/* ------------------------------------------------------------- had_quant_act_fp8 */
/* The same quantiser with a `group`-wide Hadamard in front of the absmax, which is the only place
* a rotation can go: the whole benefit is that the maximum the grid is scaled by gets smaller.
*
* THE sqrt(g) IS NOT UNDONE HERE, and that is a deliberate difference from had_quant_act_i8 above,
* which folds 1/sqrt(g) into its own scale. H is symmetric, so <Hw, Ha> = g <w, a>, and the
* residual g has to be divided out exactly once between the two sides. The int8 op splits it; this
* one gives the WHOLE factor to the weight, where dividing a bf16 scale by a power of two is an
* exponent shift and therefore exact. */
AVX_KERNEL(had_quant_act_fp8) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
const int64_t n = p_int(a, "n", 0);
const int64_t g = p_int(a, "group", 0);
/* n % g != 0 is refused rather than rounded: a rotation block that straddled the end of the
* row would mix real values with padding, and no weight block was rotated that way. */
if (n <= 0 || !pow2(g) || n % g != 0) return RAD_E_SHAPE;
if (g > AVX_HAD_MAX) return RAD_E_UNSUPPORTED;
const int64_t rows = numel(x) / n;
const int64_t ngrp = n / g;
if (rows <= 0 || numel(q) < rows * n) return RAD_E_SHAPE;
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* buf = scratch_f32((size_t)n);
float* out = scratch_f32_b((size_t)n);
const float* v = in_row(x, rowoff(x, r, n), n, buf);
if (v != buf) std::memcpy(buf, v, (size_t)n * sizeof(float));
fwht_row(buf, n, g);
for (int64_t gi = 0; gi < ngrp; ++gi) {
float sc;
fp8_group(buf, out, gi * g, gi * g + g, &sc);
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
out_row(q, rowoff(q, r, n), n, out);
}
return RAD_OK;
}
/* ---------------------------------------------------------------- the Gram accumulator
*
* h[k1][k2] += sum over rows of x[m][k1] * x[m][k2], where x is the DEQUANTISED E4M3 input, or a
* bf16 input as it stands when no scale is passed -- the second moment GPTQ's error feedback
* needs, over exactly the operand the expert GEMM contracts.
*
* `h` IS READ AS WELL AS WRITTEN and that is the op: the caller zeroes it once and drives a whole
* calibration corpus through the graph, so each launch adds its own block. An implementation that
* stored instead of added would agree on one call and disagree on a corpus.
*
* THE ACCUMULATION IS f64 HERE AND f32 ON THE DEVICE, and that is libref's choice reproduced
* rather than an accident: this is the one op in the vocabulary whose result is consumed OFFLINE,
* by the packer, through a file -- so being tighter than the kernel is the right trade, and the
* kbench tolerance covers the gap. It also means the inner reduction is NOT the f32 vector path
* the rest of this file uses; there is nothing to vectorise about an f64 accumulation of an f32
* product that would not change the answer.
*
* What IS vectorised is the dequantisation: rows are widened and scaled once into a scratch plane
* rather than inside the k2 loop, which is O(n^2 * rows) with a per-element dtype dispatch in it
* otherwise. */
AVX_KERNEL(gram_accum) {
/* `a_scale` is optional: absent, `a` is read as it stands, which is the bf16 form. */
if (a->n_t < 3) return RAD_E_INVAL;
const RadTensor *x = rad_arg_in(a, 0), *s = rad_arg_in(a, 1), *h = rad_arg_in(a, 2);
if (!x || !h) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0);
const int64_t g = s ? p_int(a, "group", 0) : n;
if (n <= 0 || g <= 0) return RAD_E_SHAPE;
const int64_t rows = numel(x) / n;
const int64_t ngrp = (n + g - 1) / g;
if (rows <= 0 || (s && numel(s) < rows * ngrp)) return RAD_E_SHAPE;
if (h->rank != 2 || h->shape[0] != n || h->shape[1] != n) return RAD_E_SHAPE;
float* xs = (float*)scratch_raw((size_t)rows * (size_t)n * sizeof(float) + 64);
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* buf = scratch_f32((size_t)n);
const float* v = in_row(x, rowoff(x, r, n), n, buf);
float* dst = xs + r * n;
const int64_t sb = s ? rowoff(s, r, ngrp) : 0, sst = s ? laststride(s) : 0;
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
const float sc = s ? ldt(s, sb + gi * sst) : 1.0f;
const vf vs = vf_set1(sc);
int64_t k = k0;
for (; k + VF_N <= k1; k += VF_N) vf_storeu(dst + k, vf_mul(vf_loadu(v + k), vs));
for (; k < k1; ++k) dst[k] = v[k] * sc;
}
}
const int64_t hst = laststride(h);
AVX_PARALLEL_FOR_IF(n * n >= 1024)
for (int64_t k1 = 0; k1 < n; ++k1) {
const int64_t hb = rowoff(h, k1, n);
for (int64_t k2 = 0; k2 < n; ++k2) {
double acc = 0.0;
for (int64_t r = 0; r < rows; ++r)
acc += (double)xs[r * n + k1] * (double)xs[r * n + k2];
const int64_t off = hb + k2 * hst;
stt(h, off, (float)((double)ldt(h, off) + acc));
}
}
return RAD_OK;
}
+797
View File
@@ -0,0 +1,797 @@
/* avx_registry.cpp -- what libavx contains, in the two forms the core reads it in.
*
* ============================== THE SCHEMAS ARE libref's, DELIBERATELY IDENTICAL ==============================
*
* The first plugin in hierarchy order to declare an op FIXES its schema, and a later plugin
* declaring the same op name with a different one is refused AT LOAD with both plugins named
* (rad_abi.h). The check is core/plugin/loader.cpp:schema_same, and what it holds is: the
* parameter list position for position -- key, type, requiredness -- and the operand list position
* for position -- role and optionality. Operand NAMES are explicitly not load-bearing.
*
* So this table is libref's, slot for slot. It is COPIED rather than shared, and that is the ABI
* boundary working as designed rather than a missed refactor: a plugin links abi/ and nothing
* else, so there is no header for libref's table to live in that libavx could include without
* making one plugin depend on another's source. What replaces the shared header is a TEST:
* rad-avx-check opens both plugins and runs the loader's own comparison over all seventy-five
* schemas before it checks a single number, and fails loudly on the first disagreement. A copy
* that is checked on every run is a copy that cannot drift; a copy that is merely intended to
* match is a copy that eventually does.
*
* ============================== WHY THE ROWS CARRY NO opd_shape ==============================
*
* `RadKernelInfo::opd_shape` answers "how big is operand i of this op at this geometry" for a tool
* calling the op cold, and libref implements one for every op in the conventional vocabulary --
* 88 KB of judgement calls about index ranges, fill domains and what a ragged batch means. libavx
* computes exactly those ops at exactly those shapes, so libref's answers are libavx's answers,
* and the ABI says so in as many words: "libref supplies it for the whole conventional vocabulary,
* so an op that stays inside docs/OPS.md is describable even when the kernel under test is not."
*
* Writing a second copy would be writing a second set of judgement calls about the SAME ops, and
* the two would disagree somewhere -- which is worse than having one, because a tool would then
* size a buffer from one plugin and check it against the other. The cost is stated plainly: a
* tool that has libavx and NOT libref cannot size libavx's buffers. That tool does not exist (both
* are host plugins and ship together) and if it ever does, the fix is to implement the hook, not
* to have guessed.
*
* ============================== AND NO TUNABLES ==============================
*
* ABI v8 has kernels declare tunable AXES and the core take the cross product (rad_abi.h). libavx
* declares none, and the reason is that its axes are not free: the vector width is fixed by the
* ISA level, which is fixed by the CPU, and the GEMM's blocking is chosen from the cache sizes
* CPUID reports rather than from a search. There is one thing worth tuning -- the L2 block edge --
* and it is read from the machine rather than measured per shape, because unlike a GPU tile it
* does not interact with an occupancy limit. A declared axis whose best value is computable is a
* declared axis that wastes the tuner's time.
*/
#include "avx_isa.h"
#include "avx_rows.h"
#include "rad_abi.h"
#include "rad_plugin.h"
/* ================================================================== parameter specs
* The macro names are libref's too. Two files that must agree line for line should look the same
* when they are diffed, and `diff libref/ref_registry.cpp libavx/avx_registry.cpp` over the schema
* section is a real review step. */
#define P_INT(k) { k, RAD_P_INT, RAD_REQUIRED }
#define P_INTO(k) { k, RAD_P_INT, RAD_OPTIONAL }
#define P_STR(k) { k, RAD_P_STR, RAD_REQUIRED }
#define P_STRO(k) { k, RAD_P_STR, RAD_OPTIONAL }
#define P_INTD(k) { k, RAD_P_INT, RAD_DERIVED }
#define P_CHUNK(k) { k, RAD_P_INT, RAD_DERIVED, RAD_PROLE_SEQ_CHUNK }
#define P_F64(k) { k, RAD_P_F64, RAD_REQUIRED }
#define P_F64O(k) { k, RAD_P_F64, RAD_OPTIONAL }
#define OPD(n) { n, RAD_OPD_IN, 0 }
#define OPD_O(n) { n, RAD_OPD_IN, 1 }
#define OUT(n) { n, RAD_OPD_OUT, 0 }
#define OUT_O(n) { n, RAD_OPD_OUT, 1 }
#define INOUT(n) { n, RAD_OPD_INOUT, 0 }
#define INOUT_O(n) { n, RAD_OPD_INOUT, 1 }
#define WGT(n) { n, RAD_OPD_WEIGHT, 0 }
#define WTAB(n) { n, RAD_OPD_WTAB, 0 }
#define WGT_O(n) { n, RAD_OPD_WEIGHT, 1 }
#define ARR(a) (a), (int)(sizeof(a) / sizeof((a)[0]))
/* ---- elementwise and norms ---------------------------------------------------------------- */
static const RadParamSpec pRmsnorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"),
P_F64O("wadd") };
static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT("w"), OUT("y") };
static const RadParamSpec pHcRead[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("lowrank"),
P_F64("eps"), P_STR("dtype"), P_F64O("wadd"),
P_INTO("inject"), P_INTO("group"), P_INTO("rotate"),
P_STRO("mix") };
static const RadOperandSpec oHcRead[] = { OPD("h"), WGT("w"), WGT("mix_down"), WGT("mix_up"),
WGT_O("inject_w"), OUT("x"), OUT_O("inj"), OUT_O("q"),
OUT_O("scale"), OUT_O("rq"), OUT_O("rscale") };
static const RadParamSpec pNgramIds[] = { P_INT("M"), P_INT("heads"), P_INT("ngram"),
P_INT("eos") };
static const RadOperandSpec oNgramIds[] = { OPD("tok"), INOUT("state"), OPD("cu"), WGT("mult"),
WGT("vocab_sizes"), WGT("offsets"),
OPD_O("cache_idx"), OPD_O("has_init"),
OPD_O("num_accepted"), OUT("ids"),
OUT_O("ahead_ids") };
static const RadParamSpec pPleGate[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("eps"),
P_STR("dtype"), P_F64O("wadd"), P_F64O("gate_eps") };
static const RadOperandSpec oPleGate[] = { OPD("k"), OPD("q"), OPD("v"), WGT("w_key"),
WGT("w_query"), WGT("w_conv"), OUT("gv"), OUT("gvn") };
static const RadParamSpec pPleConv[] = { P_INT("M"), P_INT("n"), P_INT("width"),
P_INT("dilation"), P_STR("dtype") };
static const RadOperandSpec oPleConv[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"),
OPD_O("resid"), OPD_O("cache_idx"), OPD_O("has_init"),
OPD_O("num_accepted"), OUT("y") };
static const RadParamSpec pHcWrite[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype") };
static const RadOperandSpec oHcEnter[] = { OPD("x"), OUT("h") };
static const RadOperandSpec oHcWrite[] = { OPD("y"), OPD("inj"), INOUT("h") };
static const RadParamSpec pMtpEnter[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("eps"),
P_STR("dtype"), P_F64O("wadd"), P_INTO("ngroup"),
P_STRO("fc") };
static const RadOperandSpec oMtpEnter[] = { OPD("h"), OPD("e"), WGT("w_h"), WGT("w_e"),
WGT("fc_h"), WGT("fc_e"), OUT("x") };
static const RadOperandSpec oRmsnormAdd[] = { OPD("x"), OPD("residual"), WGT("w"),
OUT("y"), OUT("residual_out") };
static const RadParamSpec pLayernorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"),
P_STR("dtype") };
static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT("y") };
static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype") };
static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") };
static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
static const RadOperandSpec oBinary[] = { OPD("a"), OPD("b"), OUT("y") };
static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") };
static const RadOperandSpec oUnary[] = { OPD("x"), OUT("y") };
static const RadOperandSpec oGather[] = { OPD("x"), OPD("idx"), OUT("y") };
static const RadOperandSpec oScatterRows[] = { OPD("v"), OPD("idx"), INOUT("x") };
static const RadParamSpec pCast[] = { P_INT("M"), P_INT("n"), P_STR("from"), P_STR("to") };
/* ---- quantisation and rotation ------------------------------------------------------------ */
static const RadParamSpec pQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"),
P_STR("dtype") };
static const RadOperandSpec oQuant[] = { OPD("x"), OUT("q"), OUT("scale"), OUT_O("asum") };
static const RadOperandSpec oHadQuant[] = { OPD("x"), OUT("q"), OUT("scale") };
static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") };
/* The fp8 fusions: the unfused pair's operands minus the tensor between them, and `out_bf16` to
* put even that back. */
static const RadParamSpec pRmsQuantFp8[] = { P_INT("M"), P_INT("n"), P_F64("eps"),
P_INT("group"), P_STR("dtype"), P_F64O("wadd") };
static const RadOperandSpec oRmsQuantFp8[] = { OPD("x"), INOUT_O("residual"), WGT("w"),
OUT("q"), OUT("scale"), OUT_O("out_bf16") };
static const RadParamSpec pGatedQuantFp8[] = { P_INT("M"), P_INT("n"), P_INT("group"),
P_STR("dtype"), P_STRO("act") };
static const RadOperandSpec oGatedQuantFp8[] = { OPD("gate_up"), OUT("q"), OUT("scale"),
OUT_O("out_bf16") };
static const RadParamSpec pRmsHadQuant[] = { P_INT("M"), P_INT("n"), P_F64("eps"),
P_INT("group"), P_STR("dtype"), P_F64O("wadd") };
static const RadOperandSpec oRmsHadQuant[] = { OPD("x"), INOUT_O("residual"), WGT("w"),
OUT("q"), OUT("scale"), OUT_O("out_bf16") };
static const RadParamSpec pGatedQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"),
P_STR("dtype"), P_STRO("act"), P_INTO("mode") };
static const RadOperandSpec oGatedQuant[] = { OPD("a"), OPD_O("b"), OUT("q"), OUT("scale") };
/* `a_scale` is optional: dtype "bf16" is a plain activation and carries none. */
static const RadOperandSpec oGram[] = { OPD("a"), OPD_O("a_scale"), INOUT("h") };
static const RadParamSpec pDequant[] = { P_INT("M"), P_INT("n"), P_INT("group"),
P_STR("dtype") };
static const RadOperandSpec oDequant[] = { OPD("q"), OPD("scale"), OUT("y") };
/* ---- gemm --------------------------------------------------------------------------------- */
static const RadParamSpec pGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_STR("dtype") };
static const RadOperandSpec oGemm[] = { OPD("a"), WGT("b"), OUT("y") };
static const RadParamSpec pGemmBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_STR("dtype"),
P_STRO("act") };
static const RadOperandSpec oGemmBias[] = { OPD("a"), WGT("b"), WGT("bias"), OPD_O("res"),
OUT("y") };
static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
P_STR("dtype") };
static const RadOperandSpec oGemmQ[] = { OPD("a"), OPD_O("a_scale"), WGT("b"), WGT("b_scale"),
OUT("y"), OPD_O("a_sum"), WGT_O("b_ref") };
static const RadOperandSpec oGemmQBias[] = { OPD("a"), OPD("a_scale"), WGT("b"), WGT("b_scale"),
WGT("bias"), OUT("y") };
/* `act` REQUIRED, where the quantiser has it optional; `N` is the weight's rows, twice the output's
* width. */
static const RadParamSpec pGemmQGated[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
P_STR("dtype"), P_STR("act") };
static const RadOperandSpec oGemmQGated[] = { OPD("a"), OPD("a_scale"), WGT("b"), WGT("b_scale"),
OUT("q"), OUT("scale"), OUT_O("out_bf16") };
/* ---- attention ---------------------------------------------------------------------------- */
static const RadParamSpec pAttnPaged[] = {
P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), P_INTD("block_size"), P_INT("causal"),
P_INT("window"), P_STR("q_dtype"), P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"),
P_INTO("n_head"), P_INTO("max_seqs")
};
static const RadOperandSpec oAttnPaged[] = {
OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"),
OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("cu_seqlens"), OUT("out")
};
static const RadConstraint cPagedBlock[] = { RAD_CGE("block_size", 1) };
static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
P_INT("causal"), P_STR("dtype"), P_F64O("scale"),
P_INTO("max_seqlen") };
static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
OUT("out") };
static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"),
P_INT("block_size"), P_STR("kv_dtype"),
P_F64O("k_scale"), P_F64O("v_scale") };
static const RadOperandSpec oKvStore[] = { OPD("k"), OPD("v"), OPD("slot_mapping"),
INOUT("kv_cache") };
static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"),
P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections") };
static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") };
static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("theta"),
P_F64("scale"), P_STR("dtype") };
static const RadOperandSpec oRopeTable[] = { OPD("positions"), OUT("cos_sin") };
static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("n_head_kv"), P_F64("theta"), P_F64("eps"),
P_F64O("scale"), P_STRO("mode"),
P_INTO("rotary_dim"), P_F64O("wadd") };
static const RadOperandSpec oQkNormRope[] = { INOUT("qkv"), OPD("positions"), WGT("q_w"),
WGT("k_w") };
/* ---- mixture of experts ------------------------------------------------------------------- */
static const RadParamSpec pScaleRows[] = { P_INT("M"), P_INT("n"), P_STR("act"),
P_STR("dtype") };
/* `add` is OPTIONAL and sits BEFORE `y`, which is the kind of detail a hand-kept copy gets wrong:
* operands are positional, so reading `y` at index 2 writes the output into the residual the
* caller passed. rad-avx-check compares this table against libref's on every run, which is what
* catches exactly this drift. */
static const RadOperandSpec oScaleRows[] = { OPD("x"), OPD("s"), OPD_O("add"), OUT("y") };
static const RadParamSpec pRouter[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"),
P_INT("norm"), P_STR("dtype") };
static const RadOperandSpec oRouter[] = { OPD("logits"), OUT("expert_ids"), OUT("expert_w") };
static const RadParamSpec pScatter[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"),
P_INTO("expert_base"),
P_STRO("protect") };
static const RadOperandSpec oScatter[] = { OPD("expert_ids"), OUT("sorted_tok"),
OUT("expert_offset"), OUT("expert_count") };
static const RadParamSpec pMoeGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"),
P_INT("top_k"), P_STR("a_order"), P_STR("dtype") };
static const RadOperandSpec oMoeGemm[] = { OPD("a"), WTAB("w"), OPD("sorted_tok"),
OPD("expert_offset"), OUT("y") };
/* The experts are two tables by parity -- `w` the even ones at [N, K], `w_odd` the odd ones at
* [N_odd, K_odd] -- with `parts` stacked parts along the rows and the output; libr4d's schema
* says why. */
static const RadParamSpec pMoeGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"),
P_INT("top_k"), P_INT("group"), P_STR("a_order"),
P_STR("dtype"), P_INTO("N_odd"), P_INTO("K_odd"),
P_INTO("parts") };
static const RadOperandSpec oMoeGemmQ[] = { OPD("a"), OPD_O("a_scale"), WTAB("w"), WTAB("w_scale"),
OPD("sorted_tok"), OPD("expert_offset"),
WTAB("w_odd"), WTAB("w_odd_scale"), OUT("y") };
/* `shared` + `shared_gate` present = the shared arm folded in: y = narrow(shared *
* act(gate)) + narrow(gathered), the unfused pair's two narrows carried in the stores. `act` is
* scale_rows' spelling, sigmoid or none, and applies to the SCALAR. Mirrors libref's schema
* exactly -- the loader refuses the whole plugin on any disagreement. */
static const RadParamSpec pMoeGather[] = { P_INT("M"), P_INT("n"), P_INT("top_k"),
P_STR("dtype"), P_STRO("act") };
static const RadOperandSpec oMoeGather[] = { OPD("y_expert"), OPD("expert_w"), OPD("sorted_tok"),
OPD_O("shared"), OPD_O("shared_gate"), OUT("y") };
static const RadParamSpec pRowTopk[] = { P_INT("M"), P_INT("N"), P_INT("R"), P_INTO("vocab_off"),
P_STR("dtype") };
static const RadOperandSpec oRowTopk[] = { OPD("x"), OUT("idx"), OUT("val"), OUT_O("pairs") };
static const RadParamSpec pRowTopkMerge[] = { P_INT("M"), P_INT("R"), P_INT("world_size"),
P_STR("dtype") };
static const RadOperandSpec oRowTopkMerge[] = { OPD("gathered"), OUT("idx"), OUT("val") };
/* Mirrors libref's row exactly: R candidates rescored against the full-precision head, ties to the
* lower id, pads sort last. libref's shape hook declines to describe this op, so the checker skips
* its geometries -- but the row must exist or the whole-plugin coverage gate fails. */
static const RadParamSpec pLogitRerank[] = { P_INT("M"), P_INT("R"), P_INT("n_vocab"),
P_INT("n_embd"), P_INTO("vocab_off"),
P_STR("dtype") };
static const RadOperandSpec oLogitRerank[] = { OPD("x"), WGT("head"), OPD("idx_in"),
OUT("idx"), OUT("val"), OUT_O("pairs") };
/* ---- gated delta net ---------------------------------------------------------------------- */
static const RadParamSpec pConvPrep[] = { P_INT("M"), P_INT("head_k"), P_INT("head_v"),
P_CHUNK("chunk"), P_INT("conv_width"),
P_F64O("l2_eps"), P_F64O("softplus_thr") };
static const RadOperandSpec oConvPrep[] = {
OPD("x"), WGT("w"), WGT_O("b"), WGT("A_log"), WGT("dt_bias"), INOUT("conv_state"), OPD("cu"),
OPD_O("a"), OPD_O("b_gate"), OPD_O("cache_idx"), OPD_O("has_init"),
OUT("q"), OUT("k"), OUT("v"), OUT("g"), OUT("beta")
};
static const RadParamSpec pConvUpdate[] = { P_INT("q_len"), P_INT("head_k"), P_INT("head_v"),
P_INT("conv_width"), P_INTO("max_query_len") };
static const RadOperandSpec oConvUpdate[] = {
OPD("x"), WGT("w"), WGT_O("b"), INOUT("conv_state"), OPD("state_idx"), OPD("num_accepted"),
OPD("cu"), OUT("q"), OUT("k"), OUT("v")
};
static const RadParamSpec pKkt[] = { P_INT("M"), P_INT("head_k"), P_CHUNK("chunk") };
static const RadOperandSpec oKkt[] = { OPD("k"), OPD("beta"), OPD("g"), OPD("cu"), OUT("A") };
static const RadParamSpec pChunkScan[] = { P_INT("M"), P_INT("head_k"), P_INT("head_v"),
P_CHUNK("chunk"), P_F64O("scale"),
P_INTO("state_fp16") };
static const RadOperandSpec oChunkScan[] = { OPD("q"), OPD("k"), OPD("v"), OPD("A"), OPD("g"),
OPD("beta"), OPD_O("h0"), OPD("cu"),
OUT("o"), OUT_O("ht"), OPD_O("state_idx") };
static const RadParamSpec pRecurrent[] = { P_INT("q_len"), P_INT("head_k"), P_INT("head_v"),
P_INTO("n_head_v"), P_F64O("scale"), P_F64O("eps"),
P_F64O("l2_eps"), P_F64O("softplus_thr"),
P_STRO("act"), P_INTO("state_fp16"),
P_STRO("state_form") };
static const RadOperandSpec oRecurrent[] = {
OPD("q"), OPD("k"), OPD("v"), OPD("a"), OPD("b"), WGT("A_log"), WGT("dt_bias"),
INOUT("state"), OPD("state_idx"), OPD("num_accepted"), OPD("cu"), OPD_O("z"),
WGT_O("norm_w"), OUT("o"), OUT_O("o_q"), OUT_O("o_scale")
};
/* gdn_conv_update folded into gdn_recurrent_update: the convolution's operands, then the
* recurrence's minus q, k and v; the parameters are the union of the two ops' under their own
* names. */
static const RadParamSpec pConvRecurrent[] = { P_INT("q_len"), P_INT("head_k"), P_INT("head_v"),
P_INT("conv_width"), P_INTO("n_head_v"),
P_F64O("scale"), P_F64O("eps"), P_F64O("l2_eps"),
P_F64O("softplus_thr"), P_STRO("act"),
P_INTO("state_fp16"), P_STRO("state_form") };
static const RadOperandSpec oConvRecurrent[] = {
OPD("x"), WGT("conv_w"), WGT_O("conv_b"), INOUT("conv_state"), OPD("conv_idx"), OPD("a"),
OPD("b"), WGT("A_log"), WGT("dt_bias"), INOUT("state"), OPD("state_idx"),
OPD("num_accepted"), OPD("cu"), OPD("z"), WGT("norm_w"), OUT("o"), OUT_O("o_q"),
OUT_O("o_scale")
};
static const RadParamSpec pGatedNorm[] = { P_INT("M"), P_INT("channels"), P_F64("eps"),
P_STR("act") };
static const RadOperandSpec oGatedNorm[] = { OPD("x"), OPD("z"), WGT("w"), OUT("o") };
/* ---- collectives -------------------------------------------------------------------------- */
static const RadParamSpec pAllReduce[] = { P_INT("world_size"), P_INT("numel"), P_STR("dtype"),
P_INT("exact"), P_INTO("min_bytes"), P_INTO("hops") };
static const RadOperandSpec oAllReduce[] = { INOUT("x"), OUT_O("y") };
static const RadParamSpec pAllGather[] = { P_INT("world_size"), P_INT("numel"), P_STR("dtype"),
P_INTO("row") };
static const RadOperandSpec oAllGather[] = { OPD("x"), OUT("y") };
/* ---- vocabulary edges --------------------------------------------------------------------- */
static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"),
P_STR("dtype"), P_INTO("vocab_offset"),
P_F64O("wscale") };
static const RadOperandSpec oEmbed[] = { OPD("tokens"), WGT("wte"), OUT("x") };
static const RadOperandSpec oEmbedQ[] = { OPD("tokens"), WGT("wte"), WGT_O("scale"), OUT("x"),
OPD_O("ahead") };
static const RadParamSpec pLogits[] = { P_INT("M"), P_INT("n_vocab"), P_INT("n_embd"),
P_STR("dtype") };
static const RadOperandSpec oLogits[] = { OPD("x"), WGT("lm_head"), OUT("logits") };
/* ---- sampling ----------------------------------------------------------------------------- */
static const RadParamSpec pMVocab[] = { P_INT("M"), P_INT("n_vocab") };
static const RadParamSpec pMCand[] = { P_INT("M"), P_INT("n_cand") };
/* libref's schema: the history stages take the rank's first vocabulary row, and DRY an optional
* plane of breaker marks beside the history. */
static const RadParamSpec pPenal[] = { P_INT("M"), P_INT("n_vocab"), P_INTO("vocab_off") };
static const RadOperandSpec oPenalties[] = { INOUT("logits"), OPD("params"), OPD("history") };
static const RadOperandSpec oDry[] = { INOUT("logits"), OPD("params"), OPD("history"),
OPD_O("breakers") };
static const RadOperandSpec oTemp[] = { INOUT("logits"), OPD("params") };
static const RadOperandSpec oMask[] = { INOUT("logits"), OPD("params"), OPD("bitmask") };
static const RadParamSpec pTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INTO("vocab_off") };
static const RadOperandSpec oTopk[] = { OPD("logits"), OPD("params"),
OUT("cand_idx"), OUT("cand_val"), OUT_O("pairs") };
static const RadOperandSpec oArgmax[] = { OPD("logits"), OPD("params"), OUT("token") };
static const RadOperandSpec oNarrow[] = { INOUT("cand_idx"), INOUT("cand_val"), OPD("params") };
static const RadOperandSpec oPick[] = { OPD("cand_idx"), OPD("cand_val"), OPD("params"),
OUT("token") };
static const RadOperandSpec oMerge[] = { OPD("gathered"), OPD("params"),
OUT("cand_idx"), OUT("cand_val") };
/* The drafter's token walk over a candidate lattice. */
static const RadParamSpec pDflashSelect[] = { P_INT("M"), P_INT("steps"), P_INT("top_k"),
P_INT("rank"), P_INT("n_vocab"),
P_INTO("anchor_stride"), P_STR("dtype") };
static const RadOperandSpec oDflashSelect[] = { OPD("cand"), OPD("unary"), OPD_O("hp"),
OPD("anchor"), WGT("pred"), WGT("succ"),
OUT("tokens") };
/* ================================================================== the schema table
* The doc strings are libavx's own and say what this plugin does with the op -- which of the two
* plugins' strings a reader sees depends on which one fixed the schema first, and schema_same does
* not compare them. Where the op is subtle the string points at libref's, which is the definition.
*/
static const RadOpSchema kSchemas[] = {
{ "rmsnorm", ARR(pRmsnorm), ARR(oRmsnorm),
"y = x * rsqrt(mean(x^2) + eps) * (w + wadd). The sum of squares is a four-accumulator vector "
"reduction, so it does not sum in libref's order and does not claim to." },
{ "rmsnorm_add", ARR(pRmsnorm), ARR(oRmsnormAdd),
"residual_out = x + residual, then y = rmsnorm(residual_out) * w. The variance is taken from the "
"unrounded f32 sum and the multiply reads residual_out back AFTER narrowing -- both are libref's "
"rule and both are observable, so both are reproduced exactly." },
{ "hc_enter", ARR(pHcWrite), ARR(oHcEnter),
"h[s] = x for each of the hc streams -- the wide residual stream's first value." },
{ "hc_read", ARR(pHcRead), ARR(oHcRead),
"The read half of a gated residual: grouped norm, low-rank gate, stream mix, and optionally the "
"block-scaled fp8 form of x and its Hadamard-rotated twin. See docs/OPS.md for the three facts "
"a second implementation has to match (the mix is a MEAN, there is a separate / hc inside each "
"gate argument, and hc_write adds into the UNNORMED h). `mix` names the matrices' stored "
"format; a host kernel reads them as the dense tensors it is handed." },
{ "hc_write", ARR(pHcWrite), ARR(oHcWrite), "h[s] += inj[s] * y, into the unnormed stream." },
{ "mtp_enter", ARR(pMtpEnter), ARR(oMtpEnter),
"MTP head entry: two norms, a per-sub-stream fc and a broadcast fc. `fc` names the two "
"matrices' stored format; a host kernel reads them as the dense tensors it is handed." },
{ "layernorm", ARR(pLayernorm), ARR(oLayernorm), "layer norm with gain and optional bias." },
{ "grid_embed", ARR(pGridEmbed), ARR(oGridEmbed),
"x += a side x side position table resampled bilinearly to the row's grid." },
{ "add", ARR(pMnD), ARR(oBinary), "elementwise sum." },
{ "mul", ARR(pMnD), ARR(oBinary),
"elementwise product; `b` may have extent 1 on any axis `a` does not and is broadcast along it." },
{ "silu_mul", ARR(pMnD), ARR(oGateUp),
"silu-gated product over a fused [M, 2n] gate_up: y = silu(gate) * up." },
{ "gelu", ARR(pMnD), ARR(oUnary), "exact erf gelu." },
{ "silu", ARR(pMnD), ARR(oUnary), "silu." },
{ "sigmoid", ARR(pMnD), ARR(oUnary), "logistic sigmoid." },
{ "ple_gate", ARR(pPleGate), ARR(oPleGate),
"PLE gate: three grouped norms, a dot, a signed sqrt." },
{ "ple_conv", ARR(pPleConv), ARR(oPleConv),
"PLE's dilated depthwise conv, silu and residual add." },
{ "ngram_ids", ARR(pNgramIds), ARR(oNgramIds), "hashed n-gram row ids for PLE." },
{ "gather_rows", ARR(pMnD), ARR(oGather), "y[i,:] = x[idx[i],:]." },
{ "scatter_rows", ARR(pMnD), ARR(oScatterRows),
"x[idx[i],:] = v[i,:], the mirror of gather_rows: `x` is INOUT and the write is partial, a "
"negative index writes nothing, and indices are distinct." },
{ "cast", ARR(pCast), ARR(oUnary),
"dtype conversion. The narrowing direction is the ABI's RTNE, bit for bit -- a vectorised cast "
"that rounded differently could not be checked against anything." },
{ "softmax", ARR(pMnD), ARR(oUnary), "row-wise softmax, max-subtracted." },
{ "quant_act_i8", ARR(pQuant), ARR(oQuant),
"symmetric int8 activation quantiser, one f32 scale per `group` contiguous elements. `asum` is "
"not produced -- libavx has no asymmetric grid to feed, exactly as libref has none." },
{ "quant_act_fp8", ARR(pQuant), ARR(oQuantFp8), "symmetric block-scaled E4M3 quantiser." },
{ "had_quant_act_fp8", ARR(pQuant), ARR(oQuantFp8),
"width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser. No normalisation: "
"the 1/group is folded into the stored weight scale at convert (docs/OPS.md)." },
{ "gram_accum", ARR(pQuant), ARR(oGram),
"h += x^T x over a dequantised E4M3 activation. `h` is [n, n] and INOUT." },
{ "had_quant_act_i8", ARR(pQuant), ARR(oHadQuant),
"Walsh-Hadamard rotation at width `group`, then symmetric int8 with ONE scale per row carrying "
"the 1/sqrt(group)." },
{ "rmsnorm_had_quant_i8", ARR(pRmsHadQuant), ARR(oRmsHadQuant),
"RMS norm, optional residual add, rotation and int8 in one pass." },
{ "gated_had_quant_i8", ARR(pGatedQuant), ARR(oGatedQuant),
"gated product, rotation and int8 in one pass." },
{ "dequant", ARR(pDequant), ARR(oDequant), "group-scaled dequantisation." },
{ "rmsnorm_quant_fp8", ARR(pRmsQuantFp8), ARR(oRmsQuantFp8),
"RMS norm with an optional residual add, then the E4M3 quantiser, in one pass. The add is "
"stored before the variance reads it, and the codes are taken over the bf16-narrowed row that "
"`out_bf16` holds." },
{ "gated_quant_fp8", ARR(pGatedQuantFp8), ARR(oGatedQuantFp8),
"act(gate) * up over a packed [M, 2n] plane, gate half first, then the E4M3 quantiser over the "
"bf16-narrowed product. `act` is silu or sigmoid, silu by default." },
{ "gemm_nt", ARR(pGemm), ARR(oGemm),
"C = A B^T, f32 accumulate, cache-blocked with a register-blocked microkernel. Sums in a "
"different order from libref's straight loop by construction; the kbench tolerance for a bf16 "
"gemm_nt (8e-3) is what that costs." },
{ "gemm_nt_bias", ARR(pGemmBias), ARR(oGemmBias),
"C = act(A B^T + bias) + res, each step rounded to C's dtype." },
{ "gemm_nt_q", ARR(pGemmQ), ARR(oGemmQ),
"C = A B^T with group-scaled quantised operands. `a_sum` and `b_ref` are libr4d's asymmetric and "
"mxfp4 forms and are ignored here, as they are in libref." },
{ "gemm_nt_q_bias", ARR(pGemmQ), ARR(oGemmQBias), "quantised C = A B^T + bias." },
{ "gemm_nt_q_gated", ARR(pGemmQGated), ARR(oGemmQGated),
"gemm_nt_q over a [N, K] gate_up plane with gated_quant_fp8's pass in the epilogue, byte for "
"byte the pair. `N` is the weight's rows, twice the fused width; the output is [M, N/2]." },
{ "attn_paged", ARR(pAttnPaged), ARR(oAttnPaged),
"paged causal / sliding-window attention, any query length, online-softmax so one pass over the "
"cache suffices." },
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense), "dense varlen attention over cu_seqlens." },
{ "kv_store", ARR(pKvStore), ARR(oKvStore), "scatter k and v into the paged cache." },
{ "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin at each position's own row." },
{ "rope", ARR(pRope), ARR(oRope), "rotary embedding in place." },
{ "qk_norm_rope", ARR(pQkNormRope), ARR(oQkNormRope), "per-head QK norm then rotary embedding." },
{ "scale_rows", ARR(pScaleRows), ARR(oScaleRows),
"one scalar per row, optionally through an activation, broadcast across the row." },
{ "router_topk", ARR(pRouter), ARR(oRouter), "softmax then exact top-k routing." },
{ "moe_scatter", ARR(pScatter), ARR(oScatter),
"stable counting sort of routing slots by expert." },
{ "moe_gemm", ARR(pMoeGemm), ARR(oMoeGemm), "grouped GEMM over the expert-sorted rows." },
{ "moe_gemm_q", ARR(pMoeGemmQ), ARR(oMoeGemmQ),
"grouped GEMM over the expert-sorted rows, quantised operands." },
{ "moe_gather", ARR(pMoeGather), ARR(oMoeGather), "weighted scatter back to token order." },
{ "row_topk", ARR(pRowTopk), ARR(oRowTopk), "exact per-row top-R." },
{ "row_topk_merge", ARR(pRowTopkMerge), ARR(oRowTopkMerge),
"the global top-R of the gathered per-rank candidate sets." },
{ "logit_rerank", ARR(pLogitRerank), ARR(oLogitRerank),
"R candidates a row rescored exactly against the full-precision head." },
{ "gdn_conv_prep", ARR(pConvPrep), ARR(oConvPrep),
"gdn prefill preamble: conv, split, l2 norm, gate cumsum, beta." },
{ "gdn_conv_update", ARR(pConvUpdate), ARR(oConvUpdate),
"gdn decode conv over the rolling speculative window." },
{ "gdn_kkt_solve", ARR(pKkt), ARR(oKkt), "gdn chunk preamble: the triangular inverse." },
{ "gdn_chunk_scan", ARR(pChunkScan), ARR(oChunkScan), "gdn chunked scan." },
{ "gdn_recurrent_update", ARR(pRecurrent), ARR(oRecurrent),
"gdn decode recurrence against the paged state cache, in the PER-CANDIDATE reading libref "
"implements. `state_form` names the reading; any other form, libr4d's two-slot \"anchor\" "
"among them, is declined by name as libref declines it." },
{ "gdn_conv_recurrent_update", ARR(pConvRecurrent), ARR(oConvRecurrent),
"gdn_conv_update followed by gdn_recurrent_update, with q, k and v never written: the operands "
"are the convolution's (`conv_idx` is its state_idx) and then the recurrence's without those "
"three." },
{ "gdn_gated_rmsnorm", ARR(pGatedNorm), ARR(oGatedNorm), "gated RMS norm over a head." },
{ "all_reduce", ARR(pAllReduce), ARR(oAllReduce),
"sum across ranks, f32, ascending rank order." },
{ "all_gather", ARR(pAllGather), ARR(oAllGather), "gather every rank's shard." },
{ "embed_lookup", ARR(pEmbed), ARR(oEmbed), "embedding gather, vocab-parallel with an offset." },
{ "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ),
"embedding gather, one scale for the table; without a scale the table is read as it is." },
{ "logits_gemm", ARR(pLogits), ARR(oLogits), "the lm_head projection." },
{ "sample_penalties", ARR(pPenal), ARR(oPenalties),
"repetition, frequency and presence penalties." },
{ "sample_dry", ARR(pPenal), ARR(oDry), "DRY repetition-suffix penalty, once per token." },
{ "sample_temp", ARR(pMVocab), ARR(oTemp), "per-request temperature." },
{ "sample_topk", ARR(pTopk), ARR(oTopk), "exact top-k candidate set, descending, ties to the "
"lower id." },
{ "sample_topp", ARR(pMCand), ARR(oNarrow), "nucleus narrowing in place." },
{ "sample_minp", ARR(pMCand), ARR(oNarrow), "min-p narrowing in place." },
{ "sample_typical", ARR(pMCand), ARR(oNarrow), "locally typical narrowing in place." },
{ "sample_xtc", ARR(pMCand), ARR(oNarrow), "exclude-top-choices narrowing in place." },
{ "sample_mask", ARR(pMVocab), ARR(oMask), "grammar bitmask application." },
{ "sample_pick", ARR(pMCand), ARR(oPick),
"seeded inverse-CDF draw. The uniform is splitmix64 over (seed * 0x9E3779B97F4A7C15 + pos), "
"top 24 bits as a float in [0,1) -- specified rather than left to a library, because the same "
"stream has to come out of a host reference, a device kernel and a rerun." },
{ "sample_merge_topk", ARR(pMCand), ARR(oMerge), "the vocab-parallel candidate merge." },
{ "sample_argmax", ARR(pMVocab), ARR(oArgmax), "greedy, ties to the lower token id." },
{ "dflash_select", ARR(pDflashSelect), ARR(oDflashSelect),
"a greedy walk over a candidate lattice: score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * "
"hp[l][r] * succ[cand[l, c]][r], pid(0) the anchor and pid(l) the walk's own previous pick. "
"`hp` absent is a plane of ones." },
};
/* ================================================================== the kernel table
*
* Every row is domain HOST at priority 0, unconstrained except where the op's own structure needs
* a value the operands do not carry. That last clause is kv_store's `block_size`, and it is
* libref's rule for the same reason: the constraint admits every value and refuses only a query
* that does not NAME one, because an absent key fails a constraint and a cache cannot be walked
* without knowing its block edge.
*
* SHAPE SAYS "any" ON EVERY ROW, and that is a claim about this plugin rather than a copied
* phrase: every extent is read off the operands (avx_common.h), so there is no geometry these
* refuse. Which ISA level runs is NOT part of the shape and deliberately does not appear in a
* constraint -- a row that said `avx512` would be a row that vanishes from the hierarchy on a
* machine without it, and the whole point of the dispatch is that the ROW is the same everywhere
* and only the instruction stream underneath it changes. */
#define SHAPE_ANY "any: every extent is read off the operands, strides included"
#define ROW(nm, opname, fam, what, dts, cons, ncons, fn) \
{ nm, opname, fam, what, SHAPE_ANY, dts, RAD_DOMAIN_HOST, 0, \
cons, ncons, nullptr, 0, nullptr, nullptr, nullptr, fn, nullptr, nullptr, nullptr, \
nullptr, nullptr, nullptr }
#define SIMPLE(nm, opname, fam, what, dts, fn) ROW(nm, opname, fam, what, dts, nullptr, 0, fn)
#define DT_FLOAT "bf16 f16 f32 fp8_e4m3 fp8_e5m2 i8 i32, chosen per operand from its own dtype"
#define DT_ANY "any dtype rad_types.h names, per operand"
/* The launch is the baseline-compiled thunk, never the level's own symbol -- see avx_dispatch.cpp
* on why the row must be correct before rad_plugin_open has run. */
#define L(nm) avx_thunk_##nm
#define AVX_THUNK_DECL(nm) extern "C" int avx_thunk_##nm(const RadArgs*, RadStream);
AVX_OP_LIST(AVX_THUNK_DECL)
#undef AVX_THUNK_DECL
static const RadKernelInfo kKernels[] = {
SIMPLE("avx_rmsnorm", "rmsnorm", "norm", "root-mean-square norm with a gain", DT_FLOAT, L(rmsnorm)),
SIMPLE("avx_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", DT_FLOAT,
L(rmsnorm_add)),
SIMPLE("avx_hc_enter", "hc_enter", "norm", "gated residual entry: hc copies of x", DT_FLOAT,
L(hc_enter)),
SIMPLE("avx_hc_read", "hc_read", "norm",
"gated residual read: grouped norm, low-rank gate, stream mix", DT_FLOAT, L(hc_read)),
SIMPLE("avx_hc_write", "hc_write", "norm", "gated residual write: h[s] += inj[s] * y", DT_FLOAT,
L(hc_write)),
SIMPLE("avx_mtp_enter", "mtp_enter", "norm",
"MTP head entry: two norms, a per-sub-stream fc and a broadcast fc", DT_FLOAT, L(mtp_enter)),
SIMPLE("avx_layernorm", "layernorm", "norm", "layer norm with gain and bias", DT_FLOAT,
L(layernorm)),
SIMPLE("avx_grid_embed", "grid_embed", "elem",
"bilinear resample of a learned position grid, added in", DT_FLOAT, L(grid_embed)),
SIMPLE("avx_add", "add", "elem", "elementwise sum", DT_FLOAT, L(add)),
SIMPLE("avx_mul", "mul", "elem", "elementwise product, broadcasting b", DT_FLOAT, L(mul)),
SIMPLE("avx_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT,
L(silu_mul)),
SIMPLE("avx_gelu", "gelu", "elem", "exact erf gelu", DT_FLOAT, L(gelu)),
SIMPLE("avx_silu", "silu", "elem", "silu", DT_FLOAT, L(silu)),
SIMPLE("avx_sigmoid", "sigmoid", "elem", "logistic sigmoid", DT_FLOAT, L(sigmoid)),
SIMPLE("avx_gather_rows", "gather_rows", "elem", "y[i,:] = x[idx[i],:]", DT_ANY, L(gather_rows)),
SIMPLE("avx_scatter_rows", "scatter_rows", "elem", "x[idx[i],:] = v[i,:]", DT_ANY,
L(scatter_rows)),
SIMPLE("avx_ngram_ids", "ngram_ids", "vocab", "hashed n-gram row ids for PLE", DT_ANY,
L(ngram_ids)),
SIMPLE("avx_ple_gate", "ple_gate", "norm", "PLE gate: three grouped norms, a dot, a signed sqrt",
DT_FLOAT, L(ple_gate)),
SIMPLE("avx_ple_conv", "ple_conv", "norm", "PLE's dilated depthwise conv, silu and residual add",
DT_FLOAT, L(ple_conv)),
SIMPLE("avx_cast", "cast", "elem", "dtype conversion", DT_ANY, L(cast)),
SIMPLE("avx_softmax", "softmax", "elem", "row-wise softmax", DT_FLOAT, L(softmax)),
SIMPLE("avx_scale_rows", "scale_rows", "elem", "one scalar per row, broadcast across the row",
DT_FLOAT, L(scale_rows)),
SIMPLE("avx_quant_act_i8", "quant_act_i8", "quant", "symmetric int8 activation quantiser",
"float in, i8 out, f32 scale", L(quant_act_i8)),
SIMPLE("avx_had_quant_act_i8", "had_quant_act_i8", "quant",
"Walsh-Hadamard rotation then symmetric int8", "float in, i8 out, f32 scale",
L(had_quant_act_i8)),
SIMPLE("avx_quant_act_fp8", "quant_act_fp8", "quant", "symmetric block-scaled E4M3 quantiser",
"float in, fp8_e4m3 out, f32 scale", L(quant_act_fp8)),
SIMPLE("avx_had_quant_act_fp8", "had_quant_act_fp8", "quant",
"width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser",
"float in, fp8_e4m3 out, f32 scale per group; n a multiple of group",
L(had_quant_act_fp8)),
SIMPLE("avx_gram_accum", "gram_accum", "quant",
"h += x^T x over a dequantised E4M3 activation, or a plain bf16 one",
"fp8_e4m3 plus an f32 scale per group, or bf16 with no scale, in; an f32 [n][n] "
"accumulator READ and added to",
L(gram_accum)),
SIMPLE("avx_rmsnorm_had_quant_i8", "rmsnorm_had_quant_i8", "quant",
"RMS norm, rotation and int8 in one pass", "float in, i8 out, f32 scale",
L(rmsnorm_had_quant_i8)),
SIMPLE("avx_gated_had_quant_i8", "gated_had_quant_i8", "quant",
"gated product, rotation and int8 in one pass", "float in, i8 out, f32 scale",
L(gated_had_quant_i8)),
SIMPLE("avx_dequant", "dequant", "quant", "group-scaled dequantisation", DT_ANY, L(dequant)),
SIMPLE("avx_rmsnorm_quant_fp8", "rmsnorm_quant_fp8", "quant",
"RMS norm, optional residual add, and the E4M3 quantiser in one pass",
"float in, fp8_e4m3 out, f32 scale, bf16 out_bf16", L(rmsnorm_quant_fp8)),
SIMPLE("avx_gated_quant_fp8", "gated_quant_fp8", "quant",
"act(gate) * up over a packed [M, 2n] plane, then the E4M3 quantiser",
"float in, fp8_e4m3 out, f32 scale, bf16 out_bf16", L(gated_quant_fp8)),
SIMPLE("avx_gemm_nt", "gemm_nt", "gemm", "C = A B^T, f32 accumulate, cache-blocked", DT_FLOAT,
L(gemm_nt)),
SIMPLE("avx_gemm_nt_bias", "gemm_nt_bias", "gemm", "C = A B^T + bias", DT_FLOAT, L(gemm_nt_bias)),
SIMPLE("avx_gemm_nt_q", "gemm_nt_q", "gemm", "C = A B^T with group-scaled quantised operands",
"i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; f32 accumulate", L(gemm_nt_q)),
SIMPLE("avx_gemm_nt_q_bias", "gemm_nt_q_bias", "gemm", "quantised C = A B^T + bias",
"i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; f32 accumulate", L(gemm_nt_q_bias)),
SIMPLE("avx_gemm_nt_q_gated", "gemm_nt_q_gated", "gemm",
"gemm_nt_q over a gate_up plane with the gated E4M3 quantiser in the epilogue",
"i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; fp8_e4m3 out, f32 scale",
L(gemm_nt_q_gated)),
ROW("avx_attn_paged", "attn_paged", "attn",
"paged causal / sliding-window attention, any query length",
"any q and out dtype; bf16 or fp8 kv cache with optional per-(seq,head) descales",
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(attn_paged)),
SIMPLE("avx_attn_dense", "attn_dense", "attn", "dense varlen attention over cu_seqlens", DT_FLOAT,
L(attn_dense)),
ROW("avx_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY,
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(kv_store)),
SIMPLE("avx_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, L(rope)),
SIMPLE("avx_rope_table", "rope_table", "attn", "cos/sin at each position's own row", DT_FLOAT,
L(rope_table)),
SIMPLE("avx_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary embedding",
DT_FLOAT, L(qk_norm_rope)),
SIMPLE("avx_router_topk", "router_topk", "moe", "softmax then exact top-k routing", DT_FLOAT,
L(router_topk)),
SIMPLE("avx_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing slots by expert",
"i32 indices", L(moe_scatter)),
SIMPLE("avx_moe_gemm", "moe_gemm", "moe", "grouped GEMM over the expert-sorted rows", DT_FLOAT,
L(moe_gemm)),
SIMPLE("avx_moe_gemm_q", "moe_gemm_q", "moe",
"grouped GEMM over the expert-sorted rows, quantised operands", DT_FLOAT, L(moe_gemm_q)),
SIMPLE("avx_moe_gather", "moe_gather", "moe", "weighted scatter back to token order", DT_FLOAT,
L(moe_gather)),
SIMPLE("avx_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, L(row_topk)),
SIMPLE("avx_row_topk_merge", "row_topk_merge", "moe",
"the global top-R of the gathered per-rank candidate sets", DT_FLOAT, L(row_topk_merge)),
SIMPLE("avx_logit_rerank", "logit_rerank", "moe",
"R candidates a row rescored exactly against the full-precision head", DT_FLOAT,
L(logit_rerank)),
SIMPLE("avx_gdn_conv_prep", "gdn_conv_prep", "gdn",
"gdn prefill preamble: conv, split, l2 norm, gate cumsum, beta", DT_FLOAT,
L(gdn_conv_prep)),
SIMPLE("avx_gdn_conv_update", "gdn_conv_update", "gdn",
"gdn decode conv over the rolling speculative window", DT_FLOAT, L(gdn_conv_update)),
SIMPLE("avx_gdn_kkt_solve", "gdn_kkt_solve", "gdn", "gdn chunk preamble: the triangular inverse",
DT_FLOAT, L(gdn_kkt_solve)),
SIMPLE("avx_gdn_chunk_scan", "gdn_chunk_scan", "gdn", "gdn chunked scan", DT_FLOAT,
L(gdn_chunk_scan)),
SIMPLE("avx_gdn_recurrent_update", "gdn_recurrent_update", "gdn",
"gdn decode recurrence against the paged state cache", DT_FLOAT, L(gdn_recurrent_update)),
SIMPLE("avx_gdn_conv_recurrent_update", "gdn_conv_recurrent_update", "gdn",
"gdn_conv_update then gdn_recurrent_update, this plugin's own two kernels in turn", DT_FLOAT,
L(gdn_conv_recurrent_update)),
SIMPLE("avx_gdn_gated_rmsnorm", "gdn_gated_rmsnorm", "gdn", "gated RMS norm over a head", DT_FLOAT,
L(gdn_gated_rmsnorm)),
/* THE COLLECTIVES HAVE NO init/fini AND THAT IS NOT AN OVERSIGHT. libref's rows carry
* ref_collective_init because its all-reduce establishes a shared rendezvous across ranks in one
* process. libavx serves the ONE-RANK case only -- world_size 1, where an all-reduce is a copy and
* an all-gather is a copy -- and refuses anything wider by name rather than pretending. A
* multi-rank host collective is a real piece of work (shared memory, a barrier, an ordering rule)
* and it is not this plugin's: a CPU kernel library has no business owning the wire. */
SIMPLE("avx_all_reduce", "all_reduce", "ar", "sum across ranks; world_size 1 only", DT_FLOAT,
L(all_reduce)),
SIMPLE("avx_all_gather", "all_gather", "ar", "gather every rank's shard; world_size 1 only",
DT_FLOAT, L(all_gather)),
SIMPLE("avx_embed_lookup", "embed_lookup", "vocab", "embedding gather", DT_FLOAT, L(embed_lookup)),
/* THE ONE ROW WITH A LAYOUT HOOK, and it only checks: the table is read as it is stored, and the
* hook refuses a table encoded any other way (avx_ngram.cpp). An E4M3 table into bf16 goes through
* the row cache; every other dtype pair takes the general gather. */
{ "avx_embed_lookup_q", "embed_lookup_q", "vocab",
"embedding gather, one scale for the table: an E4M3 table into bf16 through a shared row cache "
"and direct reads of the container, a later call's rows read ahead",
SHAPE_ANY, DT_ANY, RAD_DOMAIN_HOST, 0,
nullptr, 0, nullptr, 0, nullptr,
/* init, fini, LAUNCH, scratch, layout, relayout, opd_shape, unrelayout */
nullptr, nullptr, L(embed_lookup_q), nullptr, avx_layout_ngram, nullptr, nullptr, nullptr,
nullptr, nullptr },
SIMPLE("avx_logits_gemm", "logits_gemm", "vocab", "the lm_head projection", DT_FLOAT,
L(logits_gemm)),
SIMPLE("avx_sample_penalties", "sample_penalties", "sample",
"repetition, frequency and presence penalties", DT_FLOAT, L(sample_penalties)),
SIMPLE("avx_sample_dry", "sample_dry", "sample", "DRY repetition-suffix penalty", DT_FLOAT,
L(sample_dry)),
SIMPLE("avx_sample_temp", "sample_temp", "sample", "per-request temperature", DT_FLOAT,
L(sample_temp)),
SIMPLE("avx_sample_topk", "sample_topk", "sample", "exact top-k candidate set", DT_FLOAT,
L(sample_topk)),
SIMPLE("avx_sample_topp", "sample_topp", "sample", "nucleus narrowing in place", DT_FLOAT,
L(sample_topp)),
SIMPLE("avx_sample_minp", "sample_minp", "sample", "min-p narrowing in place", DT_FLOAT,
L(sample_minp)),
SIMPLE("avx_sample_typical", "sample_typical", "sample", "locally typical narrowing in place",
DT_FLOAT, L(sample_typical)),
SIMPLE("avx_sample_xtc", "sample_xtc", "sample", "exclude-top-choices narrowing in place",
DT_FLOAT, L(sample_xtc)),
SIMPLE("avx_sample_merge_topk", "sample_merge_topk", "sample", "vocab-parallel candidate merge",
DT_FLOAT, L(sample_merge_topk)),
SIMPLE("avx_sample_mask", "sample_mask", "sample", "grammar bitmask application", DT_FLOAT,
L(sample_mask)),
SIMPLE("avx_sample_pick", "sample_pick", "sample", "seeded inverse-CDF draw", DT_FLOAT,
L(sample_pick)),
SIMPLE("avx_sample_argmax", "sample_argmax", "sample", "greedy pick", DT_FLOAT, L(sample_argmax)),
SIMPLE("avx_dflash_select", "dflash_select", "draft",
"DFlash2's greedy walk over the candidate lattice",
"i32 candidates and tokens, float unary and codebooks", L(dflash_select)),
};
/* ================================================================== plugin exports */
static const RadPluginInfo kInfo = {
RAD_PLUGIN_KERNEL,
"libavx",
"0.1.0",
"the conventional op vocabulary in hand-written x86 SIMD, dispatched by CPU feature at load: "
"scalar / AVX / AVX2+FMA / AVX-512. Same ops as libref, same schemas, same answers to a "
"tolerance -- the difference is the instruction stream",
/* NOT a -march string. The binary runs everywhere x86-64 runs and picks its own path, so a
* build_target naming one machine would be a claim the plugin does not make. */
"host"
};
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
extern "C" int rad_kernel_schema_count(void) {
return (int)(sizeof(kSchemas) / sizeof(kSchemas[0]));
}
extern "C" const RadOpSchema* rad_kernel_schema_at(int i) {
if (i < 0 || i >= rad_kernel_schema_count()) return nullptr;
return &kSchemas[i];
}
extern "C" int rad_kernel_count(void) {
return (int)(sizeof(kKernels) / sizeof(kKernels[0]));
}
extern "C" const RadKernelInfo* rad_kernel_at(int i) {
if (i < 0 || i >= rad_kernel_count()) return nullptr;
return &kKernels[i];
}
+55
View File
@@ -0,0 +1,55 @@
/* avx_rows.h -- the quantised embedding gather's two halves: the row source, compiled once at the
* baseline, and the row decode, compiled per ISA level.
*
* embed_lookup_q over an E4M3 table into bf16 is a gather of rows that are, most of the time, not in
* memory at all: the n-gram table it exists for is tens of gigabytes in a container that is mapped
* and never loaded. Getting the bytes is the whole cost and is the same work at every ISA level --
* a row cache every thread shares, direct reads for its misses, a reader thread that runs a step
* ahead -- so that half is avx_ngram.cpp, compiled baseline, with one row cache for the process
* whatever level runs. Turning a row's codes into bf16 is the half that differs per level, so the
* level's kernel hands its own decoder in. */
#ifndef RAD_AVX_ROWS_H
#define RAD_AVX_ROWS_H
#include "rad_abi.h"
#include <cstdint>
namespace avx {
/* dst[i][0, n) = lut[src[i][0, n)] for every i < count: E4M3 codes through a table of all 256
* codes already scaled and rounded to bf16. */
typedef void (*RowDecode)(const uint8_t* const* src, uint16_t* const* dst, int64_t count,
int64_t n, const uint16_t* lut);
/* One call's gather, validated by the caller: `ids` holds M row ids, `tab` n_vocab rows of n_embd
* elements -- E4M3 codes, or bf16 as stored -- `row_bytes` apart, `out` M rows of n_embd bf16
* `x_ld` elements apart. The row cache and the reads deal in `row_bytes`; the decode in elements.
* `ahead` holds n_ahead ids a later call will gather, or is null. rank and world_size are the
* call's. */
struct RowGather {
const int32_t* ids;
int64_t M;
const uint8_t* tab;
int64_t n_vocab, n_embd, voff;
int64_t row_bytes;
float scale;
uint16_t* out;
int64_t x_ld;
const int32_t* ahead;
int64_t n_ahead;
int rank, world_size;
};
/* The gather, through the row cache when a file backs the table and from the table's memory when
* none does. Returns a RAD_* status; on anything but RAD_OK the output is not complete. */
int row_gather(const RowGather& g, RowDecode decode);
} /* namespace avx */
/* What the table must be: the E4M3 plane with ONE scale, or a plain bf16 one, stored as it is
* (avx_ngram.cpp). */
extern "C" int avx_layout_ngram(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
#endif /* RAD_AVX_ROWS_H */
+818
View File
@@ -0,0 +1,818 @@
/* avx_sample.cpp -- the sampler ops.
*
* ============================== THESE ARE NOT WHERE THE TIME GOES, EXCEPT WHERE THEY ARE ==============================
*
* Eleven of these twelve ops work over a CANDIDATE SET of a thousand entries at most, and their
* cost is control flow rather than arithmetic. Vectorising them would be work spent where no time
* is; what they get here is the one thing that does matter -- the candidate values widened once
* into f32 so the per-element dtype switch is gone -- and otherwise the reference's structure,
* which is legible and provably right.
*
* The exceptions are the three that touch the WHOLE VOCABULARY, and at a 248K vocabulary that is a
* megabyte a row:
*
* sample_temp a row multiply. Pure vector work, and the trivial one.
* sample_argmax a maximum with the LOWEST index on a tie. Vectorised through the same
* `topk_next_f32` the routers use, so the greedy path and a top-1 path cannot
* disagree about a tie -- which they must not, because a greedy request is
* staged at top_k = 1 when lm_head is vocab-sharded.
* sample_mask a bitmask over the vocabulary. This one has an AVX-512 form that is not
* available below it and is worth the `#if`: the mask word IS a `__mmask16`,
* so applying 16 tokens of grammar is one masked store of -inf and no shifts at
* all. Below AVX-512 it is a shift and a test per token.
*
* ============================== EVERY SCALAR IS PER ROW ==============================
*
* `rep`, `freq`, `pres`, `k`, `p`, the seed and the position are FIELDS OF A ROW (abi/rad_sample.h),
* not parameters. A parameter is geometry -- frozen at declare, matched on by the selector -- so
* two requests in one batch with different top_p would be two resolutions of one op and a
* deployment would have exactly one top_p, which is not a sampler.
*
* ============================== THE CANDIDATE SET ==============================
*
* `sample_topk` produces a FIXED-WIDTH set and the narrowing stages work IN PLACE. The tensors do
* not shrink, so a dropped candidate needs a spelling: index -1, value -infinity. Kept candidates
* stay where they are, in descending order.
*
* `cand_val` carries LOGITS, not probabilities, and each narrowing stage takes its own softmax over
* the set -- which is what llama.cpp does and what keeps the stages composable in any order.
*
* A GREEDY ROW (RAD_SP_GREEDY) HAS NO CANDIDATES: its token is sample_argmax's, top-k and the
* merge write it an empty set, the narrowing stages leave it alone and the pick does not touch its
* token -- libref's contract, for the reason given there.
*/
#include "avx_vec.h"
#include "avx_common.h"
#include "rad_sample.h"
#include <cfloat>
using namespace avx;
/* The params operand, checked once. A sampler op with no rows to act on is not an error -- it is a
* step in which nothing asked for that stage.
*
* The row array is a BYTE BLOB viewed through a 32-bit dtype: the sampler declares it
* [rows, sizeof(RadSampleParams)/4] u32, which is the only way the builder can express "this many
* bytes a row". The dtype is REQUIRED to be a 32-bit one rather than run through
* rad_dtype_bytes -- "any width as long as the arithmetic works out" is the wrong contract, since
* the blob is addressed as 32-bit words and a 16-bit view would pass a byte count and then misread
* every row. */
struct Rows { const RadSampleParams* p; int64_t n; };
static inline int rows_of_params(const RadTensor* t, int64_t M, Rows* out) {
if (!t || !t->data) return RAD_E_INVAL;
if (t->dtype != RAD_U32 && t->dtype != RAD_I32 && t->dtype != RAD_F32) return RAD_E_DTYPE;
if (numel(t) * 4 < M * (int64_t)sizeof(RadSampleParams)) return RAD_E_SHAPE;
out->p = (const RadSampleParams*)t->data;
out->n = M;
return RAD_OK;
}
#define AVX_TRY(expr) do { const int _s = (expr); if (_s < 0) return _s; } while (0)
/* The history window both history stages read, libref's reading (ref_sample.cpp): `hist_off` and
* `hist_len` address the row's own row of the history plane, clamped to it, and `last_n` keeps
* the TAIL of that span. last_n 0 turns the stage off for the row, a negative one keeps the whole
* span -- llama.cpp's meaning for repeat_last_n and dry_penalty_last_n. */
static inline bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_t hmax,
int64_t* ho_out, int64_t* hl_out) {
if (last_n == 0) return false;
int64_t hl = sp.hist_len;
int64_t ho = sp.hist_off < 0 ? 0 : sp.hist_off;
if (ho > hmax) ho = hmax;
if (hl > hmax - ho) hl = hmax - ho;
if (last_n > 0 && hl > last_n) {
ho += hl - last_n;
hl = last_n;
}
*ho_out = ho;
*hl_out = hl;
return hl > 0;
}
/* ------------------------------------------------------------------ sample_penalties */
/* llama.cpp's ordering, in one pass over the row's history:
*
* repetition logit = logit > 0 ? logit / rep : logit * rep (once per DISTINCT token)
* frequency logit -= count * freq
* presence logit -= pres (once per distinct token)
*
* The repetition penalty being multiplicative and SIGN-DEPENDENT is the part everyone gets wrong:
* dividing a negative logit would make it larger, so it is multiplied instead.
*
* The history is pulled into a small int array once. libref reads it back through ld_int inside
* the O(hl^2) first-occurrence test, which is a dtype switch per comparison on a loop that runs
* hl^2 times; the array makes the inner test an integer compare. The ORDER and the answer are
* unchanged -- this is the same quadratic scan, over the same values.
*
* History ids are GLOBAL and the logits row is this rank's shard, so a token's column is its id
* less `vocab_off`, and a token outside the shard is another rank's to penalise. */
AVX_KERNEL(sample_penalties) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *hist = &a->t[2];
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
AVX_TRY(rows_of_params(pr, M, &R));
const int64_t hmax = numel(hist) / M;
if (hmax <= 0) return RAD_E_SHAPE;
const int64_t voff = p_int(a, "vocab_off", 0);
AVX_PARALLEL_FOR_IF(M >= 2)
for (int64_t m = 0; m < M; ++m) {
const RadSampleParams& sp = R.p[m];
if (!(sp.flags & RAD_SP_PENALTY)) continue;
const float rep = sp.rep_penalty, freq = sp.freq_penalty, pres = sp.pres_penalty;
if (rep == 1.0f && freq == 0.0f && pres == 0.0f) continue;
int64_t ho = 0, hl = 0;
if (!hist_window(sp, sp.penalty_last_n, hmax, &ho, &hl)) continue;
const int64_t hb = rowoff(hist, m, hmax) + ho * laststride(hist);
const int64_t hs = laststride(hist);
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
int32_t* h = (int32_t*)scratch_f32((size_t)hl);
for (int64_t i = 0; i < hl; ++i) h[i] = (int32_t)ldi(hist, hb + i * hs);
for (int64_t i = 0; i < hl; ++i) {
const int32_t tok = h[i];
const int64_t col = (int64_t)tok - voff;
if (tok < 0 || col < 0 || col >= n_vocab) continue;
/* First occurrence only: the penalties are per distinct token, and the count is what
* carries the multiplicity. */
bool first = true;
int64_t count = 0;
for (int64_t j = 0; j < hl; ++j) {
if (h[j] != tok) continue;
if (j < i) { first = false; break; }
++count;
}
if (!first) continue;
float v = ldt(lg, lb + col * ls);
v = v > 0.0f ? v / rep : v * rep;
v -= (float)count * freq;
v -= pres;
stt(lg, lb + col * ls, v);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ sample_dry */
/* DRY -- "don't repeat yourself". libref's definition (ref_sample.cpp), which is llama.cpp's:
* each token that would EXTEND a suffix of the window that has occurred before is penalised ONCE,
* by multiplier * base^(L - allowed_length) for the LONGEST repeat L it would extend, repeats
* capped at the row's `dry_rep_limit`. A position the optional `breakers` plane marks holds a
* whole sequence breaker, which is never penalised. The penalty is formed by repeated
* multiplication stopping short of overflow, the way every implementation of this op forms it,
* so they agree to the bit.
*
* The window is pulled into an int array once, as the penalties do, and the per-position repeat
* lengths go into a second one; the longest per token is then found by scanning those lengths for
* each qualifying position, which needs no map and keeps the quadratic scan's memory access
* inside two small arrays. */
static inline float dry_penalty(float multiplier, float base, int64_t e) {
float pen = multiplier;
if (base == 1.0f) return pen;
const float lim = FLT_MAX / base;
for (int64_t i = 0; i < e; ++i) {
if (pen > lim) break;
pen *= base;
}
return pen;
}
AVX_KERNEL(sample_dry) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *hist = &a->t[2];
const RadTensor* brk = rad_arg_in(a, 3);
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
AVX_TRY(rows_of_params(pr, M, &R));
const int64_t hmax = numel(hist) / M;
if (hmax <= 0) return RAD_E_SHAPE;
if (brk && numel(brk) < M * hmax) return RAD_E_SHAPE;
const int64_t voff = p_int(a, "vocab_off", 0);
AVX_PARALLEL_FOR_IF(M >= 2)
for (int64_t m = 0; m < M; ++m) {
const RadSampleParams& sp = R.p[m];
if (!(sp.flags & RAD_SP_DRY) || !(sp.dry_multiplier > 0.0f)) continue;
const int64_t allowed = sp.dry_allowed_length > 0 ? sp.dry_allowed_length : 2;
int64_t ho = 0, hl = 0;
if (!hist_window(sp, sp.dry_penalty_last_n, hmax, &ho, &hl)) continue;
if (hl <= allowed) continue;
const int64_t cap = sp.dry_rep_limit > 0 && sp.dry_rep_limit < hl ? sp.dry_rep_limit : hl;
if (cap < allowed) continue;
const int64_t hb = rowoff(hist, m, hmax) + ho * laststride(hist);
const int64_t hs = laststride(hist);
const int64_t bb = brk ? rowoff(brk, m, hmax) + ho * laststride(brk) : 0;
const int64_t bs = brk ? laststride(brk) : 0;
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
int32_t* h = (int32_t*)scratch_f32((size_t)hl);
int32_t* len = (int32_t*)scratch_f32_b((size_t)hl);
for (int64_t i = 0; i < hl; ++i) h[i] = (int32_t)ldi(hist, hb + i * hs);
/* len[j]: how long a suffix of the window also ends at position j, capped; 0 where the
* continuation after j is exempt or outside this rank's shard, since such a j is never
* penalised and never the longest for a token that is. */
for (int64_t j = 0; j + 1 < hl; ++j) {
const int64_t lim = j + 1 < cap ? j + 1 : cap;
int64_t n = 0;
while (n < lim && h[j - n] == h[hl - 1 - n]) ++n;
const int64_t col = (int64_t)h[j + 1] - voff;
const bool skip = (brk && ldi(brk, bb + (j + 1) * bs) != 0) || h[j + 1] < 0 ||
col < 0 || col >= n_vocab;
len[j] = skip ? 0 : (int32_t)n;
}
const float base = sp.dry_base > 0.0f ? sp.dry_base : 1.75f;
for (int64_t j = 0; j + 1 < hl; ++j) {
if (len[j] < allowed) continue;
/* The representative of this continuation token: its longest repeat, the earliest
* position on a tie. Every other position of the same token defers to it, so the
* token is penalised once. */
const int32_t next = h[j + 1];
bool rep = true;
for (int64_t j2 = 0; j2 + 1 < hl && rep; ++j2) {
if (j2 == j || h[j2 + 1] != next) continue;
if (len[j2] > len[j] || (len[j2] == len[j] && j2 < j)) rep = false;
}
if (!rep) continue;
const int64_t off = lb + ((int64_t)next - voff) * ls;
stt(lg, off, ldt(lg, off) - dry_penalty(sp.dry_multiplier, base, len[j] - allowed));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ sample_temp */
/* temp <= 0 leaves the row untouched: greedy decoding is `sample_argmax`, and a temperature of
* zero silently meaning something else is how a sampler chain becomes unreadable. */
AVX_KERNEL(sample_temp) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1];
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
AVX_TRY(rows_of_params(pr, M, &R));
AVX_PARALLEL_FOR_IF(M * n_vocab >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
const float t = R.p[m].temp;
if (!(t > 0.0f) || t == 1.0f) continue;
const float inv = 1.0f / t;
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
if (ls != 1) {
for (int64_t i = 0; i < n_vocab; ++i) stt(lg, lb + i * ls, ldt(lg, lb + i * ls) * inv);
continue;
}
float* buf = scratch_f32((size_t)n_vocab);
const float* v = in_row(lg, lb, n_vocab, buf);
float* out = (v == buf) ? buf : scratch_f32_b((size_t)n_vocab);
const vf vi = vf_set1(inv);
int64_t i = 0;
for (; i + VF_N <= n_vocab; i += VF_N) vf_storeu(out + i, vf_mul(vf_loadu(v + i), vi));
for (; i < n_vocab; ++i) out[i] = v[i] * inv;
out_row(lg, lb, n_vocab, out);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ sample_topk */
AVX_KERNEL(sample_topk) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *ci = &a->t[2], *cv = &a->t[3];
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
AVX_TRY(rows_of_params(pr, M, &R));
/* The candidate WIDTH is the buffer's, not the request's: it is the deployment bound the arena
* was sized for, and every later stage reads it. */
const int64_t n_cand = ci->rank >= 2 ? ci->shape[ci->rank - 1] : numel(ci) / M;
if (n_cand <= 0 || numel(cv) < M * n_cand) return RAD_E_SHAPE;
/* THE VOCAB-PARALLEL PAIR PLANE, optional. cand_idx stays LOCAL -- it indexes this rank's
* logits row and every stage after top-k reads it that way -- and `pairs` carries the same
* candidates with `vocab_off` added, as (u32 GLOBAL id, f32 logit), which is what the
* all-gather moves and what sample_merge_topk reads. */
const RadTensor* pp = a->n_t > 4 && a->t[4].data ? &a->t[4] : nullptr;
const int64_t voff = p_int(a, "vocab_off", 0);
if (pp && numel(pp) < M * 2 * n_cand) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(M * n_vocab >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
/* A row's own top_k, clamped to the buffer. 0 or negative means "the whole candidate
* width", which is what a request that set no top_k asks for. A greedy row takes none,
* and its row of logits is not even read. */
int64_t k = R.p[m].top_k;
if (k <= 0 || k > n_cand) k = n_cand;
if (R.p[m].flags & RAD_SP_GREEDY) k = 0;
const int64_t lb = rowoff(lg, m, n_vocab);
const int64_t ib = rowoff(ci, m, n_cand), is = laststride(ci);
const int64_t vb = rowoff(cv, m, n_cand), vs = laststride(cv);
const int64_t pb = pp ? rowoff(pp, m, 2 * n_cand) : 0, ps = pp ? laststride(pp) : 0;
float* buf = scratch_f32((size_t)n_vocab);
const float* v = k > 0 ? in_row(lg, lb, n_vocab, buf) : buf;
float pv = INFINITY;
int64_t pi = -1;
for (int64_t r = 0; r < n_cand; ++r) {
const bool ok = r < k && topk_next_f32(v, n_vocab, &pv, &pi);
st_int_dt(ci->dtype, ci->data, ib + r * is, ok ? pi : -1);
stt(cv, vb + r * vs, ok ? pv : -INFINITY);
if (!pp) continue;
/* 0xffffffff is the hole, which the merge tests as a negative signed id -- the same
* convention cand_idx carries as -1. */
uint32_t bits;
const float val = ok ? pv : -INFINITY;
std::memcpy(&bits, &val, 4);
st_int_dt(pp->dtype, pp->data, pb + (2 * r) * ps,
ok ? (int64_t)(pi + voff) : (int64_t)0xffffffffu);
st_int_dt(pp->dtype, pp->data, pb + (2 * r + 1) * ps, (int64_t)bits);
}
}
return RAD_OK;
}
/* ================================================================== the narrowing stages
*
* All four widen the candidate values into f32 ONCE and then work on that array, which is the only
* change from libref's structure: it reads `cand_val` back through `ldt` inside loops that are
* O(n_cand) (top-p, min-p, XTC) and O(n_cand^2) (typical), so the dtype switch runs up to a
* million times on a thousand-wide set for one row.
*
* The typical stage additionally precomputes the probability and the surprisal distance per
* candidate, because libref recomputes `exp` and `log` inside its threshold search -- three libm
* calls per (candidate, candidate) pair. The search itself stays O(n_cand^2) and stays exactly the
* scan libref performs, because the answer is a threshold chosen among the distances that actually
* occur and any faster search would have to sort, which changes which of two equal distances is
* found first. */
enum Narrow { NR_TOPP, NR_MINP, NR_TYPICAL, NR_XTC };
static int narrow(const RadArgs* a, Narrow which) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *ci = &a->t[0], *cv = &a->t[1], *pr = &a->t[2];
const int64_t n_cand = p_int(a, "n_cand", ci->rank >= 2 ? ci->shape[ci->rank - 1] : 0);
if (n_cand <= 0) return RAD_E_SHAPE;
const int64_t M = numel(ci) / n_cand;
if (M <= 0 || numel(cv) < M * n_cand) return RAD_E_SHAPE;
Rows R;
AVX_TRY(rows_of_params(pr, M, &R));
AVX_PARALLEL_FOR_IF(M >= 2)
for (int64_t m = 0; m < M; ++m) {
const RadSampleParams& sp = R.p[m];
if (sp.flags & RAD_SP_GREEDY) continue;
const int64_t ib = rowoff(ci, m, n_cand), is = laststride(ci);
const int64_t vb = rowoff(cv, m, n_cand), vs = laststride(cv);
float* val = scratch_f32((size_t)n_cand);
float* prob = scratch_f32_b((size_t)n_cand);
unsigned char* alive = (unsigned char*)scratch_f32_c((size_t)n_cand / 4 + 4);
for (int64_t i = 0; i < n_cand; ++i) {
alive[i] = ldi(ci, ib + i * is) >= 0 ? 1 : 0;
val[i] = alive[i] ? ldt(cv, vb + i * vs) : -INFINITY;
}
auto drop = [&](int64_t i) {
st_int_dt(ci->dtype, ci->data, ib + i * is, -1);
stt(cv, vb + i * vs, -INFINITY);
};
float mx = -INFINITY;
for (int64_t i = 0; i < n_cand; ++i) if (alive[i] && val[i] > mx) mx = val[i];
if (mx == -INFINITY) continue;
if (which == NR_MINP) {
const float p = sp.min_p;
if (!(p > 0.0f)) continue;
/* Keep everything within a factor p of the most likely candidate. Comparing
* exp(v - max) against p is the same test as prob >= p * max_prob without forming the
* normaliser -- one fewer pass and one fewer rounding. */
for (int64_t i = 0; i < n_cand; ++i) {
if (!alive[i]) continue;
if (val[i] == mx) continue; /* the max always survives */
if (std::exp(val[i] - mx) < p) drop(i);
}
continue;
}
float sum = 0.0f;
for (int64_t i = 0; i < n_cand; ++i) if (alive[i]) sum += std::exp(val[i] - mx);
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
for (int64_t i = 0; i < n_cand; ++i)
prob[i] = alive[i] ? std::exp(val[i] - mx) * inv : 0.0f;
if (which == NR_TOPP) {
const float p = sp.top_p;
if (!(p < 1.0f) || !(p > 0.0f)) continue;
/* The candidates arrive in DESCENDING order from sample_topk and this op does not
* re-sort them. Keep the shortest prefix whose cumulative probability reaches p, and
* always keep at least one -- a p small enough to select nothing still has to produce
* a token. */
float cum = 0.0f;
bool done = false;
int64_t kept = 0;
for (int64_t i = 0; i < n_cand; ++i) {
if (!alive[i]) continue;
if (done) { drop(i); continue; }
cum += prob[i];
++kept;
if (cum >= p && kept >= 1) done = true;
}
continue;
}
if (which == NR_TYPICAL) {
const float p = sp.typical_p;
if (!(p < 1.0f) || !(p > 0.0f)) continue;
/* Locally typical sampling: keep the candidates whose surprisal -log(prob) is closest
* to the distribution's entropy, until their mass reaches p. The candidate order is by
* probability and this order is by |surprisal - H|, so the two disagree and the
* selection is a threshold on the distance rather than a prefix. Ties are kept, which
* can overshoot p slightly -- the alternative is an order that depends on the
* candidate index. */
float H = 0.0f;
for (int64_t i = 0; i < n_cand; ++i)
if (alive[i] && prob[i] > 0.0f) H -= prob[i] * std::log(prob[i]);
float* dist = val; /* `val` is dead from here: the distances reuse its storage. */
for (int64_t i = 0; i < n_cand; ++i)
dist[i] = (alive[i] && prob[i] > 0.0f) ? std::fabs(-std::log(prob[i]) - H) : 0.0f;
float cut = 0.0f;
bool have_cut = false;
for (int64_t c = 0; c < n_cand; ++c) {
if (!alive[c] || !(prob[c] > 0.0f)) continue;
const float dc = dist[c];
float mass = 0.0f;
for (int64_t i = 0; i < n_cand; ++i) {
if (!alive[i] || !(prob[i] > 0.0f)) continue;
if (dist[i] <= dc) mass += prob[i];
}
if (mass >= p && (!have_cut || dc < cut)) { cut = dc; have_cut = true; }
}
if (!have_cut) continue;
for (int64_t i = 0; i < n_cand; ++i) {
if (!alive[i]) continue;
if (!(prob[i] > 0.0f) || dist[i] > cut) drop(i);
}
continue;
}
/* XTC -- "exclude top choices". With probability `xtc_probability`, DROP every candidate
* above `xtc_threshold` except the LEAST likely of them, which is the opposite of every
* other stage here and is the point: it removes the obvious continuations and leaves the
* interesting one. The draw is per row and comes from the row's own stream, so it
* reproduces. */
{
if (!(sp.xtc_probability > 0.0f) || !(sp.xtc_threshold > 0.0f)) continue;
if (rad_sample_uniform01(sp.seed ^ RAD_SAMPLE_KEY_XTC, sp.pos) >= sp.xtc_probability)
continue;
int64_t last_above = -1, n_above = 0;
for (int64_t i = 0; i < n_cand; ++i) {
if (!alive[i]) continue;
if (prob[i] >= sp.xtc_threshold) { last_above = i; ++n_above; }
}
/* Nothing to do unless at least two candidates clear the threshold: dropping the only
* one would leave the row without its own choice. */
if (n_above < 2) continue;
for (int64_t i = 0; i < n_cand; ++i) {
if (!alive[i] || i == last_above) continue;
if (prob[i] >= sp.xtc_threshold) drop(i);
}
}
}
return RAD_OK;
}
AVX_KERNEL(sample_topp) { return narrow(a, NR_TOPP); }
AVX_KERNEL(sample_minp) { return narrow(a, NR_MINP); }
AVX_KERNEL(sample_typical) { return narrow(a, NR_TYPICAL); }
AVX_KERNEL(sample_xtc) { return narrow(a, NR_XTC); }
/* ------------------------------------------------------------------ sample_mask */
/* Where a GBNF grammar lands. The state machine stays on host and what crosses is a token bitmask
* per sequence -- 19 KiB at a 151K vocab, cheap enough to upload every step.
*
* A SET BIT MEANS ALLOWED. That polarity has to be stated: a grammar produces a set of admissible
* tokens, and the mask is that set rather than its complement. Word w bit b covers token 32*w + b,
* least significant bit first.
*
* THE AVX-512 FORM IS DIFFERENT IN KIND, not just in width, and that is why it gets an `#if`. A
* `__mmask16` IS sixteen bits of the grammar word, so applying sixteen tokens is one masked store
* of -inf with the mask inverted -- no shift, no test, no branch per token. Below AVX-512 the mask
* has to be materialised as a vector of 0/-1 and blended, which costs more than the shift-and-test
* it replaces at these widths, so those levels keep the scalar loop and say so. */
AVX_KERNEL(sample_mask) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *bm = &a->t[2];
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
AVX_TRY(rows_of_params(pr, M, &R));
const int64_t words = (n_vocab + 31) / 32;
const int64_t mask_rows = numel(bm) / (words > 0 ? words : 1);
if (mask_rows <= 0) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(M * n_vocab >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
const RadSampleParams& sp = R.p[m];
if (!(sp.flags & RAD_SP_MASK)) continue;
const int64_t row = sp.mask_row;
if (row < 0 || row >= mask_rows) continue;
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
const int64_t bb = rowoff(bm, row, words), bs = laststride(bm);
#if AVX_LEVEL == 3
if (ls == 1 && lg->dtype == RAD_F32 && bs == 1 &&
(bm->dtype == RAD_U32 || bm->dtype == RAD_I32)) {
float* p = (float*)lg->data + lb;
const uint32_t* w = (const uint32_t*)bm->data + bb;
const __m512 neg = _mm512_set1_ps(-INFINITY);
int64_t i = 0;
for (; i + 32 <= n_vocab; i += 32) {
const uint32_t bits = w[i / 32];
/* The mask is the COMPLEMENT: a set grammar bit is allowed and must be left
* alone, so -inf is stored where the bit is clear. */
_mm512_mask_storeu_ps(p + i, (__mmask16)(~(uint16_t)(bits & 0xffffu)), neg);
_mm512_mask_storeu_ps(p + i + 16, (__mmask16)(~(uint16_t)(bits >> 16)), neg);
}
for (; i < n_vocab; ++i)
if (!((w[i / 32] >> (i % 32)) & 1u)) p[i] = -INFINITY;
continue;
}
#endif
for (int64_t i = 0; i < n_vocab; ++i) {
const uint32_t word = (uint32_t)ldi(bm, bb + (i / 32) * bs);
if (!((word >> (i % 32)) & 1u)) stt(lg, lb + i * ls, -INFINITY);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ sample_pick */
/* The inverse CDF, walked in candidate order, accumulating in f32. The fallback is the LAST
* CANDIDATE ABOVE -INFINITY: `u` is strictly below 1 and the probabilities sum to 1 in exact
* arithmetic, but they do not in f32, and a draw that falls through the last comparison must still
* produce a token the distribution allows -- not one of the grammar-masked candidates that top-k
* leaves at -infinity at the tail of the set. A greedy row is skipped: its token is the argmax's.
*
* THE DRAW IS SPECIFIED rather than left to a library (abi/rad_sample.h): splitmix64 over
* (seed * golden ratio + pos), 24 bits as a float in [0, 1). The same stream has to come out of a
* host reference, a device kernel and a rerun. */
AVX_KERNEL(sample_pick) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *ci = &a->t[0], *cv = &a->t[1], *pr = &a->t[2], *tok = &a->t[3];
const int64_t n_cand = p_int(a, "n_cand", ci->rank >= 2 ? ci->shape[ci->rank - 1] : 0);
if (n_cand <= 0) return RAD_E_SHAPE;
const int64_t M = numel(ci) / n_cand;
if (M <= 0 || numel(cv) < M * n_cand || numel(tok) < M) return RAD_E_SHAPE;
Rows R;
AVX_TRY(rows_of_params(pr, M, &R));
AVX_PARALLEL_FOR_IF(M >= 2)
for (int64_t m = 0; m < M; ++m) {
if (R.p[m].flags & RAD_SP_GREEDY) continue;
const int64_t ib = rowoff(ci, m, n_cand), is = laststride(ci);
const int64_t vb = rowoff(cv, m, n_cand), vs = laststride(cv);
float mx = -INFINITY;
for (int64_t i = 0; i < n_cand; ++i) {
if (ldi(ci, ib + i * is) < 0) continue;
const float v = ldt(cv, vb + i * vs);
if (v > mx) mx = v;
}
if (mx == -INFINITY) { st_int_dt(tok->dtype, tok->data, offlin(tok, m), -1); continue; }
float sum = 0.0f;
for (int64_t i = 0; i < n_cand; ++i) {
if (ldi(ci, ib + i * is) < 0) continue;
sum += std::exp(ldt(cv, vb + i * vs) - mx);
}
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
const float u = rad_sample_uniform01(R.p[m].seed ^ RAD_SAMPLE_KEY_PICK, R.p[m].pos);
float cum = 0.0f;
int64_t chosen = -1, last = -1;
for (int64_t i = 0; i < n_cand; ++i) {
const int64_t id = ldi(ci, ib + i * is);
if (id < 0) continue;
const float v = ldt(cv, vb + i * vs);
if (v > -INFINITY) last = id;
cum += std::exp(v - mx) * inv;
if (u < cum) { chosen = id; break; }
}
st_int_dt(tok->dtype, tok->data, offlin(tok, m), chosen >= 0 ? chosen : last);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ sample_argmax */
/* Greedy, ties to the LOWER token id -- the same tie rule the top-k selection uses, so a greedy
* step and a top-1 step cannot disagree. That is not decoration: when lm_head is vocab-sharded,
* `sample_argmax` is unusable (its answer is a LOCAL column) and a greedy request is staged at
* top_k = 1 through the chain instead, so the two paths must select the same token.
*
* Run through the same `topk_next_f32` the routers use, for exactly that reason. */
AVX_KERNEL(sample_argmax) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *tok = &a->t[2];
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
if (M <= 0 || numel(tok) < M) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(M * n_vocab >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
float* buf = scratch_f32((size_t)n_vocab);
const float* v = in_row(lg, rowoff(lg, m, n_vocab), n_vocab, buf);
float pv = INFINITY;
int64_t pi = -1;
const bool ok = topk_next_f32(v, n_vocab, &pv, &pi);
st_int_dt(tok->dtype, tok->data, offlin(tok, m), ok ? pi : -1);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ sample_merge_topk */
/* THE VOCAB-PARALLEL MERGE. lm_head is vocab-sharded, so each rank runs top-k over ITS OWN shard
* and the candidate sets are all-gathered -- k * world_size pairs, 2 KiB at k=64 and world_size=4,
* against the ~77 MiB a full-logits gather would move.
*
* `gathered` is [M, world_size * n_cand] pairs of (token id, logit) as raw u32 words. The token id
* is already GLOBAL, because each rank adds its own vocab offset before the gather -- a merge that
* had to know the offsets would need the shard layout, which is the caller's business. THE LOGIT
* IS READ BY BIT PATTERN: the buffer's dtype can only be one of the two halves' types, it is u32,
* and a float read through it would turn 0x40800000 into 1.08e9 instead of 4.0.
*
* THE ROW'S OWN top_k IS RE-APPLIED, and that is why this takes `params`. Every rank ran top-k over
* its own shard before the gather, so the merged set holds up to world_size * k candidates where
* the request asked for k, and no stage after this one narrows again. At k = 1 that is not a
* slightly wider support, it is a different ANSWER: a greedy row is staged at top_k = 1 exactly so
* this chain returns the argmax, and with world_size candidates alive `sample_pick` draws among
* them against the request's seed. */
AVX_KERNEL(sample_merge_topk) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *gt = &a->t[0], *pr = &a->t[1], *ci = &a->t[2], *cv = &a->t[3];
const int64_t n_cand = p_int(a, "n_cand", ci->rank >= 2 ? ci->shape[ci->rank - 1] : 0);
if (n_cand <= 0) return RAD_E_SHAPE;
const int64_t M = numel(ci) / n_cand;
if (M <= 0 || numel(cv) < M * n_cand) return RAD_E_SHAPE;
Rows R;
AVX_TRY(rows_of_params(pr, M, &R));
if (gt->dtype != RAD_U32 && gt->dtype != RAD_I32) return RAD_E_DTYPE;
const int64_t per_row = numel(gt) / M;
const int64_t n_in = per_row / 2;
if (n_in <= 0) return RAD_E_SHAPE;
auto bits_to_f32 = [](int64_t w) {
const uint32_t u = (uint32_t)w;
float f;
std::memcpy(&f, &u, 4);
return f;
};
AVX_PARALLEL_FOR_IF(M >= 2)
for (int64_t m = 0; m < M; ++m) {
const int64_t gb = rowoff(gt, m, per_row), gs = laststride(gt);
const int64_t ib = rowoff(ci, m, n_cand), is = laststride(ci);
const int64_t vb = rowoff(cv, m, n_cand), vs = laststride(cv);
const int32_t tk = R.p[m].top_k;
const int64_t keep = (R.p[m].flags & RAD_SP_GREEDY) ? 0
: (tk > 0 && (int64_t)tk < n_cand) ? (int64_t)tk : n_cand;
/* The pairs are unpacked ONCE into two arrays. libref reads both halves back through
* ld_int inside the O(n_cand * n_in) selection, which is two dtype switches per comparison.
* The selection itself stays a selection sort over n_in entries, ties to the lower token
* id -- the tie rule every other selection in this vocabulary uses. */
float* gv = scratch_f32((size_t)n_in);
int32_t* gi = (int32_t*)scratch_f32_b((size_t)n_in);
for (int64_t j = 0; j < n_in; ++j) {
gi[j] = (int32_t)(uint32_t)ldi(gt, gb + 2 * j * gs);
gv[j] = bits_to_f32(ldi(gt, gb + (2 * j + 1) * gs));
}
float taken_v = INFINITY;
int64_t taken_i = -1;
for (int64_t r = 0; r < n_cand; ++r) {
if (r >= keep) {
st_int_dt(ci->dtype, ci->data, ib + r * is, -1);
stt(cv, vb + r * vs, -INFINITY);
continue;
}
float best = -INFINITY;
int64_t best_id = -1;
for (int64_t j = 0; j < n_in; ++j) {
const int64_t id = gi[j];
const float v = gv[j];
if (id < 0) continue;
const bool after = v < taken_v || (v == taken_v && id > taken_i);
if (!after) continue;
if (best_id < 0 || v > best || (v == best && id < best_id)) {
best = v;
best_id = id;
}
}
st_int_dt(ci->dtype, ci->data, ib + r * is, best_id);
stt(cv, vb + r * vs, best_id >= 0 ? best : -INFINITY);
if (best_id < 0) continue;
taken_v = best;
taken_i = best_id;
}
}
return RAD_OK;
}
/* ================================================================== dflash_select
*
* Not a sampler, and here because it is the other op that picks TOKENS: DFlash2's greedy walk over
* a candidate lattice. A block-diffusion drafter proposes every position of a block in one pass, so
* it cannot condition position l+1 on its pick at l; this puts that dependence back.
*
* score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * hp[l][r] * succ[cand[l, c]][r]
* pid(0) = anchor[s * anchor_stride], pid(l) = cand[l - 1, chosen(l - 1)]
*
* `hp` ABSENT IS A PLANE OF ONES -- a plain low-rank bigram. The walk is SERIAL IN l, since the
* predecessor is not known until the previous step is decided, so the parallel axis is the
* sequence and the vector work is the rank-R dot a candidate costs. A predecessor or a candidate
* outside the vocabulary contributes nothing rather than reading past a codebook; the highest
* score wins and a tie goes to the lower candidate, libref's rule. */
static inline float dot_r(const float* a, const float* b, int64_t n) {
vf acc = vf_zero();
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) acc = vf_fma(vf_loadu(a + i), vf_loadu(b + i), acc);
float s = vf_hsum(acc);
for (; i < n; ++i) s += a[i] * b[i];
return s;
}
AVX_KERNEL(dflash_select) {
if (a->n_t < 7) return RAD_E_INVAL;
const RadTensor *cand = &a->t[0], *un = &a->t[1], *anc = &a->t[3];
const RadTensor *pred = &a->t[4], *succ = &a->t[5], *out = &a->t[6];
const RadTensor* hp = rad_arg_in(a, 2);
if (!cand->data || !un->data || !anc->data || !pred->data || !succ->data || !out->data)
return RAD_E_INVAL;
const int64_t steps = p_int(a, "steps", 0);
const int64_t K = p_int(a, "top_k", 0);
/* `cand` is [M * steps, K] and it is the call; `M` is the band (avx_common.h, band_rows). */
const int64_t M = steps > 0 && K > 0
? band_rows(numel(cand) / (steps * K), p_int(a, "M", 0)) : 0;
const int64_t R = p_int(a, "rank", pred->rank >= 2 ? pred->shape[pred->rank - 1] : 0);
const int64_t nv = p_int(a, "n_vocab", pred->rank >= 2 ? pred->shape[pred->rank - 2] : 0);
const int64_t astr = p_int(a, "anchor_stride", 1);
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || nv <= 0 || astr <= 0) return RAD_E_SHAPE;
if (numel(un) < M * steps * K) return RAD_E_SHAPE;
if (numel(anc) < (M - 1) * astr + 1 || numel(out) < M * steps) return RAD_E_SHAPE;
if (numel(pred) < nv * R || numel(succ) < nv * R) return RAD_E_SHAPE;
if (hp && numel(hp) < M * steps * R) return RAD_E_SHAPE;
const int64_t cs = laststride(cand), us = laststride(un), os = laststride(out);
AVX_PARALLEL_FOR_IF(M * steps * K * R >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
float* ax = scratch_f32((size_t)R);
float* rv = scratch_f32_b((size_t)R);
float* hv = scratch_f32_c((size_t)R);
int64_t pid = ldi(anc, offlin(anc, m * astr));
for (int64_t l = 0; l < steps; ++l) {
const int64_t r = m * steps + l;
const int64_t cb = rowoff(cand, r, K), ub = rowoff(un, r, K);
/* The half of the form that does not depend on the candidate, once a step. */
const bool ok = pid >= 0 && pid < nv;
const float* pv = ok ? in_row(pred, rowoff(pred, pid, R), R, rv) : nullptr;
const float* hw = hp ? in_row(hp, rowoff(hp, r, R), R, hv) : nullptr;
for (int64_t i = 0; i < R; ++i)
ax[i] = (ok ? pv[i] : 0.0f) * (hp ? hw[i] : 1.0f);
int64_t best_c = 0;
float best_s = -INFINITY;
for (int64_t c = 0; c < K; ++c) {
const int64_t tok = ld_int_dt(cand->dtype, cand->data, cb + c * cs);
float sc = ldt(un, ub + c * us);
if (tok >= 0 && tok < nv)
sc += dot_r(ax, in_row(succ, rowoff(succ, tok, R), R, rv), R);
if (sc > best_s) { best_s = sc; best_c = c; }
}
pid = ld_int_dt(cand->dtype, cand->data, cb + best_c * cs);
st_int_dt(out->dtype, out->data, rowoff(out, m, steps) + l * os, pid);
}
}
return RAD_OK;
}
+417
View File
@@ -0,0 +1,417 @@
/* avx_support.cpp -- the dtype-generic row and the row reductions, compiled once per ISA level.
*
* WHY THESE ARE OUT OF LINE AND NOT IN THE HEADER. They are called from every kernel with a
* runtime dtype, so inlining them would paste a fifteen-way switch into sixty-eight call sites and
* the switch is the thing being hoisted out of the loop in the first place. Out of line, the
* branch is taken ONCE PER ROW and the body it lands in is a straight vector loop the hardware
* prefetcher can see through.
*
* The conversion rates per level are measured by `rad-avx-bench --cvt` and recorded in
* libavx/README.md rather than here, because they are a property of the machine the bench last ran
* on and a number typed into a comment outlives the machine that produced it.
*
* The two fp8 decodes take different paths and avx_vec.h says why: e4m3 is a branchless bit
* reconstruction, e5m2 a table gather, and the scalar level and every tail element read the table
* in both cases.
*/
#include "avx_vec.h"
#include "avx_common.h"
namespace avx {
inline namespace AVX_SUFFIX {
/* ================================================================== packed weight codes
* The conventions are libr4d's, because a .rad is specific to a kernel set (spec §4.2) and this
* plugin has to read the same bytes: W4 is two nibbles a byte with element 2i LOW and a symmetric
* two's-complement code ((n ^ 8) - 8), W2 four codes a byte with the same construction one radix
* down, MXFP4 two e2m1 nibbles with the magnitude table below. libref/ref_common.h is the written
* definition and this is the vectorised reading of it.
*
* THE W4 UNPACK IS A SHUFFLE, NOT A SHIFT PER ELEMENT. Sixteen nibble pairs are one 128-bit load;
* the low nibbles are an AND and the high ones a shift, and the two interleave back with a
* punpcklbw -- four instructions for 32 elements against 32 shifts and 32 masks scalar. W2 and
* MXFP4 are left scalar: W2 appears only in the draft head's lm_head and MXFP4 only in an expert
* grid this plugin does not serve at speed, so neither is on a path worth the code. */
static const float kMxfp4Mag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
static void w4_to_f32(const uint8_t* src, float* dst, int64_t n) {
int64_t i = 0;
#if AVX_LEVEL >= 2
const __m128i lomask = _mm_set1_epi8(0x0f);
for (; i + 32 <= n; i += 32) {
__m128i b = _mm_loadu_si128((const __m128i*)(src + (i >> 1)));
__m128i lo = _mm_and_si128(b, lomask);
__m128i hi = _mm_and_si128(_mm_srli_epi16(b, 4), lomask);
lo = _mm_sub_epi8(_mm_xor_si128(lo, _mm_set1_epi8(8)), _mm_set1_epi8(8));
hi = _mm_sub_epi8(_mm_xor_si128(hi, _mm_set1_epi8(8)), _mm_set1_epi8(8));
__m128i e0 = _mm_unpacklo_epi8(lo, hi); /* codes 0..15 */
__m128i e1 = _mm_unpackhi_epi8(lo, hi); /* codes 16..31 */
#if AVX_LEVEL >= 3
_mm512_storeu_ps(dst + i, _mm512_cvtepi32_ps(_mm512_cvtepi8_epi32(e0)));
_mm512_storeu_ps(dst + i + 16, _mm512_cvtepi32_ps(_mm512_cvtepi8_epi32(e1)));
#else
_mm256_storeu_ps(dst + i, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(e0)));
_mm256_storeu_ps(dst + i + 8,
_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(e0, 8))));
_mm256_storeu_ps(dst + i + 16, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(e1)));
_mm256_storeu_ps(dst + i + 24,
_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(e1, 8))));
#endif
}
#endif
for (; i < n; ++i) {
uint8_t b = src[i >> 1];
uint8_t nb = (i & 1) ? (uint8_t)(b >> 4) : (uint8_t)(b & 0xf);
dst[i] = (float)((int)(nb ^ 0x8u) - 8);
}
}
static void w2_to_f32(const uint8_t* src, float* dst, int64_t n) {
for (int64_t i = 0; i < n; ++i) {
uint8_t b = src[i >> 2];
uint8_t c = (uint8_t)((b >> (2 * (i & 3))) & 0x3u);
dst[i] = (float)((int)(c ^ 0x2u) - 2);
}
}
static void mxfp4_to_f32(const uint8_t* src, float* dst, int64_t n) {
for (int64_t i = 0; i < n; ++i) {
uint8_t b = src[i >> 1];
uint8_t nb = (i & 1) ? (uint8_t)(b >> 4) : (uint8_t)(b & 0xf);
float v = kMxfp4Mag[nb & 7u];
dst[i] = (nb & 8u) ? -v : v;
}
}
/* ================================================================== the generic row */
void row_to_f32(uint32_t dt, const void* src, float* dst, int64_t n) {
switch (dt) {
case RAD_F32: std::memcpy(dst, src, (size_t)n * 4); break;
case RAD_BF16: cvt_bf16_to_f32((const uint16_t*)src, dst, n); break;
case RAD_F16: cvt_f16_to_f32((const uint16_t*)src, dst, n); break;
case RAD_F8E4M3: cvt_fp8e4m3_to_f32((const uint8_t*)src, dst, n); break;
case RAD_F8E5M2: cvt_fp8e5m2_to_f32((const uint8_t*)src, dst, n); break;
case RAD_I8: cvt_i8_to_f32((const int8_t*)src, dst, n); break;
case RAD_I4: w4_to_f32((const uint8_t*)src, dst, n); break;
case RAD_I2: w2_to_f32((const uint8_t*)src, dst, n); break;
case RAD_FP4E2M1: mxfp4_to_f32((const uint8_t*)src, dst, n); break;
default:
/* Everything left is an integer or a bool, none of them hot. The ABI's own accessor is
* the definition and there is nothing to vectorise about a u8 widen nobody runs. */
for (int64_t i = 0; i < n; ++i) dst[i] = rad_load_f32(src, dt, i);
break;
}
}
void row_from_f32(uint32_t dt, const float* src, void* dst, int64_t n) {
switch (dt) {
case RAD_F32: std::memcpy(dst, src, (size_t)n * 4); break;
case RAD_BF16: cvt_f32_to_bf16(src, (uint16_t*)dst, n); break;
case RAD_F16: cvt_f32_to_f16(src, (uint16_t*)dst, n); break;
case RAD_F8E4M3: cvt_f32_to_fp8e4m3(src, (uint8_t*)dst, n); break;
case RAD_F8E5M2: cvt_f32_to_fp8e5m2(src, (uint8_t*)dst, n); break;
case RAD_I8: cvt_f32_to_i8(src, (int8_t*)dst, n); break;
default:
/* Every other integer width rounds and saturates as i8 does (avx_common.h: st_elem). */
for (int64_t i = 0; i < n; ++i) st_elem(dst, dt, i, src[i]);
break;
}
}
void row_to_f32_strided(uint32_t dt, const void* src, int64_t stride, float* dst, int64_t n) {
if (stride == 1) { row_to_f32(dt, src, dst, n); return; }
/* A GATHER, AND IT IS LEFT SCALAR. vpgatherdd issues one cache line per lane where the scalar
* loop's loads coalesce in the load queue, and every strided operand in this plugin is a
* column slice of a fused projection (docs/OPS.md on `z`) -- a handful of rows per launch. Not
* a hot path, and not worth a second code path that would need its own check. */
for (int64_t i = 0; i < n; ++i) dst[i] = ld_elem(src, dt, i * stride);
}
/* ================================================================== row reductions
* FIXED TREES. The accumulator count is written out rather than left to the unroller, because the
* summation order has to be a property of the source and not of the optimiser: a rebuild that
* moved the answer in the last ulp would show up in the checker as a tolerance move and be read as
* whatever change was under test. Four accumulators is what it takes to cover the FMA latency on a modern core
* -- the sweep that says so is `rad-avx-bench --reduce`. */
float row_sumsq(const float* x, int64_t n) {
vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero();
int64_t i = 0;
for (; i + 4 * VF_N <= n; i += 4 * VF_N) {
vf v0 = vf_loadu(x + i), v1 = vf_loadu(x + i + VF_N);
vf v2 = vf_loadu(x + i + 2 * VF_N), v3 = vf_loadu(x + i + 3 * VF_N);
a0 = vf_fma(v0, v0, a0);
a1 = vf_fma(v1, v1, a1);
a2 = vf_fma(v2, v2, a2);
a3 = vf_fma(v3, v3, a3);
}
for (; i + VF_N <= n; i += VF_N) { vf v = vf_loadu(x + i); a0 = vf_fma(v, v, a0); }
float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3)));
for (; i < n; ++i) s += x[i] * x[i];
return s;
}
float row_sum(const float* x, int64_t n) {
vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero();
int64_t i = 0;
for (; i + 4 * VF_N <= n; i += 4 * VF_N) {
a0 = vf_add(a0, vf_loadu(x + i));
a1 = vf_add(a1, vf_loadu(x + i + VF_N));
a2 = vf_add(a2, vf_loadu(x + i + 2 * VF_N));
a3 = vf_add(a3, vf_loadu(x + i + 3 * VF_N));
}
for (; i + VF_N <= n; i += VF_N) a0 = vf_add(a0, vf_loadu(x + i));
float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3)));
for (; i < n; ++i) s += x[i];
return s;
}
float row_amax(const float* x, int64_t n) {
vf m0 = vf_zero(), m1 = vf_zero();
int64_t i = 0;
for (; i + 2 * VF_N <= n; i += 2 * VF_N) {
m0 = vf_max(m0, vf_abs(vf_loadu(x + i)));
m1 = vf_max(m1, vf_abs(vf_loadu(x + i + VF_N)));
}
for (; i + VF_N <= n; i += VF_N) m0 = vf_max(m0, vf_abs(vf_loadu(x + i)));
float m = vf_hmax(vf_max(m0, m1));
for (; i < n; ++i) { float av = x[i] < 0 ? -x[i] : x[i]; if (av > m) m = av; }
return m;
}
float row_max(const float* x, int64_t n) {
if (n <= 0) return -3.402823466e+38f;
vf m0 = vf_set1(x[0]), m1 = vf_set1(x[0]);
int64_t i = 0;
for (; i + 2 * VF_N <= n; i += 2 * VF_N) {
m0 = vf_max(m0, vf_loadu(x + i));
m1 = vf_max(m1, vf_loadu(x + i + VF_N));
}
for (; i + VF_N <= n; i += VF_N) m0 = vf_max(m0, vf_loadu(x + i));
float m = vf_hmax(vf_max(m0, m1));
for (; i < n; ++i) if (x[i] > m) m = x[i];
return m;
}
/* ================================================================== an operand's row, as f32 */
const float* in_row(const RadTensor* t, int64_t base, int64_t n, float* scr) {
const int64_t st = laststride(t);
if (st == 1) {
/* SUB-BYTE DTYPES AT AN ODD ELEMENT OFFSET are the one case a byte pointer cannot express,
* and they take the slow path rather than being silently truncated: `byte_at` maps element
* 2i and 2i+1 to the same byte, so a W4 row starting at an odd element would read the whole
* row shifted by one nibble -- a permutation, and the kind that produces plausible numbers.
* Every real W4 row starts on a group boundary, so this costs nothing. */
const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1
: (t->dtype == RAD_I2) ? 3 : 0;
if (!sub || (base & sub) == 0) {
const void* p = byte_at(t->data, t->dtype, base);
return row_f32_in(t->dtype, p, scr, n);
}
}
for (int64_t i = 0; i < n; ++i) scr[i] = ldt(t, base + i * st);
return scr;
}
void out_row(const RadTensor* t, int64_t base, int64_t n, const float* src) {
const int64_t st = laststride(t);
if (st == 1) {
const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1
: (t->dtype == RAD_I2) ? 3 : 0;
if (!sub || (base & sub) == 0) {
row_from_f32(t->dtype, src, (void*)byte_at(t->data, t->dtype, base), n);
return;
}
}
for (int64_t i = 0; i < n; ++i) stt(t, base + i * st, src[i]);
}
/* ================================================================== exact top-R
*
* ONE STEP OF AN EXACT SELECTION, descending by value and on a tie by the LOWER index. libref's
* `topk_next` is the definition and this is the vectorised reading of it.
*
* THE ELIGIBILITY TEST SPLITS AT THE PREVIOUS PICK, and that is what makes it vectorisable at all.
* The rule is "skip anything above the last pick, and skip the last pick itself and everything
* before it that equals it" -- which reads as an index comparison and is not a lane predicate. But
* it is equivalent to two PURE VALUE tests over two ranges:
*
* i <= pi eligible iff !(v > pv) and v != pv
* i > pi eligible iff !(v > pv)
*
* so each range is one compare and one blend, and the maximum over them is a vector max. Recovering
* WHICH index held that maximum is a second pass that early-exits at the first match -- on real
* data it reads a fraction of the row. libref does one scalar pass with two unpredictable branches
* per element; at a 248K vocabulary and R = 16 that is eight million of them.
*
* `!(v > pv)` RATHER THAN `v <= pv` IS DELIBERATE and is why the comparisons below are the
* unordered NGT form: for a NaN both are different answers, and libref's `if (v > *pv) continue;`
* treats a NaN as eligible. Matching it costs nothing here.
*
* WHAT DOES NOT MATCH, stated rather than hidden: libref seeds its running best with the FIRST
* eligible element and only replaces it on a strict `>`, so an eligible NaN encountered first stays
* the winner for the whole row. A vector max cannot reproduce that, and this returns the largest
* non-NaN instead. Both are arbitrary -- a NaN logit has no correct selection -- and no path in
* this project produces one (a masked logit is -inf, which IS ordered and IS handled). */
bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) {
const float prev = *pv;
const int64_t pidx = *pi;
#if AVX_LEVEL == 0
/* ONE PASS AT THE SCALAR LEVEL, WHICH IS libref's LOOP. The two-pass form below -- a vector
* maximum and then a scan for the index that held it -- pays only because the first pass is
* vector work; with a vector of one float it is strictly two passes where libref does one, and
* it measures slower than the reference it is meant to replace. A fallback that loses to the
* thing it falls back from is not a fallback, so the scalar level gets its own loop. */
float best = 0.0f;
int64_t bi = -1;
for (int64_t j = 0; j < n; ++j) {
const float x = v[j];
if (x > prev) continue;
if (x == prev && j <= pidx) continue;
if (bi < 0 || x > best) { best = x; bi = j; }
}
if (bi < 0) return false;
*pv = best;
*pi = bi;
return true;
#else
const float NEG = -INFINITY;
/* The split point: indices at or below `pidx` must also differ from `prev`. */
const int64_t split = (pidx + 1 > 0) ? (pidx + 1 < n ? pidx + 1 : n) : 0;
float best = NEG;
int64_t i = 0;
{
const vf vprev = vf_set1(prev), vneg = vf_set1(NEG);
vf acc = vf_set1(NEG);
/* Range one: below or at the previous pick -- equality is excluded here. */
for (; i + VF_N <= split; i += VF_N) {
const vf x = vf_loadu(v + i);
#if AVX_LEVEL == 3
const __mmask16 ok = _kand_mask16(_mm512_cmp_ps_mask(x, vprev, _CMP_NGT_UQ),
_mm512_cmp_ps_mask(x, vprev, _CMP_NEQ_UQ));
acc = vf_max(acc, _mm512_mask_blend_ps(ok, vneg, x));
#else
const __m256 ok = _mm256_and_ps(_mm256_cmp_ps(x, vprev, _CMP_NGT_UQ),
_mm256_cmp_ps(x, vprev, _CMP_NEQ_UQ));
acc = vf_max(acc, _mm256_blendv_ps(vneg, x, ok));
#endif
}
for (; i < split; ++i) {
const float x = v[i];
if (x > prev || x == prev) continue;
if (x > best) best = x;
}
/* Range two: past the previous pick -- equality is allowed. */
for (; i + VF_N <= n; i += VF_N) {
const vf x = vf_loadu(v + i);
#if AVX_LEVEL == 3
const __mmask16 ok = _mm512_cmp_ps_mask(x, vprev, _CMP_NGT_UQ);
acc = vf_max(acc, _mm512_mask_blend_ps(ok, vneg, x));
#else
const __m256 ok = _mm256_cmp_ps(x, vprev, _CMP_NGT_UQ);
acc = vf_max(acc, _mm256_blendv_ps(vneg, x, ok));
#endif
}
const float vm = vf_hmax(acc);
if (vm > best) best = vm;
}
for (; i < n; ++i) {
const float x = v[i];
if (x > prev) continue;
if (x == prev && i <= pidx) continue;
if (x > best) best = x;
}
/* THE LOWEST INDEX HOLDING THAT MAXIMUM -- "ties to the lower column" -- AND THIS PASS IS
* VECTORISED TOO, because it costs as much as the maximum does when it is not.
*
* The maximum can sit anywhere in the row, so a scalar scan for it reads n/2 elements on
* average: over a 32000-logit row that is sixteen thousand unpredictable compares, and it
* dominates `sample_argmax`. Comparing a whole vector against `best` and taking the lowest set
* bit of the mask turns that into n/2/VF_N iterations.
*
* THE LOW RANGE IS SCANNED FIRST AND THAT IS NOT A DETAIL. "Lowest index" means lowest over the
* WHOLE row, so a match below the previous pick beats one above it -- and scanning the long
* vector range first and only then the short scalar one returns the wrong index exactly when
* the maximum occurs twice, once on each side. That failure only bites on ties: it does not
* show at f32 or at the scalar level, and it shows at bf16, where a narrow row quantised to a
* handful of distinct values makes a repeated maximum common.
*
* Below the previous pick the extra `x != prev` test applies, and that range is at most pidx+1
* long -- zero for an argmax, R-1 for the R-th selection -- so it stays scalar. Past it,
* eligibility is exactly `!(x > prev)` and `x == best` already implies it, since `best` was
* drawn from eligible lanes and is therefore <= prev. */
for (int64_t j = 0; j < split; ++j) {
const float x = v[j];
if (x != best || x == prev) continue;
*pv = best;
*pi = j;
return true;
}
{
int64_t j = split;
const vf vbest = vf_set1(best);
for (; j + VF_N <= n; j += VF_N) {
const vf x = vf_loadu(v + j);
#if AVX_LEVEL == 3
const unsigned msk = (unsigned)_mm512_cmpeq_ps_mask(x, vbest);
#else
const unsigned msk =
(unsigned)_mm256_movemask_ps(_mm256_cmp_ps(x, vbest, _CMP_EQ_OQ));
#endif
if (msk) { *pv = best; *pi = j + __builtin_ctz(msk); return true; }
}
for (; j < n; ++j)
if (v[j] == best) { *pv = best; *pi = j; return true; }
}
return false;
#endif
}
} /* inline namespace */
} /* namespace avx */
/* ================================================================== the machine's FMA ceiling
*
* THE CEILING HAS TO BE MEASURED WITH THE FLAGS THE KERNELS ARE COMPILED WITH, which is why this
* lives here -- in a file compiled once per ISA level -- and not in rad-avx-bench, which is
* baseline-compiled like the dispatcher and can only ever emit SSE2. A bench that reported the
* scalar chain as "the machine's peak" would be reporting something ten times below what a GEMM
* at this level is up against, and every kernel would look like it was doing well.
*
* WHAT IT MEASURES: a dependency-free chain of independent FMA accumulators, all in registers,
* nothing touching memory. What comes out is what the machine RETIRES, including whatever clock it
* actually holds under a sustained vector load -- which on a part with an AVX-512 frequency offset
* is not the advertised boost, and is exactly the number a kernel is competing with.
*
* THE ACCUMULATOR COUNT IS THE REGISTER FILE, and getting it wrong understates the ceiling rather
* than overstating it -- which is worse, because every kernel then looks good against it. Sixteen
* accumulators plus the two constants is EIGHTEEN live vectors, which fits AVX-512's 32 registers
* and spills on AVX2's and AVX's 16. With sixteen everywhere the AVX2 peak comes out barely above
* the AVX one -- a step of a few percent for turning two instructions into one, where the ports
* say 2x -- because the spill is inside the loop. Ten accumulators covers a 4-5 cycle FMA latency
* against 2 FMA ports with room to spare and leaves six registers free.
*
* `volatile` on the sink, so the whole loop is not deleted. The accumulators are read out through
* it; without that the compiler is entirely within its rights to remove the work and report an
* infinite ceiling, which is the classic way this measurement is wrong. */
extern "C" double AVX_FN(avx_peak_fma)(int64_t iters) {
using namespace avx;
#if AVX_LEVEL == 1 || AVX_LEVEL == 2
enum { NACC = 10 }; /* 16 architectural YMM registers */
#else
enum { NACC = 16 }; /* 32 ZMM at AVX-512; scalar has no such limit */
#endif
vf acc[NACC];
for (int i = 0; i < NACC; ++i) acc[i] = vf_set1((float)(i + 1) * 1e-6f);
const vf m = vf_set1(1.0000001f), b = vf_set1(1e-7f);
for (int64_t it = 0; it < iters; ++it)
for (int i = 0; i < NACC; ++i) acc[i] = vf_fma(acc[i], m, b);
float sink = 0;
for (int i = 0; i < NACC; ++i) sink += vf_hsum(acc[i]);
volatile float keep = sink;
(void)keep;
/* 2 flops an FMA, NACC of them an iteration, VF_N lanes each. */
return 2.0 * (double)iters * (double)NACC * (double)VF_N;
}
+25
View File
@@ -0,0 +1,25 @@
/* avx_table.cpp -- one ISA level's table of kernel entry points, compiled once per level.
*
* There is nothing to read here and that is the point. The table is generated from AVX_OP_LIST in
* avx_isa.h, so the member order and the initialiser order are the SAME MACRO EXPANSION and cannot
* drift: a table whose members were typed out twice is a table where `silu` and `sigmoid` end up
* swapped one day, and the symptom of that is a model that produces fluent wrong text rather than
* a failure anything reports. The declarations come from the same list too, so an op added to
* AVX_OP_LIST without an implementation at every level is a LINK error naming the missing symbol
* and the level it is missing from -- which is the diagnostic you want, four times over.
*/
#include "avx_vec.h"
#include "avx_isa.h"
/* Every kernel at this level, declared. AVX_FN pastes the level's suffix on. */
#define AVX_DECL(nm) extern "C" int AVX_FN(avx_##nm)(const RadArgs*, RadStream);
AVX_OP_LIST(AVX_DECL)
#undef AVX_DECL
#define AVX_ENTRY(nm) AVX_FN(avx_##nm),
extern "C" const AvxKernelTable AVX_FN(avx_table) = {
AVX_OP_LIST(AVX_ENTRY)
};
#undef AVX_ENTRY
+862
View File
@@ -0,0 +1,862 @@
/* avx_vec.h -- the vector abstraction every kernel in this plugin is written against, and the
* dtype conversions that feed it.
*
* THIS HEADER IS COMPILED FOUR TIMES, once per ISA level, with AVX_LEVEL defined on the command
* line and the matching -m flags on the object. Nothing in here is selected at runtime: by the
* time this is preprocessed the level is a constant, so `vf` is one concrete type and every
* operation below is one instruction or a short fixed sequence. The runtime choice happens once,
* in avx_dispatch.cpp, between whole tables of already-compiled functions.
*
* ============================== WHY AN ABSTRACTION AND NOT FOUR COPIES ==============================
*
* Four hand-written copies of seventy-five kernels is three hundred implementations
* to keep in agreement, and they would not stay in agreement -- the levels whatever machine you
* develop on cannot execute are the ones that rot, and they are the levels the plugin exists for.
* Written once against `vf`, the AVX-512 path is THE SAME ALGORITHM as the scalar path and the
* checker's job is to prove the arithmetic agrees, not to re-derive the op.
*
* The cost is real and is stated rather than hidden: an abstraction cannot express the things that
* differ in KIND between levels -- AVX-512's write masks, its 32 registers, its compress/expand.
* So where one of those is the whole point, the kernel writes an `#if AVX_LEVEL >= 3` block and
* says why in a comment next to it. That is a handful of places (the GEMM microkernel's register
* blocking, top-k's compress), not the general case.
*
* ============================== EVERYTHING COMPUTES IN f32 ==============================
*
* libref's contract is f32 accumulation with IEEE RTNE narrowing (libref/ref_common.h) and this
* plugin is checked against it, so f32 is the working type here too. Operands arrive as bf16, f16,
* fp8 or i8; the rule is CONVERT A WHOLE ROW ONCE into an f32 scratch, compute, convert back. Not
* per element, which is what libref does and what makes it slow: a per-element dtype switch inside
* the inner loop is a branch the vectoriser cannot cross. The size of that effect is measured per
* op by rad-avx-bench and recorded in each kernel's own header, not guessed at here.
*
* WHAT THIS PLUGIN DOES NOT PROMISE, and libref does: no reassociation and no FMA. Both are given
* up deliberately and both are why the tolerances in avx_check.cpp are the kbench ones rather than
* zero. A vector reduction sums in a different order by construction -- that IS the vectorisation
* -- and refusing FMA would throw away half the machine's flops. The narrowing conversions are the
* part that must be bit-exact, because they define what a result IS, and they are (see below).
*/
#ifndef RAD_AVX_VEC_H
#define RAD_AVX_VEC_H
#ifndef AVX_LEVEL
#error "AVX_LEVEL must be defined on the command line: 0 scalar, 1 avx, 2 avx2, 3 avx512"
#endif
#include "rad_abi.h"
#include "rad_plugin.h"
#include <cstdint>
#include <cstring>
#include <cmath>
#if AVX_LEVEL >= 1
#include <immintrin.h>
#endif
/* The symbol suffix for this level. Every kernel defines avx_<op>_<suffix>. */
#if AVX_LEVEL == 0
#define AVX_SUFFIX sc
#define AVX_LEVEL_NAME "scalar"
#elif AVX_LEVEL == 1
#define AVX_SUFFIX v1
#define AVX_LEVEL_NAME "avx"
#elif AVX_LEVEL == 2
#define AVX_SUFFIX v2
#define AVX_LEVEL_NAME "avx2"
#elif AVX_LEVEL == 3
#define AVX_SUFFIX v3
#define AVX_LEVEL_NAME "avx512"
#else
#error "AVX_LEVEL out of range"
#endif
#define AVX_CAT2(a, b) a##_##b
#define AVX_CAT(a, b) AVX_CAT2(a, b)
/* avx_rmsnorm -> avx_rmsnorm_v2 at AVX_LEVEL 2. */
#define AVX_FN(name) AVX_CAT(name, AVX_SUFFIX)
/* The header of every kernel in this plugin. `a` is the RadArgs and `stream` the RadStream, which
* a host kernel ignores -- the house rule is that every entry point is (const RadArgs*, RadStream)
* whatever domain it runs in (libr4d/r4d_plugin.h), and a host plugin that dropped the second
* parameter would not be substitutable for a device one. */
#define AVX_KERNEL(nm) \
extern "C" int AVX_FN(avx_##nm)(const RadArgs* a, [[maybe_unused]] RadStream stream)
namespace avx {
/* EVERY LEVEL GETS ITS OWN NAMESPACE, and it is an `inline` one so that a kernel writes `avx::vf`
* without knowing which level it is being compiled at. Without this the four objects would define
* four `avx::row_to_f32` symbols and the link would pick one of them for all four tables -- which
* is not a link error, it is an AVX-512 helper silently running inside the scalar path, and on a
* machine without AVX-512 that is a SIGILL from the fallback that exists to prevent SIGILLs. */
inline namespace AVX_SUFFIX {
/* ================================================================== the vector type */
#if AVX_LEVEL == 0
typedef float vf;
enum { VF_N = 1 };
static inline vf vf_zero() { return 0.0f; }
static inline vf vf_set1(float x) { return x; }
static inline vf vf_load(const float* p) { return *p; }
static inline vf vf_loadu(const float* p) { return *p; }
static inline void vf_store(float* p, vf v) { *p = v; }
static inline void vf_storeu(float* p, vf v) { *p = v; }
static inline vf vf_add(vf a, vf b) { return a + b; }
static inline vf vf_sub(vf a, vf b) { return a - b; }
static inline vf vf_mul(vf a, vf b) { return a * b; }
static inline vf vf_div(vf a, vf b) { return a / b; }
static inline vf vf_max(vf a, vf b) { return a > b ? a : b; }
static inline vf vf_min(vf a, vf b) { return a < b ? a : b; }
static inline vf vf_fma(vf a, vf b, vf c) { return a * b + c; }
static inline vf vf_sqrt(vf a) { return std::sqrt(a); }
static inline vf vf_abs(vf a) { return std::fabs(a); }
static inline float vf_hsum(vf a) { return a; }
static inline float vf_hmax(vf a) { return a; }
#elif AVX_LEVEL == 1 || AVX_LEVEL == 2
typedef __m256 vf;
enum { VF_N = 8 };
static inline vf vf_zero() { return _mm256_setzero_ps(); }
static inline vf vf_set1(float x) { return _mm256_set1_ps(x); }
static inline vf vf_load(const float* p) { return _mm256_load_ps(p); }
static inline vf vf_loadu(const float* p) { return _mm256_loadu_ps(p); }
static inline void vf_store(float* p, vf v) { _mm256_store_ps(p, v); }
static inline void vf_storeu(float* p, vf v) { _mm256_storeu_ps(p, v); }
static inline vf vf_add(vf a, vf b) { return _mm256_add_ps(a, b); }
static inline vf vf_sub(vf a, vf b) { return _mm256_sub_ps(a, b); }
static inline vf vf_mul(vf a, vf b) { return _mm256_mul_ps(a, b); }
static inline vf vf_div(vf a, vf b) { return _mm256_div_ps(a, b); }
static inline vf vf_max(vf a, vf b) { return _mm256_max_ps(a, b); }
static inline vf vf_min(vf a, vf b) { return _mm256_min_ps(a, b); }
#if AVX_LEVEL >= 2
static inline vf vf_fma(vf a, vf b, vf c) { return _mm256_fmadd_ps(a, b, c); }
#else
/* AVX HAS NO FMA -- it is a separate feature that arrived with Haswell, and Sandy Bridge is the
* whole reason this level exists. Two roundings here, which makes this level numerically CLOSER
* to libref than AVX2 is, not further. */
static inline vf vf_fma(vf a, vf b, vf c) { return _mm256_add_ps(_mm256_mul_ps(a, b), c); }
#endif
static inline vf vf_sqrt(vf a) { return _mm256_sqrt_ps(a); }
static inline vf vf_abs(vf a) {
return _mm256_and_ps(a, _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff)));
}
static inline float vf_hsum(vf a) {
/* Lane-crossing first, then within the 128. Fixed order, so the answer does not depend on
* which of two equally valid trees the compiler picks. */
__m128 lo = _mm256_castps256_ps128(a);
__m128 hi = _mm256_extractf128_ps(a, 1);
__m128 s = _mm_add_ps(lo, hi);
s = _mm_add_ps(s, _mm_movehl_ps(s, s));
s = _mm_add_ss(s, _mm_shuffle_ps(s, s, 0x55));
return _mm_cvtss_f32(s);
}
static inline float vf_hmax(vf a) {
__m128 lo = _mm256_castps256_ps128(a);
__m128 hi = _mm256_extractf128_ps(a, 1);
__m128 s = _mm_max_ps(lo, hi);
s = _mm_max_ps(s, _mm_movehl_ps(s, s));
s = _mm_max_ss(s, _mm_shuffle_ps(s, s, 0x55));
return _mm_cvtss_f32(s);
}
#else /* AVX_LEVEL == 3 */
typedef __m512 vf;
enum { VF_N = 16 };
static inline vf vf_zero() { return _mm512_setzero_ps(); }
static inline vf vf_set1(float x) { return _mm512_set1_ps(x); }
static inline vf vf_load(const float* p) { return _mm512_load_ps(p); }
static inline vf vf_loadu(const float* p) { return _mm512_loadu_ps(p); }
static inline void vf_store(float* p, vf v) { _mm512_store_ps(p, v); }
static inline void vf_storeu(float* p, vf v) { _mm512_storeu_ps(p, v); }
static inline vf vf_add(vf a, vf b) { return _mm512_add_ps(a, b); }
static inline vf vf_sub(vf a, vf b) { return _mm512_sub_ps(a, b); }
static inline vf vf_mul(vf a, vf b) { return _mm512_mul_ps(a, b); }
static inline vf vf_div(vf a, vf b) { return _mm512_div_ps(a, b); }
static inline vf vf_max(vf a, vf b) { return _mm512_max_ps(a, b); }
static inline vf vf_min(vf a, vf b) { return _mm512_min_ps(a, b); }
static inline vf vf_fma(vf a, vf b, vf c) { return _mm512_fmadd_ps(a, b, c); }
static inline vf vf_sqrt(vf a) { return _mm512_sqrt_ps(a); }
static inline vf vf_abs(vf a) { return _mm512_abs_ps(a); }
static inline float vf_hsum(vf a) { return _mm512_reduce_add_ps(a); }
static inline float vf_hmax(vf a) { return _mm512_reduce_max_ps(a); }
#endif
/* Tail handling. A masked load is the right instruction at AVX-512 and there is no such thing
* below it, so `vf_load_n` is a mask at level 3 and a small stack copy elsewhere. Kernels use it
* only for the RAGGED END of a row: a model width is a multiple of 128 and the tail almost never
* runs, so this is about correctness at odd shapes, not about speed. */
static inline vf vf_load_n(const float* p, int n) {
#if AVX_LEVEL == 3
return _mm512_maskz_loadu_ps((__mmask16)((1u << n) - 1u), p);
#elif AVX_LEVEL == 0
return n > 0 ? *p : 0.0f;
#else
float tmp[VF_N] = { 0 };
for (int i = 0; i < n; ++i) tmp[i] = p[i];
return _mm256_loadu_ps(tmp);
#endif
}
static inline void vf_store_n(float* p, vf v, int n) {
#if AVX_LEVEL == 3
_mm512_mask_storeu_ps(p, (__mmask16)((1u << n) - 1u), v);
#elif AVX_LEVEL == 0
if (n > 0) *p = v;
#else
float tmp[VF_N];
_mm256_storeu_ps(tmp, v);
for (int i = 0; i < n; ++i) p[i] = tmp[i];
#endif
}
/* ================================================================== narrowing conversions
*
* THE BIT-EXACTNESS RULE. rad_plugin.h defines f32->bf16 as RTNE with the tie broken on the
* surviving bit's parity, NaN forced quiet, and overflow allowed to carry into the bf16 infinity.
* That definition IS the result (rad_plugin.h says so at length), and the kbench tolerance for
* `cast` is 1e-6 -- which is to say: exact. So the vector forms below are the SAME INTEGER
* ARITHMETIC, lane for lane, not an approximation of it, and avx_check.cpp checks `cast` over
* every dtype pair against libref at that tolerance to hold them there.
*
* NOT `_mm512_cvtneps_pbh`. Zen 5 has AVX512-BF16 and its convert is also RTNE, but its NaN
* handling is the hardware's rather than the ABI's, and the ABI's is what libref computes. One
* instruction saved against a conversion that is a mask and two integer ops is not worth a
* divergence the checker would have to be loosened to accept.
*/
static inline void cvt_bf16_to_f32(const uint16_t* src, float* dst, int64_t n) {
int64_t i = 0;
#if AVX_LEVEL == 3
for (; i + 16 <= n; i += 16) {
__m256i h = _mm256_loadu_si256((const __m256i*)(src + i));
__m512i w = _mm512_slli_epi32(_mm512_cvtepu16_epi32(h), 16);
_mm512_storeu_ps(dst + i, _mm512_castsi512_ps(w));
}
#elif AVX_LEVEL == 2
for (; i + 8 <= n; i += 8) {
__m128i h = _mm_loadu_si128((const __m128i*)(src + i));
__m256i w = _mm256_slli_epi32(_mm256_cvtepu16_epi32(h), 16);
_mm256_storeu_ps(dst + i, _mm256_castsi256_ps(w));
}
#elif AVX_LEVEL == 1
/* AVX has no 256-bit integer ALU: the shift has to happen in two 128-bit halves and the
* result is glued with vinsertf128, which is a FLOAT-domain instruction and therefore legal
* here. This is the shape every integer helper at this level takes. */
for (; i + 8 <= n; i += 8) {
__m128i h = _mm_loadu_si128((const __m128i*)(src + i));
__m128i lo = _mm_slli_epi32(_mm_cvtepu16_epi32(h), 16);
__m128i hi = _mm_slli_epi32(_mm_cvtepu16_epi32(_mm_srli_si128(h, 8)), 16);
__m256 v = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_castsi128_ps(lo)),
_mm_castsi128_ps(hi), 1);
_mm256_storeu_ps(dst + i, v);
}
#endif
for (; i < n; ++i) dst[i] = rad_bf16_to_f32(src[i]);
}
#if AVX_LEVEL >= 1
/* The RTNE core, on a vector of f32 bit patterns, leaving 16-bit results in the low half of each
* lane. Shared by the three vector levels; the pack differs and the arithmetic does not. */
#if AVX_LEVEL == 3
static inline __m512i bf16_round_bits(__m512 f) {
__m512i u = _mm512_castps_si512(f);
__m512i mag = _mm512_and_si512(u, _mm512_set1_epi32(0x7fffffff));
__mmask16 nan = _mm512_cmpgt_epi32_mask(mag, _mm512_set1_epi32(0x7f800000));
__m512i lsb = _mm512_and_si512(_mm512_srli_epi32(u, 16), _mm512_set1_epi32(1));
__m512i rnd = _mm512_srli_epi32(
_mm512_add_epi32(_mm512_add_epi32(u, _mm512_set1_epi32(0x7fff)), lsb), 16);
__m512i qnan = _mm512_or_si512(_mm512_srli_epi32(u, 16), _mm512_set1_epi32(0x0040));
return _mm512_mask_blend_epi32(nan, rnd, qnan);
}
#elif AVX_LEVEL == 2
static inline __m256i bf16_round_bits(__m256 f) {
__m256i u = _mm256_castps_si256(f);
__m256i mag = _mm256_and_si256(u, _mm256_set1_epi32(0x7fffffff));
__m256i nan = _mm256_cmpgt_epi32(mag, _mm256_set1_epi32(0x7f800000));
__m256i lsb = _mm256_and_si256(_mm256_srli_epi32(u, 16), _mm256_set1_epi32(1));
__m256i rnd = _mm256_srli_epi32(
_mm256_add_epi32(_mm256_add_epi32(u, _mm256_set1_epi32(0x7fff)), lsb), 16);
__m256i qnan = _mm256_or_si256(_mm256_srli_epi32(u, 16), _mm256_set1_epi32(0x0040));
return _mm256_blendv_epi8(rnd, qnan, nan);
}
#else /* AVX_LEVEL == 1 */
static inline __m128i bf16_round_bits128(__m128 f) {
__m128i u = _mm_castps_si128(f);
__m128i mag = _mm_and_si128(u, _mm_set1_epi32(0x7fffffff));
__m128i nan = _mm_cmpgt_epi32(mag, _mm_set1_epi32(0x7f800000));
__m128i lsb = _mm_and_si128(_mm_srli_epi32(u, 16), _mm_set1_epi32(1));
__m128i rnd = _mm_srli_epi32(_mm_add_epi32(_mm_add_epi32(u, _mm_set1_epi32(0x7fff)), lsb), 16);
__m128i qnan = _mm_or_si128(_mm_srli_epi32(u, 16), _mm_set1_epi32(0x0040));
return _mm_blendv_epi8(rnd, qnan, nan);
}
#endif
#endif
static inline void cvt_f32_to_bf16(const float* src, uint16_t* dst, int64_t n) {
int64_t i = 0;
#if AVX_LEVEL == 3
for (; i + 16 <= n; i += 16) {
__m512i w = bf16_round_bits(_mm512_loadu_ps(src + i));
_mm256_storeu_si256((__m256i*)(dst + i), _mm512_cvtepi32_epi16(w));
}
#elif AVX_LEVEL == 2
for (; i + 8 <= n; i += 8) {
__m256i w = bf16_round_bits(_mm256_loadu_ps(src + i));
__m128i lo = _mm256_castsi256_si128(w);
__m128i hi = _mm256_extracti128_si256(w, 1);
/* Every lane is already <= 0xffff, so packus is exact rather than saturating. */
_mm_storeu_si128((__m128i*)(dst + i), _mm_packus_epi32(lo, hi));
}
#elif AVX_LEVEL == 1
for (; i + 8 <= n; i += 8) {
__m256 v = _mm256_loadu_ps(src + i);
__m128i lo = bf16_round_bits128(_mm256_castps256_ps128(v));
__m128i hi = bf16_round_bits128(_mm256_extractf128_ps(v, 1));
_mm_storeu_si128((__m128i*)(dst + i), _mm_packus_epi32(lo, hi));
}
#endif
for (; i < n; ++i) dst[i] = rad_f32_to_bf16(src[i]);
}
/* f16 IS HARDWARE FROM AVX2 UP AND SOFTWARE BELOW IT. F16C is its own CPUID bit and arrived one
* generation after AVX, so the level-1 path cannot use vcvtph2ps and falls through to the ABI's
* software convert. That is the honest thing: a level named `avx` that quietly required F16C
* would fault on the only machines it exists for. F16C's rounding is IEEE RTNE, which is what
* rad_f32_to_f16 computes, so the two agree bit for bit -- checked by `cast` at 1e-6. */
static inline void cvt_f16_to_f32(const uint16_t* src, float* dst, int64_t n) {
int64_t i = 0;
#if AVX_LEVEL == 3
for (; i + 16 <= n; i += 16)
_mm512_storeu_ps(dst + i, _mm512_cvtph_ps(_mm256_loadu_si256((const __m256i*)(src + i))));
#elif AVX_LEVEL == 2
for (; i + 8 <= n; i += 8)
_mm256_storeu_ps(dst + i, _mm256_cvtph_ps(_mm_loadu_si128((const __m128i*)(src + i))));
#endif
for (; i < n; ++i) dst[i] = rad_f16_to_f32(src[i]);
}
static inline void cvt_f32_to_f16(const float* src, uint16_t* dst, int64_t n) {
int64_t i = 0;
#if AVX_LEVEL == 3
for (; i + 16 <= n; i += 16)
_mm256_storeu_si256((__m256i*)(dst + i),
_mm512_cvtps_ph(_mm512_loadu_ps(src + i), _MM_FROUND_TO_NEAREST_INT));
#elif AVX_LEVEL == 2
for (; i + 8 <= n; i += 8)
_mm_storeu_si128((__m128i*)(dst + i),
_mm256_cvtps_ph(_mm256_loadu_ps(src + i), _MM_FROUND_TO_NEAREST_INT));
#endif
for (; i < n; ++i) dst[i] = rad_f32_to_f16(src[i]);
}
/* ---- fp8. THE DECODE IS A 256-ENTRY TABLE AT THE SCALAR LEVEL and a bit reconstruction above it;
* the encode is a masked fast path.
*
* DECODE: every possible byte is one of 256 floats, so the exact answer is a lookup and there is
* nothing to round. The table is built by the ABI's own converter at load (avx_fp8_table_init), so
* it cannot drift from rad_fp8e4m3_to_f32, and it is what the scalar path and every tail element
* read. The vector e4m3 path reconstructs the bits instead, for the reason set out above
* cvt_fp8e4m3_to_f32; e5m2 still gathers from its table.
*
* ENCODE: the bit-exact algorithm has three branches (subnormal, normal, saturate) and vectorising
* all three costs more than it saves. Instead the normal case -- |x| in [2^-6, 448), which is
* every element of a normalised activation -- is done with vector integer arithmetic, and a mask
* of the elements that are NOT in that range drives a scalar fixup through the ABI's converter. On
* real activations the mask is empty and the fixup loop does not run; when it does run the answer
* is the ABI's, which is the definition. */
} /* the tables are at GLOBAL scope with C linkage, deliberately: they are defined once in the
baseline-compiled avx_dispatch.cpp and read by all four levels, so they must NOT pick up the
per-level inline namespace the rest of this header is wrapped in. */
}
extern "C" {
/* NOT `const`, and that is forced: the tables are filled at load by rad_plugin_open from the
ABI's own converters (a typed-out table would be a second definition of the format that can
drift), so the object has to be writable. A const declaration here against a non-const
definition would link -- C linkage does not mangle the type -- and would be a quiet type
mismatch that no tool reports. */
extern float avx_fp8e4m3_tab[256];
extern float avx_fp8e5m2_tab[256];
}
namespace avx {
inline namespace AVX_SUFFIX {
/* THE DECODE IS A BIT RECONSTRUCTION, AND THE TABLE GATHER IS THE NULL RESULT.
*
* The obvious implementation is a 256-entry table -- every byte is one of 256 floats, so the answer
* is a lookup and there is nothing to round -- gathered with vpgatherdd. `rad-avx-bench --cvt` says
* that form LOSES TO THE SCALAR TABLE LOOKUP at both vector levels. A gather issues one cache line
* per lane however small the table is; a 1 KiB table resident in L1 does not make that cheap, it
* just makes it not slower than DRAM. Sixteen lanes of vpgatherdd is sixteen L1 accesses in
* sequence.
*
* The reconstruction below is pure integer arithmetic and no memory at all:
*
* u = (b & 0x7f) << 20 + 120 << 23 puts e in the f32 exponent field (bias 7 -> 127) and m
* in the top three mantissa bits, in one add
* e == 0 is an fp8 SUBNORMAL, where the implicit 1 that f32 just
* supplied is wrong: (f - 2^-7) * 2 removes it and
* rescales, which is exact -- both operands are powers of
* two times a 3-bit mantissa
* mag == 0x7f is the format's ONLY NaN (S1111111); blended in
* sign (b & 0x80) << 24
*
* The reconstruction is worth roughly 2.5x the gather at AVX2 and 3.3x at AVX-512 on that bench,
* and the gather and the scalar table are within a few percent of each other.
*
* The table stays for the scalar path, where it is exact, has no branch, and is what the level is
* for. It also stays because rad_plugin_open builds it from the ABI's own converter, so it remains
* the definition the reconstruction above is checked against.
*
* WHAT IS NOT CLAIMED: that avoiding memory is obviously faster. Both forms are measured rather
* than argued, and the checker proves the answer is identical over all 256 input bytes, NaN and
* subnormals included, which a draw of normals never would. */
static inline void cvt_fp8e4m3_to_f32(const uint8_t* src, float* dst, int64_t n) {
int64_t i = 0;
#if AVX_LEVEL == 3
const __m512i c7f = _mm512_set1_epi32(0x7f);
const __m512i cbias = _mm512_set1_epi32(120 << 23);
const __m512 chalf = _mm512_set1_ps(0.0078125f); /* 2^-7 */
const __m512 cnan = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fc00000));
for (; i + 16 <= n; i += 16) {
const __m512i b = _mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*)(src + i)));
const __m512i mag = _mm512_and_si512(b, c7f);
const __m512i u = _mm512_add_epi32(_mm512_slli_epi32(mag, 20), cbias);
__m512 f = _mm512_castsi512_ps(u);
const __mmask16 sub = _mm512_cmplt_epi32_mask(mag, _mm512_set1_epi32(8));
f = _mm512_mask_blend_ps(sub, f,
_mm512_mul_ps(_mm512_sub_ps(f, chalf), _mm512_set1_ps(2.0f)));
f = _mm512_mask_blend_ps(_mm512_cmpeq_epi32_mask(mag, c7f), f, cnan);
const __m512i sign = _mm512_slli_epi32(_mm512_and_si512(b, _mm512_set1_epi32(0x80)), 24);
_mm512_storeu_ps(dst + i, _mm512_castsi512_ps(
_mm512_or_si512(_mm512_castps_si512(f), sign)));
}
#elif AVX_LEVEL == 2
const __m256i c7f = _mm256_set1_epi32(0x7f);
const __m256i cbias = _mm256_set1_epi32(120 << 23);
const __m256 chalf = _mm256_set1_ps(0.0078125f);
const __m256 cnan = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fc00000));
for (; i + 8 <= n; i += 8) {
const __m256i b = _mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*)(src + i)));
const __m256i mag = _mm256_and_si256(b, c7f);
const __m256i u = _mm256_add_epi32(_mm256_slli_epi32(mag, 20), cbias);
__m256 f = _mm256_castsi256_ps(u);
const __m256i sub = _mm256_cmpgt_epi32(_mm256_set1_epi32(8), mag);
f = _mm256_blendv_ps(f, _mm256_mul_ps(_mm256_sub_ps(f, chalf), _mm256_set1_ps(2.0f)),
_mm256_castsi256_ps(sub));
f = _mm256_blendv_ps(f, cnan, _mm256_castsi256_ps(_mm256_cmpeq_epi32(mag, c7f)));
const __m256i sign = _mm256_slli_epi32(_mm256_and_si256(b, _mm256_set1_epi32(0x80)), 24);
_mm256_storeu_ps(dst + i, _mm256_castsi256_ps(
_mm256_or_si256(_mm256_castps_si256(f), sign)));
}
#endif
for (; i < n; ++i) dst[i] = avx_fp8e4m3_tab[src[i]];
}
static inline void cvt_fp8e5m2_to_f32(const uint8_t* src, float* dst, int64_t n) {
int64_t i = 0;
#if AVX_LEVEL == 3
for (; i + 16 <= n; i += 16) {
__m512i i32 = _mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*)(src + i)));
_mm512_storeu_ps(dst + i, _mm512_i32gather_ps(i32, avx_fp8e5m2_tab, 4));
}
#elif AVX_LEVEL == 2
for (; i + 8 <= n; i += 8) {
__m256i i32 = _mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*)(src + i)));
_mm256_storeu_ps(dst + i, _mm256_i32gather_ps(avx_fp8e5m2_tab, i32, 4));
}
#endif
for (; i < n; ++i) dst[i] = avx_fp8e5m2_tab[src[i]];
}
static inline void cvt_f32_to_fp8e4m3(const float* src, uint8_t* dst, int64_t n) {
int64_t i = 0;
#if AVX_LEVEL == 3
/* q = ((e+7) << 3) | rtne(mantissa >> 20), valid while 2^-6 <= |x| < 448 and x is finite.
* Anything else takes the scalar fixup below.
*
* THE LOWER BOUND IS 2^-6 AND NOTHING ELSE. e4m3's smallest NORMAL is 2^-6; below it the
* format is subnormal and the mantissa has to be renormalised with a variable shift, which is
* the branch this fast path exists to avoid. A bound set any lower lets fp8-subnormal
* magnitudes through the normal path, where they produce an exponent field of zero or below
* and an answer that is wrong by orders of magnitude. The bound is written as its float bit
* pattern with the value beside it so the next reader can check it rather than trust it. */
const __m512i c_lo = _mm512_set1_epi32(0x3c800000); /* 2^-6, the smallest e4m3 normal */
const __m512i c_hi = _mm512_set1_epi32(0x43e00000); /* 448, the largest e4m3 finite */
for (; i + 16 <= n; i += 16) {
__m512 f = _mm512_loadu_ps(src + i);
__m512i u = _mm512_castps_si512(f);
__m512i mag = _mm512_and_si512(u, _mm512_set1_epi32(0x7fffffff));
__mmask16 fast = _kand_mask16(_mm512_cmpge_epi32_mask(mag, c_lo),
_mm512_cmplt_epi32_mask(mag, c_hi));
__m512i sign = _mm512_srli_epi32(_mm512_and_si512(u, _mm512_set1_epi32(0x80000000u)), 24);
/* RTNE on the 20 bits below the kept mantissa: add half, plus one more when the surviving
* bit is odd -- the same tie rule as bf16, one field down. The exponent field rides along
* in the same add, so a mantissa carry increments it for free. */
__m512i lsb = _mm512_and_si512(_mm512_srli_epi32(mag, 20), _mm512_set1_epi32(1));
__m512i r = _mm512_add_epi32(_mm512_add_epi32(mag, _mm512_set1_epi32(0x7ffff)), lsb);
__m512i e = _mm512_sub_epi32(_mm512_srli_epi32(r, 23), _mm512_set1_epi32(127 - 7));
__m512i m = _mm512_and_si512(_mm512_srli_epi32(r, 20), _mm512_set1_epi32(7));
__m512i q = _mm512_or_si512(sign, _mm512_or_si512(_mm512_slli_epi32(e, 3), m));
/* A carry out of the top mantissa bit can push e past 15, and (e, m) = (15, 7) is the
* format's only NaN encoding rather than a number. Neither can be produced by an input
* strictly below 448, but the guard costs one compare and the alternative is a silent NaN
* in a weight: elements that reach either drop into the fixup, which saturates. */
__mmask16 ovf = _kor_mask16(
_mm512_cmpgt_epi32_mask(e, _mm512_set1_epi32(15)),
_kand_mask16(_mm512_cmpeq_epi32_mask(e, _mm512_set1_epi32(15)),
_mm512_cmpeq_epi32_mask(m, _mm512_set1_epi32(7))));
fast = _kandn_mask16(ovf, fast);
/* THE ALL-FAST CASE IS THE WHOLE POINT AND IT GETS ITS OWN EXIT. Every element of a
* normalised activation is in [2^-6, 448), so `fast` is 0xffff on essentially every vector
* a model produces, and the answer is one narrowing store of sixteen bytes.
*
* Without this exit the sixteen lanes spill to a stack array and a scalar loop tests one
* mask bit per element -- a loop that then runs on exactly the path the vector arithmetic
* was written to avoid, and dominates the op. A "fast path" whose epilogue is a
* per-element branch is not a fast path. */
if (fast == (__mmask16)0xffff) {
_mm_storeu_si128((__m128i*)(dst + i), _mm512_cvtepi32_epi8(q));
continue;
}
alignas(64) int32_t tmp[16];
_mm512_store_si512((__m512i*)tmp, q);
for (int k = 0; k < 16; ++k)
dst[i + k] = (fast >> k) & 1 ? (uint8_t)tmp[k] : rad_f32_to_fp8e4m3(src[i + k]);
}
#elif AVX_LEVEL == 2
/* THE SAME ARITHMETIC AT 256 BITS, and it exists because without it AVX2 falls all the way
* through to the ABI's scalar converter: an order of magnitude slower than the AVX-512 body,
* not the 2x its width would suggest. AVX2 is the level most machines in the world run, so a
* gap there is not a rounding error in the coverage.
*
* The mask is a movemask rather than a k-register, and the all-fast exit is the same: eight
* lanes narrowed to eight bytes with two packs. */
for (; i + 8 <= n; i += 8) {
__m256 f = _mm256_loadu_ps(src + i);
__m256i u = _mm256_castps_si256(f);
__m256i mag = _mm256_and_si256(u, _mm256_set1_epi32(0x7fffffff));
const __m256i c_lo = _mm256_set1_epi32(0x3c800000); /* 2^-6 */
const __m256i c_hi = _mm256_set1_epi32(0x43e00000); /* 448 */
/* cmpgt is the only signed compare AVX2 has, so `mag >= c_lo` is written as
* `!(c_lo > mag)` and `mag < c_hi` as `c_hi > mag`. Both operands are non-negative. */
__m256i ge = _mm256_andnot_si256(_mm256_cmpgt_epi32(c_lo, mag),
_mm256_cmpgt_epi32(c_hi, mag));
__m256i sign = _mm256_srli_epi32(_mm256_and_si256(u, _mm256_set1_epi32(0x80000000u)), 24);
__m256i lsb = _mm256_and_si256(_mm256_srli_epi32(mag, 20), _mm256_set1_epi32(1));
__m256i r = _mm256_add_epi32(_mm256_add_epi32(mag, _mm256_set1_epi32(0x7ffff)), lsb);
__m256i e = _mm256_sub_epi32(_mm256_srli_epi32(r, 23), _mm256_set1_epi32(127 - 7));
__m256i m = _mm256_and_si256(_mm256_srli_epi32(r, 20), _mm256_set1_epi32(7));
__m256i q = _mm256_or_si256(sign, _mm256_or_si256(_mm256_slli_epi32(e, 3), m));
__m256i ovf = _mm256_or_si256(
_mm256_cmpgt_epi32(e, _mm256_set1_epi32(15)),
_mm256_and_si256(_mm256_cmpeq_epi32(e, _mm256_set1_epi32(15)),
_mm256_cmpeq_epi32(m, _mm256_set1_epi32(7))));
ge = _mm256_andnot_si256(ovf, ge);
const int fast = _mm256_movemask_ps(_mm256_castsi256_ps(ge));
if (fast == 0xff) {
__m128i p = _mm_packus_epi32(_mm256_castsi256_si128(q),
_mm256_extracti128_si256(q, 1));
p = _mm_packus_epi16(p, p);
_mm_storel_epi64((__m128i*)(dst + i), p);
continue;
}
alignas(32) int32_t tmp[8];
_mm256_store_si256((__m256i*)tmp, q);
for (int k = 0; k < 8; ++k)
dst[i + k] = (fast >> k) & 1 ? (uint8_t)tmp[k] : rad_f32_to_fp8e4m3(src[i + k]);
}
#endif
for (; i < n; ++i) dst[i] = rad_f32_to_fp8e4m3(src[i]);
}
static inline void cvt_f32_to_fp8e5m2(const float* src, uint8_t* dst, int64_t n) {
for (int64_t i = 0; i < n; ++i) dst[i] = rad_f32_to_fp8e5m2(src[i]);
}
/* ---- int8. `_mm*_cvtps_epi32` rounds under MXCSR, which is round-to-nearest-even unless a
* caller has changed it -- the same rule `std::nearbyintf` follows, which is what libref uses.
*
* THE CLAMP IS TAKEN IN FLOAT, BEFORE THE CONVERSION, and the saturating packs are not a
* substitute for it: a value past the int32 range and +inf both convert to 0x80000000, the
* "integer indefinite", which the packs then saturate to -128 -- the opposite end of the range.
* Clamping to [-128, 127] first and rounding second lands where libref's round-then-clamp does for
* every input, the .5 ties at the ends included, so this stays bit-exact against the reference and
* `quant_act` can be held at 1e-6. A NaN stores 0, which is also what the scalar tail does. */
#if AVX_LEVEL == 3
static inline __m512 i8_range_ps(__m512 x) {
const __mmask16 ord = _mm512_cmp_ps_mask(x, x, _CMP_ORD_Q);
x = _mm512_min_ps(_mm512_max_ps(x, _mm512_set1_ps(-128.0f)), _mm512_set1_ps(127.0f));
return _mm512_maskz_mov_ps(ord, x);
}
#elif AVX_LEVEL == 2
static inline __m256 i8_range_ps(__m256 x) {
const __m256 ord = _mm256_cmp_ps(x, x, _CMP_ORD_Q);
x = _mm256_min_ps(_mm256_max_ps(x, _mm256_set1_ps(-128.0f)), _mm256_set1_ps(127.0f));
return _mm256_and_ps(x, ord);
}
#endif
static inline int8_t i8_round_sat(float v) {
if (std::isnan(v)) return 0;
const float r = std::nearbyintf(v);
return (int8_t)(r < -128.f ? -128.f : (r > 127.f ? 127.f : r));
}
static inline void cvt_f32_to_i8(const float* src, int8_t* dst, int64_t n) {
int64_t i = 0;
#if AVX_LEVEL == 3
for (; i + 16 <= n; i += 16) {
__m512i q = _mm512_cvtps_epi32(i8_range_ps(_mm512_loadu_ps(src + i)));
_mm_storeu_si128((__m128i*)(dst + i), _mm512_cvtsepi32_epi8(q));
}
#elif AVX_LEVEL == 2
for (; i + 8 <= n; i += 8) {
__m256i q = _mm256_cvtps_epi32(i8_range_ps(_mm256_loadu_ps(src + i)));
__m128i p = _mm_packs_epi32(_mm256_castsi256_si128(q), _mm256_extracti128_si256(q, 1));
p = _mm_packs_epi16(p, p);
_mm_storel_epi64((__m128i*)(dst + i), p);
}
#endif
for (; i < n; ++i) dst[i] = i8_round_sat(src[i]);
}
/* Fused scale + int8-encode for the quant_act_i8 family: t = src*inv computed in a register
* feeds the same cvtps/packs sequence the split form uses (MXCSR round-to-nearest-even,
* saturating packs -- exactly libref's nearbyintf-and-clamp, bit for bit), so the bytes match
* the scale-then-store form while a full f32 write + read of the row disappears. Kept to the
* int8 family: the fp8 encode's bit-twiddle is a long integer chain and folding the scale into
* it measures slower, where this one measures a few percent faster -- the same traffic saved,
* the opposite instruction-level trade. */
static inline void cvt_scaled_f32_to_i8(const float* src, float inv, int8_t* dst, int64_t n) {
int64_t i = 0;
#if AVX_LEVEL == 3
const __m512 vinv = _mm512_set1_ps(inv);
for (; i + 16 <= n; i += 16) {
__m512 t = _mm512_mul_ps(_mm512_loadu_ps(src + i), vinv);
__m512i q = _mm512_cvtps_epi32(i8_range_ps(t));
_mm_storeu_si128((__m128i*)(dst + i), _mm512_cvtsepi32_epi8(q));
}
#elif AVX_LEVEL == 2
const __m256 vinv = _mm256_set1_ps(inv);
for (; i + 8 <= n; i += 8) {
__m256 t = _mm256_mul_ps(_mm256_loadu_ps(src + i), vinv);
__m256i q = _mm256_cvtps_epi32(i8_range_ps(t));
__m128i p = _mm_packs_epi32(_mm256_castsi256_si128(q), _mm256_extracti128_si256(q, 1));
p = _mm_packs_epi16(p, p);
_mm_storel_epi64((__m128i*)(dst + i), p);
}
#endif
for (; i < n; ++i) dst[i] = i8_round_sat(src[i] * inv);
}
static inline void cvt_i8_to_f32(const int8_t* src, float* dst, int64_t n) {
int64_t i = 0;
#if AVX_LEVEL == 3
for (; i + 16 <= n; i += 16)
_mm512_storeu_ps(dst + i,
_mm512_cvtepi32_ps(_mm512_cvtepi8_epi32(
_mm_loadu_si128((const __m128i*)(src + i)))));
#elif AVX_LEVEL == 2
for (; i + 8 <= n; i += 8)
_mm256_storeu_ps(dst + i,
_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(
_mm_loadl_epi64((const __m128i*)(src + i)))));
#endif
for (; i < n; ++i) dst[i] = (float)src[i];
}
/* ================================================================== the dtype-generic row
*
* ONE SWITCH PER ROW, NOT PER ELEMENT. This is the single most valuable thing in this header:
* libref's inner loops call ld_dt(), which is a switch on every element, and hoisting it to the
* row is most of the speedup on every memory-bound op before a single vector instruction is
* issued. The f32 case is a memcpy the caller can skip entirely -- see row_f32_in below.
*
* W4 / W2 / MXFP4 are the packed WEIGHT codes and are decoded here too, because `dequant` and the
* quantised GEMMs both need them and the unpack is the same nibble arithmetic in both. They are
* raw CODES: the group scale belongs to the caller, which is the only component that knows where
* the scale stream is (libref/ref_common.h makes the same split). */
void row_to_f32 (uint32_t dt, const void* src, float* dst, int64_t n);
void row_from_f32(uint32_t dt, const float* src, void* dst, int64_t n);
/* The strided form: element i of the row is at src[i * stride]. A separate function because the
* contiguous one is the case that matters and a stride parameter in it would cost a multiply per
* element on the path that does not need one. */
void row_to_f32_strided(uint32_t dt, const void* src, int64_t stride, float* dst, int64_t n);
/* When the source is already f32, hand back the pointer instead of copying. Returns `src` for
* RAD_F32 and `scratch` (filled) otherwise, so a kernel reads:
* const float* x = avx::row_f32_in(dt, p, scratch, n);
* and pays nothing at all on the f32 path. */
static inline const float* row_f32_in(uint32_t dt, const void* src, float* scratch, int64_t n) {
if (dt == RAD_F32) return (const float*)src;
row_to_f32(dt, src, scratch, n);
return scratch;
}
/* ================================================================== math
*
* exp AND THE SIGMOID IT FEEDS. Every softmax, every gate and every attention row goes through
* this, so a call to libm's expf per element is most of the cost of those ops. How much is
* measured per op by rad-avx-bench.
*
* THE POLYNOMIAL IS MINIMAX DEGREE 5 ON [-ln2/2, ln2/2] after range reduction, which is ~0.6 ulp
* and comfortably inside every tolerance in this project -- softmax's 1e-6 included, because the
* softmax NORMALISES: a relative error common to every term cancels in the quotient, and what
* survives is the DIFFERENCE between lanes' errors, an order smaller again.
*
* NULL RESULT, on the two ways of not writing this: the _mm512_exp_ps SVML form is not available
* without Intel's runtime, and GCC's libmvec vectorises expf only when it can prove the loop is
* safe to call `_ZGVeN16v_expf` from, which it cannot do inside a kernel that also does integer
* work. Hand-writing the polynomial is not a micro-optimisation here, it is the only way to get a
* vector exp at all. */
static inline vf vf_exp(vf x) {
#if AVX_LEVEL == 0
return std::exp(x);
#else
/* Clamp first: the reduction below overflows the integer exponent construction outside this
* range. The TOP saturates, which every consumer here wants rather than an infinity. The
* BOTTOM and a NaN are put right after the polynomial, because the clamp alone answers
* wrongly for both: e^-inf would come out as e^lo, a tiny positive number, and a NaN would be
* clamped to lo and vanish -- so a fully masked softmax row would read 1/n instead of the NaN
* libref gives. Below lo e^x is under the smallest normal float and is taken as zero. */
const vf hi = vf_set1(88.3762626647949f), lo = vf_set1(-87.3365447504f);
const vf x0 = x;
x = vf_min(vf_max(x, lo), hi);
const vf log2e = vf_set1(1.44269504088896341f);
const vf c1 = vf_set1(-0.693359375f), c2 = vf_set1(2.12194440e-4f);
#if AVX_LEVEL == 3
vf n = _mm512_roundscale_ps(vf_mul(x, log2e), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
#else
vf n = _mm256_round_ps(vf_mul(x, log2e), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
#endif
/* x - n*ln2, split so the product is exact in f32. */
vf r = vf_fma(n, c1, x);
r = vf_fma(n, c2, r);
vf r2 = vf_mul(r, r);
/* exp(r) on [-ln2/2, ln2/2]. Horner, so the dependency chain is the depth of the polynomial
* and not of a wider evaluation tree. */
vf p = vf_set1(1.9875691500e-4f);
p = vf_fma(p, r, vf_set1(1.3981999507e-3f));
p = vf_fma(p, r, vf_set1(8.3334519073e-3f));
p = vf_fma(p, r, vf_set1(4.1665795894e-2f));
p = vf_fma(p, r, vf_set1(1.6666665459e-1f));
p = vf_fma(p, r, vf_set1(5.0000001201e-1f));
p = vf_fma(p, r2, vf_add(r, vf_set1(1.0f)));
/* 2^n by building the exponent field directly. */
#if AVX_LEVEL == 3
__m512i k = _mm512_slli_epi32(_mm512_add_epi32(_mm512_cvtps_epi32(n), _mm512_set1_epi32(127)), 23);
vf e = vf_mul(p, _mm512_castsi512_ps(k));
e = _mm512_mask_mov_ps(e, _mm512_cmp_ps_mask(x0, lo, _CMP_LT_OQ), _mm512_setzero_ps());
return _mm512_mask_mov_ps(e, _mm512_cmp_ps_mask(x0, x0, _CMP_UNORD_Q), x0);
#else
#if AVX_LEVEL == 2
__m256i k = _mm256_slli_epi32(_mm256_add_epi32(_mm256_cvtps_epi32(n), _mm256_set1_epi32(127)), 23);
vf e = vf_mul(p, _mm256_castsi256_ps(k));
#else
__m128i nlo = _mm_cvtps_epi32(_mm256_castps256_ps128(n));
__m128i nhi = _mm_cvtps_epi32(_mm256_extractf128_ps(n, 1));
nlo = _mm_slli_epi32(_mm_add_epi32(nlo, _mm_set1_epi32(127)), 23);
nhi = _mm_slli_epi32(_mm_add_epi32(nhi, _mm_set1_epi32(127)), 23);
__m256 k = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_castsi128_ps(nlo)),
_mm_castsi128_ps(nhi), 1);
vf e = vf_mul(p, k);
#endif
e = _mm256_andnot_ps(_mm256_cmp_ps(x0, lo, _CMP_LT_OQ), e);
return _mm256_blendv_ps(e, x0, _mm256_cmp_ps(x0, x0, _CMP_UNORD_Q));
#endif
#endif
}
static inline vf vf_sigmoid(vf x) {
/* 1 / (1 + e^-x). Not the tanh form: this is what libref computes and the two differ in the
* last ulp, which `sigmoid`'s 1e-5 f32 tolerance would pass but `hc_read`'s gate chain -- a
* sigmoid of a dot product of a sigmoid -- accumulates. */
return vf_div(vf_set1(1.0f), vf_add(vf_set1(1.0f), vf_exp(vf_sub(vf_zero(), x))));
}
static inline vf vf_silu(vf x) { return vf_mul(x, vf_sigmoid(x)); }
#if AVX_LEVEL >= 2
/* The CHEAP silu, for consumers that round to bf16 on the next store: a Taylor-4 exp head
* (truncation ~6e-5) and a raw reciprocal seed (2^-14 avx512, 2^-12 avx2, no Newton step)
* instead of the minimax tail and the division. ~3e-4 worst lane against the 6e-3 bf16
* bucket: twentyfold of margin -- but NOT for f32 consumers, where 3e-4 does not fit 1e-5.
* Declared here rather than inside one kernel so every bf16-store consumer can reach it;
* silu_mul is the only caller today, because in a frontend-bound token loop -- the conv
* kernels -- the difference is unmeasurable. Callers key on their OUTPUT dtype. */
static inline vf vf_exp_t4(vf x) {
const vf hi = vf_set1(88.3762626647949f), lo = vf_set1(-87.3365447504f);
x = vf_min(vf_max(x, lo), hi);
const vf log2e = vf_set1(1.44269504088896341f);
const vf c1 = vf_set1(-0.693359375f), c2 = vf_set1(2.12194440e-4f);
#if AVX_LEVEL == 3
vf n = _mm512_roundscale_ps(vf_mul(x, log2e), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
#else
vf n = _mm256_round_ps(vf_mul(x, log2e), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
#endif
vf r = vf_fma(n, c1, x);
r = vf_fma(n, c2, r);
/* Taylor-4 head: 1 + r(1 + r(1/2 + r(1/6 + r/24))). Four FMAs against the exact path's
* seven-op minimax tail -- the reduction above is unchanged, so the exponent build below
* is too. */
vf p = vf_fma(r, vf_set1(1.0f / 24.0f), vf_set1(1.0f / 6.0f));
p = vf_fma(p, r, vf_set1(0.5f));
p = vf_fma(p, r, vf_set1(1.0f));
p = vf_fma(p, r, vf_set1(1.0f));
#if AVX_LEVEL == 3
__m512i k = _mm512_slli_epi32(_mm512_add_epi32(_mm512_cvtps_epi32(n), _mm512_set1_epi32(127)), 23);
return vf_mul(p, _mm512_castsi512_ps(k));
#else
__m256i k = _mm256_slli_epi32(_mm256_add_epi32(_mm256_cvtps_epi32(n), _mm256_set1_epi32(127)), 23);
return vf_mul(p, _mm256_castsi256_ps(k));
#endif
}
static inline vf vf_silu_fast(vf x) {
#if AVX_LEVEL == 3
vf e = vf_exp_t4(vf_sub(vf_zero(), x));
vf d = vf_add(vf_set1(1.0f), e);
vf r = _mm512_rcp14_ps(d);
#else
vf e = vf_exp_t4(vf_sub(vf_zero(), x));
vf d = vf_add(vf_set1(1.0f), e);
vf r = _mm256_rcp_ps(d);
#endif
/* No Newton step: d lies in [1, emax] so the seed is in range and nothing overflows. */
return vf_mul(x, r);
}
#endif
/* Sum of squares of a row, vectorised, with a FIXED reduction tree so the answer does not depend
* on the compiler's unrolling. Used by every norm. */
/* ================================================================== an operand's row, as f32
*
* THE TWO FUNCTIONS EVERY KERNEL OPENS WITH. `in_row` hands back a pointer to `n` floats holding
* element (base + i * laststride) of the operand -- which is `t->data` itself when the operand is
* already dense f32, so the common case copies nothing at all. `out_row` is the inverse.
*
* They are where the DENSE/STRIDED split lives, and it lives in one place on purpose: every op in
* this vocabulary has to accept a strided view (libref/ref_ops.h: "no geometry constraints" has to
* mean strides too), and seventy-five kernels each writing their own stride test is seventy-five
* chances to write `t->stride[0]` where `laststride(t)` was meant. */
/* ONE STEP OF AN EXACT TOP-R SELECTION over a row of f32: descending by value and, ON A TIE, by
* the LOWER index. That tie rule is libr4d's and it has to be stated rather than left to a sort's
* stability -- a router that breaks ties differently from the kernel it is checked against routes a
* token to a different expert, and the diff is a whole layer wide.
*
* `pv`/`pi` carry the previously selected (value, index); seed them with +infinity and -1. Returns
* false when nothing is left to select. Shared by row_topk, router_topk and sample_topk, which is
* why it is here rather than in one of them. */
bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi);
const float* in_row (const struct RadTensor* t, int64_t base, int64_t n, float* scr);
void out_row(const struct RadTensor* t, int64_t base, int64_t n, const float* src);
float row_sumsq(const float* x, int64_t n);
float row_sum (const float* x, int64_t n);
float row_amax (const float* x, int64_t n);
float row_max (const float* x, int64_t n);
} /* inline namespace AVX_SUFFIX */
} /* namespace avx */
#endif /* RAD_AVX_VEC_H */