radiance 1.7.0

- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-16 18:25:18 +02:00
1 parent b068190326
commit 1e968f6e1d
739 files changed
+128447 -84632

No files matched your search

+47 -65
View File
@@ -1,39 +1,24 @@
# libavx -- the conventional op vocabulary in hand-written x86 SIMD, dispatched by CPU feature.
#
# ============================ THE BUILD IS THE DISPATCH ============================
# This build is what makes runtime dispatch safe:
#
# 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 OBJECT libraries with different
# -m flags and AVX_LEVEL=0..3. avx_vec.h wraps each level in its own inline namespace; without
# that the linker would keep one definition (e.g. of avx::row_to_f32) for all four tables, and
# the scalar path could execute AVX-512 and fault.
#
# 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 registry are compiled at baseline with no -m flags, because they decide
# which levels may run. This depends on the flags, not the source: with -mavx512f the compiler
# may auto-vectorise code that has no intrinsics.
#
# 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.
# No -march=native: the .so is copied to other machines and dlopened by an engine that does not
# know its target, so it would SIGILL on older CPUs before main.
#
# -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.
# The root CMakeLists adds this directory on every x86-64 build; these are the production host
# kernels (e.g. the n-gram embedding gather when placed on the host). It also builds standalone
# against an installed radiance, like any third-party plugin:
# `cmake -S libavx -B build-avx -DCMAKE_PREFIX_PATH=<radiance prefix>`. That needs no ROCm, and
# the checker's oracle is then the installed reference library.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(libavx LANGUAGES CXX)
@@ -41,13 +26,11 @@ if(NOT COMMAND rad_add_plugin)
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.
# The harnesses go beside the plugin in the build's $RADIANCE_HOME; the loader ignores non-.so files.
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.
# Every kernel translation unit. The baseline sources belong to the plugin target below.
set(AVX_KERNEL_SRC
avx_support.cpp
avx_table.cpp
@@ -56,26 +39,27 @@ set(AVX_KERNEL_SRC
avx_hc.cpp
avx_quant.cpp
avx_gemm.cpp
avx_gemm_tile.cpp
avx_planes.cpp
avx_attn.cpp
avx_qsa.cpp
avx_moe.cpp
avx_gdn.cpp
avx_sample.cpp
avx_misc.cpp
avx_gen.cpp
avx_gen_attn.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.
# The flag sets, written out because each states which instructions the object may contain.
#
# 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).
# 0 scalar x86-64 baseline (SSE2).
# 1 avx -mavx only. F16C and FMA are separate CPUID bits (Ivy Bridge, Haswell); requiring them
# would fault on the Sandy Bridge parts this level exists for.
# 2 avx2 -mavx2 -mfma -mf16c, which ship together.
# 3 avx512 F + BW + DQ + VL (the conjunction avx_dispatch.cpp checks) plus the AVX2 set. No
# avx512bf16 / avx512vnni: many AVX-512 parts lack them (avx_vec.h converts bf16 with
# integer ops instead of vcvtneps2bf16).
set(AVX_FLAGS_0 "")
set(AVX_FLAGS_1 -mavx)
set(AVX_FLAGS_2 -mavx2 -mfma -mf16c)
@@ -89,18 +73,12 @@ foreach(lvl RANGE 0 3)
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.
# Contraction is allowed, unlike libref (the oracle, which must not contract). libavx is checked
# against it to a tolerance, and vectorised reductions are not bit-exact anyway, so FMA is kept.
-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.
# No -ffast-math: it assumes no NaN/Inf and no signed zero, and these ops rely on them (a masked
# logit is -inf; an attention row with no valid keys carries a NaN through the online softmax).
# The checker compares the finiteness pattern before any value.
-fno-math-errno)
set_property(TARGET avx_lvl${lvl} PROPERTY POSITION_INDEPENDENT_CODE ON)
if(OpenMP_CXX_FOUND)
@@ -109,9 +87,8 @@ foreach(lvl RANGE 0 3)
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.
# Baseline sources. avx_ngram.cpp is also here because it holds the embedding gather's row cache
# and reader thread, which must exist once per process, not once per level.
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})
@@ -128,13 +105,18 @@ else()
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)
# The harnesses dlopen both plugins by path and link neither, so they exercise the exact .so the
# engine would load, in either build or against a plugin built elsewhere.
add_executable(rad-avx-check avx_check.cpp avx_check_hand.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)
# In the source tree the checker also decodes weights with the core's own decoder, an oracle
# independent of both plugins (avx_check_hand.cpp). One source file, not the core library.
if(TARGET rad_core)
target_sources(rad-avx-check PRIVATE ${CMAKE_SOURCE_DIR}/core/format/encoding.cpp)
target_include_directories(rad-avx-check PRIVATE ${CMAKE_SOURCE_DIR}/core)
target_compile_definitions(rad-avx-check PRIVATE AVX_CHECK_CORE_DECODER=1)
endif()
set_target_properties(rad-avx-check PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${AVX_OUT_DIR})
add_executable(rad-avx-bench avx_bench.cpp avx_cases.cpp)
+530 -143
View File
@@ -1,130 +1,274 @@
# libavx
The conventional op vocabulary in hand-written x86 SIMD, runtime-dispatched by CPU feature.
The conventional op vocabulary in hand-written x86 SIMD, dispatched at run time 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.
libavx is a kernel plugin beside `libref` and `libr4d`. libref is the only other host
implementation, and it is a slow reference. libavx implements all 123 of libref's ops with the
same schemas and the same answers to a tolerance, the image generator's included (below).
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.
It builds on its own 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, because it supplies the engine's host kernels: libref is the oracle and
the engine refuses to serve on it, so an op placed 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, wherever
`--ngram-placement` leaves the n-gram table for the host gather: in the container's mapping
(`disk`), or in a locked copy in RAM when no device kernel for the op is loaded (`ram`). Where
libr4d is loaded, `ram` is a pinned copy its kernel reads over the link and this one does not run.
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.
`--ngram-placement` leaves the n-gram table for the host gather: read from the container file
(`disk`), or a locked copy in RAM when no device kernel for the op is loaded (`ram`). Where libr4d
is loaded, `ram` is a pinned copy its kernel reads over the link, and this one does not run.
`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 rows come through `avx_ngram.cpp`, compiled baseline so the process has one of each:
## The build is the dispatch
- a row cache shared by every thread (2^19 rows, eight ways, CLOCK replacement);
- an O_DIRECT read through io_uring for each miss, with the ranks dividing a call's misses rather
than duplicating them;
- a reader thread that fetches the next prefill chunk's rows while the current one runs.
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.
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 rows from the container file as stored.
`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.
`rad-avx-check` runs the op over a file-backed table with two ranks and the reader racing, and
compares every row with the file's bytes: 1000 calls at the highest level the CPU executes and 50 at
each other level. The reads, the cache and the reader thread are compiled once, at the baseline, so
the other levels differ only in the decode. Each table is written once per run under a name of its
own.
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.
## 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` puts each level in its
own inline namespace so the four symbol sets cannot collide; otherwise the linker picks one
definition of `avx::row_to_f32` for all four tables and the scalar path executes AVX-512.
`avx_dispatch.cpp` and `avx_registry.cpp` decide whether the others may run, so they are compiled
baseline, with no `-m` flags. That is a property of the flags, not the source: a compiler given
`-mavx512f` may auto-vectorise anything. `-march=native` appears nowhere.
Detection uses `__builtin_cpu_supports`, not raw CPUID, because the OS must also enable the state:
a CPU may enumerate AVX-512 while the kernel leaves the ZMM state disabled, and using it then
faults. AVX-512 requires F + BW + DQ + VL, all 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.
four levels and the engine never reaches 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.
Every op `libref` implements, `libavx` implements, so the selector resolves no op of a CPU-only
deployment to libref: Flash-Next's QSA indexer, the DFlash2 drafters' convolution and the image
generator included. `rad-avx-check` fails on any missing op, and reports a row that returns
`RAD_E_UNSUPPORTED` separately from one that is absent: a declining row is worse than none, because
the selector resolves to it and the step fails at issue rather than at declare.
Every `RAD_E_UNSUPPORTED` a libavx kernel returns, beside libref's answer to the same geometry:
| where | libavx refuses | libref |
|---|---|---|
| `attn_paged`, `attn_dense` | head_dim over 2048 | the same (`REF_HD_MAX`) |
| `attn_local_rel` | a right context; head_dim or left context + 1 over 2048 | the same |
| `rope`, `qk_norm_rope`, `qsa_block_key` | an unknown `mode`; for `rope`, an unknown `ladder` | the same |
| `rope` | YaRN with `axial` or a position scale | the same |
| `rope` | a rotary half-width over 1024 | the same |
| `had_quant_act_i8`, `had_quant_act_fp8`, `rmsnorm_had_quant_i8`, `gated_had_quant_i8`, `hc_read` | a Hadamard group over 4096 | the same (`REF_HAD_MAX`) |
| `gdn_conv_prep`, `gdn_conv_update` | a convolution history over 16 | the same |
| `gdn_recurrent_update` | a `state_form` other than `per_candidate` or `anchor` | the same |
| `ple_conv`, `causal_conv1d` | a history over 64 | the same |
| `ngram_ids` | `ngram` over 8 | the same |
| `moe_gemm`, `moe_gemm_q`, `moe_gemm_q_mod4` | an `a_order` other than `token` or `sorted` | the same |
| `gemm_nt_q` | parts (`pb1`/`pb2`) over a weight other than MXFP4 and the ParoQuant grids, or on the bias form | the same |
| `gemm_nt_q` | parts at `w2a8` / `w4a8_asym`; a zero-point grid's bias form; `a_sum` at any other grid; `b_ref` beside a weight other than e2m1 | the same |
| `attn_prefix_self` | head_dim over 1024; the int8 score form with descales | the same |
| `all_reduce`, `all_gather` | world size over 1 | serves up to 8 ranks; deliberate, below |
| `embed_lookup_q` | a file without direct I/O; a bf16 gather in a process without io_uring | reads the table as memory; deliberate, see the gather above |
Everything but the last two rows refuses exactly where libref does, so the selector never
resolves a geometry to libavx that libref would have served. The per-entry image ops
(`lane_gather`, `lane_store`, `randn_lanes`, `flow_euler`) check every entry before writing any,
where libref writes the entries before a bad one; they return libref's code, and refuse (with
`RAD_E_SHAPE`) the entries libref would read or write past an operand for.
`moe_gemm_q` and `moe_gemm_q_mod4` carry layout hooks for Qwen3.8-Flash-Next's codebook experts
(`w4nla8h`, `w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h`; `docs/MOE-W4.md`): a view of several planes
(`codes,table`, `scale,scale.1`) is stored in the joined form of `abi/rad_planes.h`, the bytes
libref's hooks store, and a selection the `dtype` does not name is refused at declare with
`RAD_E_DTYPE`, as libref refuses it. At launch both libraries refuse with `RAD_E_DTYPE` a joined
form of other planes, plain and codebook experts in one call, and a joined scale beside plain codes.
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.
implementation is a rendezvous over shared state with a barrier and a generation counter, one per
process; two plugins each carrying one would make two rendezvous groups for one world, and which
one a rank joined would depend on 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 makes an op in `docs/OPS.md` 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.
`rad-avx-check` opens both plugins with `dlopen` and links neither, so it checks the `.so` the
engine would load. It checks, in order: schema agreement (a copy of the loader's `schema_same`, run
before any arithmetic, because the loader refuses the whole plugin on one disagreement), coverage,
the numbers, and every ISA level. Each level prints:
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
522 checked, 522 passed, 0 failed, 0 declined, 0 skipped, 0 missing. worst rel_l2 = 3.556e-04
worst case: rmsnorm M=3 n=645 eps=1e-05 dtype=bf16 wadd=1
522 rerun on 4 threads, byte for byte
hand-built: 198 checked, 0 failed
zero rows: 116 ops 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.
against `rad-kbench`'s tolerance table, ids (i32, u32, i64 outputs) exactly; the worst case differs
per level. Every conversion is also checked exhaustively: all 256 or 65536 bit patterns of each
narrow format, in both directions, bit-identical to libref including NaN, subnormals and negative
zero. Normal draws reach none of those patterns, so a conversion can be wrong by octaves at the
bottom of its range while every geometry 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.
Each case also checks what a value comparison cannot see:
A cold description cannot reach every form of every op, and the **hand-built cases** are the rest:
- **Guard bytes.** Every operand and scratch buffer carries 64 bytes of a known pattern on each
side, checked after the launch, for both plugins. A write past a row's end is otherwise invisible
until it lands on something the engine reads.
- **Inputs unchanged.** Every input and weight must hold its drawn bytes after the launch; a kernel
writing into one would corrupt a weight or a shared buffer in the engine.
- **Something was computed.** A case whose libref output equals what was drawn (all-zero weights,
a sampler stage its parameters switch off) fails as vacuous.
- **Threads.** Every check geometry is below the kernels' OpenMP thresholds, so each case runs a
second time with every parallel region forced onto four threads through `avx_par_force` (an
exported symbol, like `avx_isa_force`) and must reproduce the serial run byte for byte, as the
threading rule in `avx_common.h` promises. `--threads N` changes the team, 0 skips the rerun.
- **Zero rows.** Each op's first case is described at its row count and at twice it; the extents
that change are set to zero and the op launched with its row parameter at 0. It must return
`RAD_E_SHAPE` and write nothing, as docs/OPS.md requires and libref does.
A case libref cannot describe or run fails rather than being skipped, because the table is then
wrong. Two forms libref cannot describe have no table case for that reason: `sample_merge_topk`'s
packed (id, logit) words and the bias form of `gemm_nt_q` at `fp8a16` (it requires `a_scale`); the
first is a hand-built case.
The harness draws what libref's descriptions cannot state: integer and 4-bit codes across their
grid (a weight-scale draw truncates them to zero), weight tables (a MoE layer's experts) like any
weight, an operand flagged `RAD_OPD_F_IDX_PREFIX` (a routing histogram's offsets) as a
non-decreasing prefix array, and an E8M0 exponent plane as the power of two nearest each draw.
Sampler rows are its own too: libref describes them as random requests (`RAD_FILL_SAMPLE_PARAMS`,
over a `RAD_OPD_F_IDX_HISTORY` history), which rad-kbench draws; the harness writes each row as a
request with every stage switched on, over a history that repeats itself.
A cold description cannot reach every form of every op, and the hand-built cases cover 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.
selects. For example, a description draws `dflash_select`'s 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. Others cover formats libref does not describe: MXFP4 weights with e8m0 exponents
(one of them 0xFF, NaN), ParoQuant's multi-part GEMM, an fp8 KV cache read with per-head descales,
4-bit experts, activation scale grids finer than the weight's, packed-code stores, and
`gdn_recurrent_update`'s anchor state form, both against libref and against itself: over four steps
the anchor replay must give the per-candidate form's `o` bit for bit, which is what lets greedy
speculation emit the same text as greedy decode.
## The measurement platform
The codebook experts reach both libraries in the joined form, which no description draws. Their
cases draw canonical planes (codes over the whole code range, the shipped w4nl and w5nl tables,
E4M3 or bf16 scales, the fixed 2^-13 level), store them through each library's own layout hooks,
and run each library on its own stored bytes, every form at four geometries that reach each decode
at each level: AVX-512's lines, the chunk decode, the generic one; the fused and the panel forms;
narrower classes, a dropped slot, a partial row block and odd widths. Besides the checks above,
both libraries must store the same bytes and each unrelayout give the planes back; libref over the
stored form must equal libref over the logical form rad-kbench and the oracle pass, bit for bit;
and both must agree with the core's own decoder (`core/format/encoding.h`, compiled into the
checker in the source tree): the weight decoded with its Hadamard undone against the activation
rotated back, summed in double. The hooks of both libraries must refuse the same mismatched
selections with the same code.
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.
The QSA indexer's hand-built cases are batches a description cannot draw: `cu` not starting at 0
and rows no sequence holds, -1 pages and a sequence whose blocks are all dead, the score plane as a
column slice of its declared width, block keys in the KV cache's rank, ring wrap in the tail store
and the work list, and libr4d's eight few-live selection rows, held to the selection rule itself as
well as to libref. Their outputs start as a sentinel, so an element only one side writes shows.
### Weights of several planes
A weight joined over several planes (docs/OPS.md, Weights of several planes; abi/rad_planes.h) has
no description, so its cases are hand-built: canonical planes with codes across their range, real
scales, zeros at both ends of the code range; both libraries' layout hooks must join them into the
same bytes and invert them back; both launch over the joined form. Each GEMM case is also held to
an answer neither library computes: in radiance's own tree the checker compiles in the core's
affine decoder (core/format/encoding.cpp), dequantises the planes and the activation, and takes a
double product. The cases:
- `logits_gemm` over `fp8_e4m3*bf16[128x128]` (N = 200, K = 320: a partial block row and column)
and `i8*bf16[1x128]` heads, M 1, 5 and 9, bf16 and f32 activations; `logit_rerank` over both,
candidates across the shard and both block rows.
- `hc_read` (inject and the final mixer) and `mtp_enter` over E4M3 rows with f32 scales per 128
columns and per quarter row, bf16 and f32.
- `gemm_nt_q` at `w2a8`, `w4a8_asym`, `w4a16_asym`, `w5a16`, `w4a8i8_asym` and `w5a8i8`, M 1,
13 and 17 (the small-M paths' blocks and the decoded driver), N not a multiple of 6 or 16, the
ParoQuant grids in two and three parts; a plain `b_scale` at a grid is refused by both.
- The hooks' refusals, pinned for both libraries: a u4 head, a transformed head, a grid's scale
and zero over the wrong codes, at the wrong group, out of order, or at a grid without a zero.
At every level the heads' f32 logits agree with libref to 4e-7 and the grids' bf16 outputs to 5e-9
(most of them byte for byte); against the core decoder the logits are within 4e-7 and the
grids within 2e-3, their bf16 rounding.
## Checking another host library
`rad-avx-check` checks any host kernel library against libref, without a GPU and without the
engine:
rad-avx-check --ref <prefix>/share/radiance/kernels/libref.so --avx path/to/mylib.so
A library not named `libavx` is checked as a host library rather than held to libavx's contract:
- Schemas must agree with libref's wherever both declare an op, since the loader refuses the
plugin otherwise. Ops libref does not declare have no oracle and are not checked.
- Coverage is reported: the libref ops the library has no host row for are listed, and every table
and hand-built case for them is left out. A row that returns `RAD_E_UNSUPPORTED` still fails, for
the reason above.
- Each case runs on the row the selector would choose: the host row whose constraints the
geometry meets, highest priority first. A case no row admits is counted, not failed. Device rows
are never launched; the checker passes host pointers.
- The ISA sweep needs `avx_isa_force`, and the threaded rerun `avx_par_force`. Without them the
library is checked once, at the level it picks for itself, on the thread count it picks.
- The file-backed gather and its init are libavx's own and do not run.
Everything else applies unchanged: the tolerances, guard bytes, unchanged inputs, exact ids, the
vacuity check and the exhaustive conversions (when the library has `cast`).
## Measurement platform
The numbers below are one thread on a Ryzen 9 9950X3D (Zen 5, 16 cores, 128 MiB L3), measured with
`rad-avx-bench --peak`. All four ISA levels execute natively on that part. Re-run the commands above
for another CPU; 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.
The avx2 and avx512 figures are 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 not a
read-for-ownership the compiler may have elided.
`--peak --threads N` measures the memory ceilings on N threads, and adds a read-only stream, the
ceiling of an op that only reads (the QSA indexer's keys). Each eight-core complex of this part
reaches memory through its own link, narrower for writes than for reads, so the triad hardly moves
with threads while the read stream does:
read DRAM 39 GB/s 1 thread 53-57 GB/s 8 threads (cores 0-7) 64-66 GB/s 16 threads
The ranges are run-to-run spread on a machine shared with other work.
## Conversion, MB/s of source bytes
`rad-avx-bench --cvt`, through the plugin's own `cast`.
`rad-avx-bench --cvt`, through the plugin's own `cast`, same platform.
| pair | scalar | avx | avx2 | avx512 | libref |
|---|---|---|---|---|---|
@@ -137,14 +281,14 @@ written — and does not count a read-for-ownership the compiler may have elided
| 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.
f16 is software below AVX2 because F16C is a separate CPUID bit that arrived a 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.
`rad-avx-bench`, microseconds per launch, median of 7 reps, one thread, cache-warm, same platform.
The 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) |
|---|---|---|---|---|---|---|---|
@@ -162,75 +306,310 @@ speculative verify window, 512 a prefill chunk.
| 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:
The libref column is about libref, a scalar loop with a per-element dtype switch; the ratio only
shows an op is wired. The rate column against the ceilings above is what describes 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.
- `gemm_nt` at prefill reaches 188 GFLOP/s of a 351 GFLOP/s ceiling (54%).
- `sample_argmax` reaches 111 GB/s of a 129 GB/s L1 ceiling (86%): a single pass over the logits,
close to the memory system's limit.
- `softmax` at 41 GB/s and `logits_gemm` at 24 GB/s are DRAM-bound. `logits_gemm`'s weight is
128 MiB in bf16 and fits no cache, so it is a memory benchmark, and 24 against a 42 GB/s
single-thread triad is the comparison that applies.
- `silu_mul` at 23 GB/s and `rmsnorm` at 48 GB/s 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.
All numbers are single-thread. The plugin parallelises over the outer dimension with OpenMP above a
work threshold; the bench pins one thread because that ranks a kernel change, while a 32-thread
number measures the memory controller.
## Why the code is shaped the way it is
### The codebook experts
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.
`rad-avx-bench --moe [--moe-dtype LIST] [--threads N]` runs `moe_gemm_q` over Qwen3.8-Flash-Next's
experts at the model's geometry on one rank: 512 experts in two parity tables at top-k 10, gate_up
`[1280, 2560]` and down `[2560, 640]`, 1.3 GB stored through libavx's own layout hooks. Each call
draws a new routing, so a decode step reads its experts from DRAM as a served one does. GB/s counts
the codes and scales of the experts a call routes to; GFLOP/s is `2 M top_k N K`. One thread on a
core that measured 347 GFLOP/s (FMA, avx512) and a 39.6 GB/s DRAM triad in the same session;
microseconds per call:
**The register block is swept, not reasoned about** (`gemm_nt` bf16, M=512 N=2048 K=2048):
| dtype | M | proj | libref | scalar | avx | avx2 | avx512 | rate (avx512) |
|---|---|---|---|---|---|---|---|---|
| w4nl64a8h | 1 | gate_up | 52215 | 17166 | 14371 | 1706 | **591** | 28.6 GB/s |
| w4nl64a8h | 1 | down | 25558 | 8655 | 7351 | 869 | **392** | 21.5 GB/s |
| w4nl64a8h | 4 | gate_up | 209824 | 67939 | 56762 | 6738 | **2427** | 27.1 GB/s |
| w4nl64a8h | 4 | down | 100874 | 33854 | 28751 | 3426 | **1523** | 21.6 GB/s |
| w4nl64a8h | 64 | gate_up | | | | 73779 | **32050** | 19.4 GB/s |
| w4nl64a8h | 64 | down | | | | 37662 | **18215** | 17.0 GB/s |
| w4nl64a8h | 2048 | gate_up | | | | 1109980 | **665963** | 201.5 GFLOP/s |
| w4nl64a8h | 2048 | down | | | | 557618 | **293857** | 228.4 GFLOP/s |
| w4nla8h | 1 | gate_up | 49967 | 18048 | 15348 | 1629 | **538** | 31.4 GB/s |
| w4nla8h | 2048 | gate_up | | | | 1100388 | **662523** | 202.6 GFLOP/s |
| w4nl32a8h | 1 | gate_up | 54194 | 17841 | 15042 | 1840 | **696** | 25.0 GB/s |
| w4nl32a8h | 2048 | gate_up | | | | 1196490 | **668847** | 200.7 GFLOP/s |
| w5nl64a8h | 1 | gate_up | 51501 | 18977 | 16711 | 3895 | **1202** | 17.5 GB/s |
| w5nl64a8h | 2048 | gate_up | | | | 1149541 | **694854** | 193.2 GFLOP/s |
On eight threads (eight cores, an 8-thread DRAM triad of 45.8 GB/s) the served form reads 54.4 /
53.6 GB/s at M = 1 (gate_up / down) and 55.1 / 53.4 at M = 64, and computes 1529 / 1607 GFLOP/s at
M = 2048, 55-58% of eight cores' FMA peak. Decode is then at the memory system's limit: the triad
also writes, and the read stream is faster than it.
- **Decode on one thread** reaches 72% of the triad on gate_up, and the decode is what limits it
(eight vpermps and seven shifts per 128 codes): cache-warm, the same call reads about 30 GB/s.
down's rows are 320 bytes, so the per-row work (scales, horizontal sums, stores) weighs more. At
M = 64 most experts take one or two rows, and each 64-row item is mostly overhead around a short
decode.
- **u5 decodes at half u4's rate**: a code straddles bytes, so each sixteen take a broadcast, a
vpshufb, a variable shift and a two-table vpermt2ps. w5nl64a8h is not the served form.
- **AVX2** decodes through two 8-entry vpermps and a blend per eight codes; it is 2-3x the AVX-512
time on one thread and the same on eight, where both wait on DRAM.
- **Prefill** reaches 58-66% of the FMA peak, gemm_nt's share: the 3 x 8 register block over an
L2-resident panel decoded once per 64 rows, one horizontal sum per output.
- The scalar and AVX levels decode a row through the table and take the generic dot; they are the
correctness baselines.
### The QSA indexer and DFlash2's convolution
Qwen3.8-Flash-Next's indexer (`arch/qwen4exp_fp8`: 4 heads of 128, ratio 4, topk 512, a 7-row
ring) over 8K, 64K and 200K tokens of context, with every block complete and every query past
them; and the 27B DFlash2 drafter's convolution (`arch/common/rad_block_dflash2.h`: n_embd 5120,
2 taps, groups of 16, a 16-row block). One thread, cache-warm, as above; `blocks` is context / 4.
| op | geometry | libref | scalar | avx | avx2 | avx512 | rate (avx512) |
|---|---|---|---|---|---|---|---|
| qsa_score | M=1, 8K (2048 blocks) | 896 | 269 | 41.6 | 34.0 | **31.4** | 17.2 GB/s |
| qsa_score | M=1, 64K | 7938 | 2159 | 341 | 296 | **225** | 19.2 GB/s |
| qsa_score | M=1, 200K | 24222 | 6662 | 1061 | 944 | **724** | 18.2 GB/s |
| qsa_score | M=4, 200K | 88009 | 23875 | 2277 | 2100 | **1400** | 146 GFLOP/s |
| qsa_score | M=2048, 64K | 14.9 s | 3.92 s | 313 ms | 322 ms | **184 ms** | 187 GFLOP/s |
| qsa_select | M=1, 8K | 6.19 | 6.33 | 5.99 | 1.69 | **1.64** | 10.0 GB/s |
| qsa_select | M=1, 200K | 339 | 135 | 135 | 23.0 | **21.0** | 19.1 GB/s |
| qsa_select | M=2048, 64K | 241 ms | 130 ms | 111 ms | 36.4 ms | **29.9 ms** | 9.0 GB/s |
| qsa_tail_store | 4 sequences, decode | 1.03 | 0.21 | 0.15 | 0.12 | **0.10** | 20.0 GB/s |
| qsa_work | 4 sequences, decode | 4.05 | 0.83 | 0.62 | 0.49 | **0.41** | 20.1 GB/s |
| qsa_work | 2048 rows, 512 blocks | 467 | 93.0 | 67.5 | 51.8 | **40.8** | 25.7 GB/s |
| dflash_conv | T=16 | 538 | 41.6 | 27.1 | 13.4 | **8.28** | 44.5 GB/s |
| dflash_conv | T=64 | 2156 | 166 | 109 | 55.0 | **37.0** | 38.2 GB/s |
The indexer is the only decode op that grows with context, and at decode its keys (256 bytes a
block, 12.8 MB at 200K) fit this part's L3 though no real step leaves them there. So decode is also
measured the way it runs: on a team (`--threads`), with the operands flushed from every cache
before each launch (`--cold`), against the read-only ceiling of the same team. Eight threads on
cores 0-7:
| op | geometry | avx512 | rate | ceiling |
|---|---|---|---|---|
| qsa_score | M=1, 8K | 14.0 | 38.5 GB/s | 53-57 GB/s read |
| qsa_score | M=1, 64K | 84.7 | 51.1 GB/s | 53-57 GB/s read |
| qsa_score | M=1, 200K | 213 | 62.0 GB/s | 53-57 GB/s read |
| qsa_score | M=4, 200K | 278 | 49.7 GB/s | 53-57 GB/s read |
| qsa_score | M=2048, 64K | 25.3 ms | 1360 GFLOP/s | 2680 GFLOP/s FMA |
| qsa_select | M=4, 200K | 47.8 | 33.5 GB/s | |
| qsa_select | M=2048, 64K | 4.94 ms | 54.4 GB/s | |
On all 16 cores (0-15), with another job on the machine, decode over 200K tokens takes 219 us at
M=1 (60 GB/s of a 64-69 GB/s read ceiling) and 277 us at M=4, no faster than on one complex: the
stream is at the memory's limit either way. The prefill chunk takes 13.7 ms (2.5 TFLOP/s).
- `qsa_score` at decode streams the keys at or near the read ceiling from 64K up, with the software
prefetch 32 blocks ahead (a block table need not be in page order, so the hardware prefetcher
cannot follow it). At M=4 a block's 16 dot rows are compute the stream does not fully hide. At 8K
a launch moves 0.5 MB, too little for the stream to reach its rate. One thread reaches 44% of the
FMA ceiling at M=4 and 56% at prefill: each (row, block group) adds a 45-instruction lane
reduction and the accumulators' setup to its 128 FMAs.
- `qsa_select` is linear in the blocks, under 1 ns a block on one core, a row a thread; at decode a
row is one thread's work, a tenth of the scoring before it.
- `qsa_tail_store` and `qsa_work` copy at most a few hundred key rows a step through f32, as libref
does, so a key lands with the bits libref's would.
- `dflash_conv` is bound by instructions, not by L2 (152 GB/s): the bf16 store rounds in software,
RTNE with the ABI's NaN rule, about a third of each vector's instructions.
### Weights of several planes, at model size
The decode step's largest reads are an lm head and, in the 2-bit draft heads and ParoQuant's int4
and int5 linears, zero-point grids, all stored joined (docs/OPS.md). At M = 1 to 8 they are memory
benchmarks, so `rad-avx-bench --joined --threads 16` times them on every core (pinned to cores
0-15), each weight over a working set past the 128 MiB L3 (copies of a weight under 1 GiB), beside
a read-only stream of 1 GiB on the same threads, measured before and after the kernels and the
better reading kept: 70.5 GB/s in the run below (the triad: 50). Best of 7, milliseconds, from the
quietest of several runs on a machine shared with other work.
| op | geometry | M = 1 | M = 4 | M = 8 | M = 64 |
|---|---|---|---|---|---|
| logits_gemm | fp8_e4m3*bf16[128x128] 248320x5120 (1.27 GB) | 19.2 (66 GB/s) | 21.2 | | 70 (2.3 TFLOP/s) |
| logits_gemm | i8*bf16[1x128] 248320x5120 (1.29 GB) | 17.9 (72 GB/s) | 19.0 | | 83 (2.0 TFLOP/s) |
| logits_gemm | i8*bf16[1x128] 248320x2560 (0.65 GB) | 10.2 (63 GB/s) | 9.7 | | 34 (2.4 TFLOP/s) |
| gemm_nt_q | w2a8 248320x5120 (0.35 GB) | 5.2 (68 GB/s) | 5.7 | 6.1 | |
| gemm_nt_q | w4a16_asym 34816x5120, 2 parts (93 MB) | 1.8 (51 GB/s) | 1.5 | 2.7 | |
| gemm_nt_q | w4a16_asym 5120x17408 (47 MB) | 1.0 (46 GB/s) | 1.3 | 1.4 | |
| gemm_nt_q | w5a16 34816x5120, 2 parts (115 MB) | 2.6 (44 GB/s) | 4.6 | 5.5 | |
| gemm_nt_q | w5a16 5120x17408 (58 MB) | 1.3 (45 GB/s) | 1.5 | 2.6 | |
| gemm_nt_q | w4a8i8_asym / w5a8i8 34816x5120, 2 parts, M = 256 | | | | 53 / 47 (1.7 / 1.9 TFLOP/s) |
Against the read-only ceiling:
- **The lm heads run at 85-102% of it at M = 1 and 4.** A joined head goes through the GEMM's
register-blocked driver with a row decoder in its packing step (E4M3 by avx_vec.h's bit
reconstruction, int8 by widening, then one multiply by the covering scale), so the codes are
widened six rows at a time into L2 and never in memory. At M = 64 it is compute-bound at 2.0-2.4
TFLOP/s, 36-43% of the 5.6 TFLOP/s 16-core FMA peak: a decoded weight's M block is the whole of
M, so the head is decoded once, and the 1.3 MiB activation panel is read again for every six head
rows.
- **The 2-bit head runs at 96% of it at M = 1 and 81% at M = 8** on the integer path: code planes
in registers against the activation in plane order, one vpdpbusd a plane where AVX512-VNNI is
present (vpmaddubsw, vpmaddwd and an add where it is not).
- **ParoQuant int4 and int5 run at 62-72% of it at M = 1** (int4 reached 92-99% in a quieter run),
and fall to 30-50% by M = 8: every 16 codes decode in registers (int5 by pdep) and meet M
activation rows with one load and one FMA each, two weight rows sharing each load at AVX-512, so
from M = 4 the activation loads outnumber the rest of the loop.
- **The prefill grids are compute-bound** at 1.7-1.9 TFLOP/s on the decoded driver, a third of the
FMA peak: the codes are widened to f32 rather than multiplied as int8.
On a busy machine each figure moves by up to 2x between runs; repeat before comparing two.
## Image generation
Qwen-Image 2.1 (`arch/qwenimage21`) generates on the host backend with `--kernels libavx` alone,
no reference library loaded: engine_e2e_test's `qwen_image_generates_on_libavx_alone_as_on_libref`
serves a tiny synthetic pipeline converted to a bf16 and a block-fp8 container, with and without
guidance. A seed repeats its PNG byte for byte, and the picture agrees with libref's at 51-53 dB
PSNR (another seed: 15 dB). The core needed no change for it.
The generator's 18 ops (`avx_gen.cpp`, `avx_gen_attn.cpp`) round where libref rounds, which is
where the upstream bf16 model stores a tensor. The sampler (`randn_lanes`, `flow_euler`), the gated
residual, the lane copies, the shortcuts, `chan_affine`, `timestep_embed` and `to_rgba8` are libref's
bit for bit, held to zero error by the hand-built cases: a seed's noise and every later sampler
state are the same on both host libraries. `flow_euler` keeps libref's two roundings where it
multiplies and adds (`keep`: this plugin is built with `-ffp-contract=fast`). The norms, the
convolution and the attention reduce in other orders and are held to the tolerance table.
- **`conv2d_nhwc`** is GEMMs over bands of patch rows. The weight is re-laid once a launch as
`[cout][kh][kw][cin]`, so a pixel's patch row is k * k channel runs copied back to back; a band
of output rows (at least 8 Mi patch elements and eight times the weight) is one `gemm_nt_into`
call, the bf16 outer-product path where the CPU has AVX512_BF16. A 1 x 1 layer reads x in place;
a layer narrower than one 48-column panel (the decoder's last, 4 channels) computes y^T so the
threads split the pixels.
- **`attn_prefix_self`** is flash attention over each (entry, kv head)'s keys, packed once a launch
into 64-key tiles (the prefix from the paged cache, then the own rows), for kv heads in groups of
at most 64 MiB of tiles. A task is 32 query positions of one kv head; S = Q K^T and O += P V are
`vdpbf16ps` broadcasts against the tile (P rounded to bf16, as attn_dense's bf16 form and
PyTorch's CPU flash attention do) on AVX512_BF16 parts and f32 FMAs elsewhere. The int8 score
form computes libref's exact integer dot products (codes of at most 127 are exact in bf16).
- `qk_norm_rope` gained libref's `gptj_blocks` (the DiT's adjacent pairs, in whole vectors) and
`imrope` (the text encoder's) modes, which Qwen-Image needs.
One thread, microseconds per launch, the model's widths (`rad-avx-bench --op <op>`; libref is not
timed past 2e10 FLOP). The bf16 dot-product ceiling is twice the f32 FMA one, about 700 GFLOP/s a
core at AVX-512:
| op | geometry | libref | scalar | avx | avx2 | avx512 | rate (avx512) |
|---|---|---|---|---|---|---|---|
| conv2d_nhwc | 3x3 1152->1152, 1024 px | - | 1530639 | 401811 | 242491 | **48957** | 500 GFLOP/s |
| conv2d_nhwc | 3x3 576->576, 4096 px | - | 1470642 | 350498 | 205767 | **39526** | 619 GFLOP/s |
| conv2d_nhwc | 3x3 up 2 288->288, 16384 px | - | 1465933 | 343962 | 201592 | **40163** | 609 GFLOP/s |
| conv2d_nhwc | 3x3 144->144, 65536 px | - | 1506985 | 349133 | 194474 | **41631** | 588 GFLOP/s |
| conv2d_nhwc | 3x3 144->4, 262144 px | 1066406 | 192806 | 68558 | 45259 | **35668** | 76 GFLOP/s |
| conv2d_nhwc | 1x1 1152->3456, 1024 px | 3259307 | 497989 | 113977 | 63326 | **13314** | 612 GFLOP/s |
| attn_prefix_self | 1024 rows + 256 prefix, 32 x 128, bf16 | - | 736629 | 171322 | 169915 | **48335** | 444 GFLOP/s |
| attn_prefix_self | the same, int8 scores | - | 1024020 | 224256 | 198774 | **66715** | 322 GFLOP/s |
| attn_prefix_self | 4096 rows + 256, 4 x 128, bf16 | - | 1243625 | 287250 | 282482 | **80237** | 455 GFLOP/s |
| ln_mod | 1024 x 4096 | 53696 | 3490 | 1909 | 1347 | **879** | 19.1 GB/s |
| gate_add | 1024 x 4096 | 48096 | 2974 | 2105 | 1444 | **991** | 25.4 GB/s |
| ln_mod_quant_fp8 | 1024 x 4096, gated | 120492 | 28441 | 23452 | 5227 | **3267** | 9.0 GB/s |
| qk_norm_rope | gptj_blocks, 1024 x 64 heads of 128 | 83241 | 9851 | 4963 | 3851 | **3078** | 10.9 GB/s |
| l2norm_chan | 262144 px x 144, silu | 534042 | 100513 | 50344 | 34219 | **23405** | 6.5 GB/s |
| d2s_add | 576 -> 288, 512 x 512 out | 174944 | 47387 | 42418 | 34430 | **29654** | 12.7 GB/s |
- The convolutions reach 70-88% of the bf16 dot-product ceiling at AVX-512 and 58-70% of the f32
FMA one at AVX2. The 4-channel output layer is f32 dot products over 1296-long patch rows (24% of
the FMA ceiling); it is 0.06% of the decoder's FLOPs.
- The attention reaches 64% of the bf16 ceiling: the softmax between the two products costs about
a fifth of a tile at head width 128. The int8 rows above draw their key scales as unit normals,
so the running maximum moves in most tiles; a model's moves rarely.
- The row ops are not bandwidth-bound: each rounds its row through bf16 two or three times in L1
(the stores libref models), and l2norm_chan divides and takes an exponential per element.
16 threads (`--threads 16`, the 16 cores pinned; other work was running on the machine,
so these vary by about 15%):
| op | geometry | avx512 | avx2 |
|---|---|---|---|
| conv2d_nhwc | 3x3 at 576, 1152, 288 (up 2) | 3.7-4.1 TFLOP/s | 0.48-0.55 TFLOP/s |
| conv2d_nhwc | 3x3 144->144 at the picture's resolution | 3.1-3.9 TFLOP/s | 0.39 TFLOP/s |
| conv2d_nhwc | 1x1 1152->3456 | 6.3 TFLOP/s | 0.71 TFLOP/s |
| attn_prefix_self | bf16 scores, 1024 and 4096 rows | 4.4-5.9 TFLOP/s | 1.5-1.8 TFLOP/s |
| attn_prefix_self | int8 scores | 3.7-4.4 TFLOP/s | 1.4-1.5 TFLOP/s |
| gemm_nt | the DiT's gate_up, bf16, M 1024 | 5.2 TFLOP/s | 0.64 TFLOP/s |
| gemm_nt_q | the same, fp8a8 (block fp8) | 0.31-0.42 TFLOP/s | 0.26 TFLOP/s |
| ln_mod, gate_add | 1024 x 4096 | 92-101 GB/s | |
| ln_mod_quant_fp8, qk_norm_rope | 1024 x 4096 | 33-35 GB/s | |
At AVX2 the convolution and the bf16 GEMM run on the generic driver, which at large M forks one
parallel region per 6- to 16-row block of A: it is a decode-shaped loop, and why their 16-thread
rate there is a fraction of one thread's times sixteen.
**Seconds per denoising step and per image, this machine.** A DiT step is 32 blocks of linears
(13.96 GFLOP a latent row), the attention over the conditioning and the image's rows, and the row
ops (about 2.5 ms a block at 1024 rows). The decoder is about 4.3 TFLOP at 512 x 512 and 17 TFLOP
at 1024 x 1024, plus a few GB of row passes. Estimated from the 16-thread rates above with a 256-key
conditioning and no guidance (guidance doubles the steps' cost):
| picture | container | linears | attention | step | 40 steps + condition + decode |
|---|---|---|---|---|---|
| 512 x 512 (1024 rows) | bf16 | 14.3 TFLOP, 2.8 s | 0.7 TFLOP, 0.15 s | **3.0 s** | **about 2 minutes** |
| 1024 x 1024 (4096 rows) | bf16 | 57 TFLOP, 11 s | 9.3 TFLOP, 1.9 s | **13 s** | **about 9 minutes** |
| 512 x 512 | block fp8 | 14.3 TFLOP, 40 s | 0.2 s | **40 s** | 27 minutes; Turbo's 8 steps 5.5 |
| 1024 x 1024 | block fp8 | 57 TFLOP, 160 s | 2.3 s | **162 s** | 1.8 hours; Turbo's 8 steps 22 |
The fp8 rows are `gemm_nt_q`'s fp8a8 rate, a twelfth to a seventeenth of the bf16 GEMM's here:
its generic driver widens each fp8 weight row to f32 again for every 16-row block of the
activation. With a bf16-pair path for block fp8 the fp8 container would cost about what the bf16
one does. The decoder takes about 1.3 s at 512 x 512 and 5 s at 1024 x 1024, the condition (the
8B text encoder and the DiT over about 100 prompt tokens) about 0.6 s in bf16 and 8 s in fp8.
## Design choices
Each choice below was measured on the platform above. The variants that did not pay are recorded
beside the code.
**Register block** (`gemm_nt` bf16, M=512 N=2048 K=2048; `avx_gemm.cpp`):
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.
3×4 and 4×3 at AVX2 fall to 58 ms against 31-34 around them: 12 accumulators plus 3-4 A vectors
plus one B is 16-17 live registers in a 16-register file, and the spill lands inside the k loop.
Wider in N beats 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.
**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.
**Cache-blocking the A panel gains about 6% on this part**, not the several-fold the traffic
argument predicts, and at M=64 it is slightly worse (2.91 ms against 2.85). The 128 MiB L3 serves
the traffic blocking removes. It is kept because it is never much worse and is the real fix on a
part with 8 MiB of L3.
**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×.
**fp8 decode is branchless exponent reconstruction, not a table gather.** Every fp8 byte is one of
256 floats, but `vpgatherdd` measured 3268 MB/s at AVX2 and 3815 at AVX-512 against 4512 scalar,
because a gather issues one cache line per lane however small the table. The reconstruction
reaches 8294 and 12545 MB/s.
**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.
**The fp8 encode finishes in vector registers.** Computing sixteen lanes with vector integer
arithmetic and then spilling them to a stack array for a scalar loop that tests one mask bit each
costs about twice the vector form: on a normalised activation the mask is all ones every time, so
that loop always runs.
**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.
**Every conversion is vectorised at AVX2 as well as AVX-512.** A level that falls back to the ABI's
scalar converter costs an order of magnitude more than the vector form, not the 2× its width
suggests, and AVX2 is the level most machines 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.
**The scalar top-R selection is single-pass.** The two-pass form (vector max, then find the index)
pays only when the first pass is vector work; at the scalar level it is two passes where one would
do and is slower than libref's. 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.
**Peak kernels are compiled per level.** A peak loop compiled baseline measures SSE2 whatever level
it is nominally for, and every kernel then looks excellent against a ceiling an order of magnitude
too low. So the peak kernels live in the plugin, compiled per level like every other kernel. The
accumulator count matters as much: sixteen accumulators plus two constants is eighteen live vectors
and spills a 16-register file, costing more than the FMA saves, so the AVX and AVX2 peaks use ten.
## Layout
@@ -239,13 +618,21 @@ saves, so the AVX and AVX2 peaks use ten.
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_planes.h weights joined over several planes: the hooks (libref's rules) and readers
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_table.cpp one level's table of entry points, expanded from AVX_OP_LIST; compiled 4x
avx_support.cpp the generic row, the reductions, the top-R step; compiled 4x
avx_planes.cpp a joined row's decode: scaled E4M3 / int8, zero-point u2 / u4 / u5; 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_{elementwise,norm,hc,quant,gemm,attn,qsa,moe,gdn,sample,misc}.cpp the kernels; compiled 4x
avx_gen.cpp the image generator's norms, sampler, lanes and decoder ops; compiled 4x
avx_gen_attn.cpp attn_prefix_self, the generator's attention; compiled 4x
avx_harness.h plugin loading, row selection, the operand draw, guarded buffers, 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.h what the checker's files share: the comparison, the threaded rerun
avx_check.cpp rad-avx-check: schemas, coverage, the table, the conversions, the levels
avx_check_hand.cpp rad-avx-check's hand-built cases
avx_check_rows.cpp rad-avx-check's file-backed embed_lookup_q case
avx_bench.cpp rad-avx-bench
+330 -309
View File
File diff suppressed because it is too large. Load diff
+947 -88
View File
File diff suppressed because it is too large. Load diff
+444 -129
View File
@@ -1,32 +1,22 @@
/* avx_cases.cpp -- the geometry table both harnesses run.
/* avx_cases.cpp -- the geometry table both harnesses run (one table, so the bench and the checker
* cannot drift apart; tools/opshapes.h does the same for rad-kbench and rad-tune).
*
* 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.
* Values are chosen to break hand-vectorised kernels, not for realism (a real n_embd would make the
* checker take minutes and find nothing a 640-wide row does not):
*
* 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:
* Rows wider than any vector (16 floats at AVX-512), so the main body runs at every level.
* Rows that are not a multiple of it, where tails, masked stores and scalar loops can disagree:
* 645 % 16 == 5, 645 % 8 == 5, 259 % 16 == 3.
* More than one row, to catch a kernel that computes row 0 and broadcasts it.
* M = 1, 7 and 65 on the GEMMs: decode, a speculative verify window, and one row past any
* register-block edge.
* Both sides of every option: `causal`, bounded and unbounded `window`, `norm`, both `a_order`
* spellings, both rope `mode`s.
*
* 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.
* Ops run in f32 (tight tolerance: only summation order may differ) and in bf16 (narrowing).
*
* 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.
* `bytes` and `flops` feed the bench's rate columns and stay 0 where the cost is not a simple
* function of the geometry (in-place samplers, draw-dependent scatters).
*/
#include "avx_harness.h"
@@ -35,7 +25,7 @@ std::vector<Case> build_cases() {
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. */
/* Bytes moved by an elementwise op over `rows` x `n`, `w` bytes per element, `k` streams. */
auto EB = [](double rows, double n, double w, double k) { return rows * n * w * k; };
for (const char* dt : { "f32", "bf16", "f16" }) {
@@ -77,13 +67,28 @@ std::vector<Case> build_cases() {
add("clamp", { HI("M", 7), HI("n", 645), HS("dtype", dt) }, EB(7, 645, w, 2));
add("rmsnorm", { HI("M", 5), HI("n", 645), HF("eps", 1e-6), HS("dtype", dt),
HF("wadd", 0), HF("mult", 0.5) }, EB(5, 645, w, 2));
/* The audio subsampler's two geometries, scaled down in time, with and without the
* frame mask, and a segment boundary (cu_div 2: the cu counts finer than the rows). */
/* The audio subsampler's two geometries, scaled down in time: without and with the
* frame mask and a segment boundary (cu_div 2: cu counts in units finer than rows). */
add("conv2d", { HI("M", 24), HI("width", 16), HI("cin", 1), HI("cout", 24), HI("kh", 3),
HI("kw", 3), HI("stride", 2), HI("pad", 1), HS("dtype", dt) });
add("conv2d", { HI("M", 24), HI("width", 8), HI("cin", 20), HI("cout", 12), HI("kh", 3),
HI("kw", 3), HI("stride", 2), HI("pad", 1), HI("cu_div", 2),
HI("valid_stride", 2), HS("dtype", dt) });
/* Qwen3-ASR's: a [mel, time] kernel (time last), a bias and gelu after it; and its
* output projection as a 1 x 16 convolution over the frequency axis. */
add("conv2d", { HI("M", 24), HI("width", 16), HI("cin", 6), HI("cout", 10), HI("kh", 3),
HI("kw", 3), HI("stride", 2), HI("pad", 1), HS("dtype", dt),
HI("t_last", 1), HS("act", "gelu") });
add("conv2d", { HI("M", 8), HI("width", 16), HI("cin", 6), HI("cout", 20), HI("kh", 1),
HI("kw", 16), HI("stride", 1), HI("pad", 0), HS("dtype", dt) });
/* A kernel taller than sixteen rows. */
add("conv2d_unfold", { HI("M", 40), HI("width", 4), HI("cin", 2), HI("kh", 17),
HI("kw", 1), HI("stride", 1), HI("pad", 8), HS("dtype", dt) });
for (int tl : { 0, 1 })
add("conv2d_unfold", { HI("M", 24), HI("width", 16), HI("cin", 6), HI("kh", 3),
HI("kw", 3), HI("stride", 2), HI("pad", 1),
HI("cu_div", 2), HI("valid_stride", 2), HI("t_last", tl),
HS("dtype", dt) });
add("conv1d_dw", { HI("M", 26), HI("n", 645), HI("k", 5), HS("dtype", dt) });
add("conv1d_dw", { HI("M", 24), HI("n", 64), HI("k", 5), HI("cu_div", 4), HS("dtype", dt) });
add("rel_sinusoid", { HI("M", 13), HI("n", 1024), HF("max_timescale", 10000.0),
@@ -96,16 +101,14 @@ std::vector<Case> build_cases() {
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. */
/* Every dtype pair: `cast` carries the narrowing conventions and is checked at 1e-6, i.e.
* exactly. */
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. */
/* The wide residual stream: Qwen4-Exp's gated residual scaled down (hc 4, lowrank 8). `inject`
* on is the trunk case, off the final mixer; they differ in the operand list. */
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) });
@@ -115,7 +118,7 @@ std::vector<Case> build_cases() {
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. */
/* The fp8 form and its Hadamard-rotated variant, 32-wide groups (four per 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) });
@@ -129,14 +132,17 @@ std::vector<Case> build_cases() {
}
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). */
/* Quantisation. 128 is the real grid; 64 tests a second block edge. n = 256 is divisible by
* both, which the had_* forms require (a rotation block may not straddle the row end). */
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_i8g", { HI("M", 5), HI("n", 256), HI("group", group),
HS("dtype", "bf16") }, EB(5, 256, 2, 1.5));
add("quant_act_i8g", { 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),
@@ -155,33 +161,39 @@ std::vector<Case> build_cases() {
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. */
* scale covers four values), f32 activations (still narrowed to bf16), 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. */
/* The plain bf16 activation, with 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. */
/* GEMM. K = 259 is not a multiple of any vector or block width.
*
* gemm_nt_bias's activations run at M = 7 only. The product is computed the same way whatever
* `act` names, and the activation and residual are applied afterwards, element by element, by
* an epilogue with no M blocking (avx_gemm.cpp: gemm_epilogue), so M = 1 and 65 add nothing
* for them; those two keep the plain bias form for the product's own M edges. */
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);
if (M == 7)
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);
}
/* Encoder-sized M at a width that is not a whole number of 48-column panels, with K odd and
* even: 37 rows take the bf16 dot-product path, 133 the outer-product one -- its column edge,
* its zero-paired last k and its five-row tail. */
/* Encoder-sized M with N not a multiple of the 48-column panel, K odd and even: 37 rows take
* the bf16 dot-product path, 133 the outer-product one (column edge, zero-paired last k,
* five-row tail). */
for (const char* dt : { "f32", "bf16" })
for (int M : { 37, 133 })
for (int K : { 259, 64 }) {
@@ -191,23 +203,50 @@ std::vector<Case> build_cases() {
add("gemm_nt_bias", { HI("M", M), HI("N", 100), HI("K", K), HS("dtype", dt),
HS("act", "gelu_tanh") }, 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" })
/* The formats libref describes (ref_shapes.cpp): block fp8, and the int4 and int8 weights
* against quant_act_i8's step-ordered codes. The bias form needs `a_scale`, which fp8a16 (a
* bf16 activation) does not have, so libref declines it there. */
for (const char* dt : { "fp8a8", "fp8a16", "w4a8", "w8a8" })
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);
if (std::strcmp(dt, "fp8a16") != 0)
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. */
/* The int8 trunk (row-major codes, a scale per row per 128 of K on both sides) and OCP-MXFP4
* (e2m1 codes with an E8M0 exponent per 32 of K against the E4M3 activation). */
for (int M : { 1, 65 }) {
add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128),
HS("dtype", "i8a8") }, 0, 2.0 * M * 96 * 256);
add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 32),
HS("dtype", "mxfp4a8") }, 0, 2.0 * M * 96 * 256);
}
/* Block fp8 off the 128 grid: N = 200 gives the weight's scale plane a second, partial block
* row (rows 128..199) and K = 320 a partial last group (256..319). */
for (const char* dt : { "fp8a8", "fp8a16" })
for (int M : { 1, 65 })
add("gemm_nt_q", { HI("M", M), HI("N", 200), HI("K", 320), HI("group", 128),
HS("dtype", dt) }, 0, 2.0 * M * 200 * 320);
add("gemm_nt_q_bias", { HI("M", 7), HI("N", 200), HI("K", 320), HI("group", 128),
HS("dtype", "fp8a8") }, 0, 2.0 * 7 * 200 * 320);
/* The tile drivers' edges (avx_gemm_tile.cpp): K = 1104 is two of the bf16 driver's K chunks
* and three of the f32 one's, the last with a partial group; K = 17408 (the 27B's down) puts
* 490 rows in two or three super-blocks, the last one short. */
for (const char* dt : { "fp8a8", "fp8a16", "i8a8", "mxfp4a8", "w4a8" })
add("gemm_nt_q", { HI("M", 40), HI("N", 100), HI("K", 1104),
HI("group", std::strcmp(dt, "mxfp4a8") ? 128 : 32), HS("dtype", dt) },
0, 2.0 * 40 * 100 * 1104);
add("gemm_nt_q", { HI("M", 490), HI("N", 20), HI("K", 17408), HI("group", 128),
HS("dtype", "fp8a8") }, 0, 2.0 * 490 * 20 * 17408);
for (const char* dt : { "f32", "bf16" })
add("gemm_nt", { HI("M", 40), HI("N", 100), HI("K", 1104), HS("dtype", dt) }, 0,
2.0 * 40 * 100 * 1104);
add("gemm_nt", { HI("M", 250), HI("N", 20), HI("K", 17408), HS("dtype", "bf16") }, 0,
2.0 * 250 * 20 * 17408);
/* The gated form, which libref describes at fp8a8 only. N is the weight's rows, so the output
* is N/2 = 96 wide. */
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),
@@ -224,9 +263,8 @@ std::vector<Case> build_cases() {
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. */
/* Attention. q_len 1 is decode, 17 a ragged verify window, 64 the prefill panel form
* (q_len >= 32, uniform). `window` 0 is unbounded, 8 sliding (a different loop bound). */
for (const char* dt : { "f32", "bf16" })
for (int qlen : { 1, 17, 64 })
for (int window : { 0, 8 })
@@ -239,23 +277,45 @@ std::vector<Case> build_cases() {
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), HI("window", 0) });
/* The sliding window both ways: bidirectional |i - j| < 5 and causal i - j < 5, over
* segments longer than the window so both bounds bite. */
/* The sliding window both ways (bidirectional |i - j| < 5, causal i - j < 5), over segments
* longer than the window. */
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), HI("window", 5) });
/* Gemma 4's audio attention: left 12 over segments longer than the window. */
/* Blocks: each segment cut into blocks of 7 rows that attend within themselves (a chunked
* encoder's windows), the last block of a segment short. */
for (const char* dt : { "f32", "bf16" })
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 1), HI("causal", 0),
HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24),
HI("block", 7) });
for (const char* dt : { "f32", "bf16" })
add("seg_sinusoid", { HI("M", 30), HI("n", 64), HI("period", 13), HS("dtype", dt) });
/* Gemma 4's audio attention: left 12, over segments longer than the window. */
for (const char* dt : { "f32", "bf16" })
for (int cd : { 1, 4 })
add("attn_local_rel", { HI("M", 40), HI("head_dim", 32), HI("n_head", 3),
HI("left", 12), HI("right", 0), HF("softcap", 50.0),
HI("cu_div", cd), HS("dtype", dt) });
/* An fp8 cache under bf16 queries, as --kv-cache-dtype fp8 serves: decode and a ragged verify
* window, unbounded and sliding. */
for (int qlen : { 1, 17 })
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", "bf16"), HS("kv_dtype", "fp8_e4m3"),
HF("scale", 0.125), HI("max_ctx", 128), HI("n_head", 8),
HI("max_seqs", 2) });
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) });
/* The fp8 store divides by the reader's descales; one below 1 and one above. */
for (double ks : { 0.5, 2.0 })
add("kv_store", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2),
HI("block_size", 16), HS("kv_dtype", "fp8_e4m3"), HF("k_scale", ks),
HF("v_scale", 1.0 / ks) });
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),
@@ -268,13 +328,22 @@ std::vector<Case> build_cases() {
HS("mode", mode), HI("rotary_dim", 64), HF("wadd", 0),
HI("v_norm", 1) });
}
/* `blocks`, the two-component vision form: x over the first half, y over the second, the
* components named in the other order from the planes. */
/* `blocks`, the two-component vision form: x over the first half, y over the second, with the
* components listed in the opposite order to the position planes. */
for (const char* dt : { "f32", "bf16" }) {
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 4),
HF("theta", 100.0), HF("eps", 1e-6), HS("mode", "blocks"),
HS("sections", "16 16"), HS("comps", "1 0"), HI("v_norm", 1),
HS("dtype", dt) });
/* Qwen-Image's two forms over one position component (libref describes no other):
* the DiT's adjacent pairs in one section, and Qwen3-VL's interleaved M-RoPE, which then
* reduces to NeoX pairs. Three components are avx_check_hand.cpp's. */
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 4),
HF("theta", 10000.0), HF("eps", 1e-6), HS("mode", "gptj_blocks"),
HS("sections", "32"), HS("dtype", dt) });
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2),
HF("theta", 5e6), HF("eps", 1e-6), HS("mode", "imrope"),
HI("rotary_dim", 64), HS("sections", "12 10 10"), HS("dtype", dt) });
}
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 10000.0), HF("scale", 1.0),
HS("dtype", "f32") });
@@ -297,8 +366,8 @@ std::vector<Case> build_cases() {
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 1e7), HF("scale", 1),
HS("dtype", "f32"), HF("yarn_factor", 0), HF("yarn_magnitude", magnitude) });
}
/* QSA's compressed key at Flash-Next's geometry (n 128, ratio 4, a 64-wide rotary), stock and
* with YaRN, positions drawn up to the block count times the ratio. */
/* QSA's compressed key at Flash-Next's geometry (n 128, ratio 4, 64-wide rotary), plain and
* with YaRN; positions are drawn up to block count times ratio. */
for (const char* dt : { "f32", "bf16" }) {
add("qsa_block_key", { HI("M", 12), HI("n", 128), HI("ratio", 4), HI("rotary_dim", 64),
HF("eps", 1e-6), HF("theta", 1e7), HF("scale", 1), HF("wadd", 1),
@@ -308,8 +377,42 @@ std::vector<Case> build_cases() {
HS("dtype", dt), HF("yarn_factor", 2), HF("yarn_low", 14),
HF("yarn_high", 22), HF("yarn_magnitude", 1.069314718) });
}
/* The rest of the indexer at Flash-Next's geometry (4 heads of 128, ratio 4, a 7-row ring for
* depth 3) with the block count cut to the checker's budget, then the edges: block counts that
* are no multiple of any vector width, one block, several sequences, more rows than a score
* tile, a head width that pads, and a topk that keeps every live block or splits the zeros.
* libref's descriptions draw page ids >= 0, cu from 0 and nc in [0, blocks]; the hand-built
* cases (avx_check_hand.cpp) cover the rest. */
for (const char* dt : { "bf16", "f32" }) {
add("qsa_score", { HI("M", 4), HI("n", 128), HI("heads", 4), HI("blocks", 300),
HI("seqs", 1), HS("dtype", dt) });
add("qsa_tail_store", { HI("M", 5), HI("n", 128), HI("ratio", 4), HI("ring", 7),
HI("seqs", 5), HS("dtype", dt) });
add("qsa_work", { HI("M", 8), HI("n", 128), HI("ratio", 4), HI("ring", 7), HI("seqs", 4),
HI("work", 6), HS("dtype", dt) });
}
add("qsa_score", { HI("M", 7), HI("n", 128), HI("heads", 4), HI("blocks", 37), HI("seqs", 3),
HS("dtype", "bf16") });
add("qsa_score", { HI("M", 19), HI("n", 72), HI("heads", 3), HI("blocks", 41), HI("seqs", 2),
HS("dtype", "f32") });
add("qsa_score", { HI("M", 1), HI("n", 128), HI("heads", 4), HI("blocks", 1), HI("seqs", 1),
HS("dtype", "bf16") });
add("qsa_select", { HI("M", 4), HI("blocks", 300), HI("topk", 32), HI("ratio", 4),
HI("seqs", 1) });
add("qsa_select", { HI("M", 4), HI("blocks", 300), HI("topk", 200), HI("ratio", 4),
HI("seqs", 1) });
add("qsa_select", { HI("M", 3), HI("blocks", 300), HI("topk", 512), HI("ratio", 4),
HI("seqs", 1) });
add("qsa_select", { HI("M", 7), HI("blocks", 129), HI("topk", 16), HI("ratio", 4),
HI("seqs", 3) });
add("qsa_select", { HI("M", 2), HI("blocks", 1), HI("topk", 1), HI("ratio", 3),
HI("seqs", 1) });
add("qsa_tail_store", { HI("M", 3), HI("n", 37), HI("ratio", 2), HI("ring", 2), HI("seqs", 3),
HS("dtype", "f32") });
add("qsa_work", { HI("M", 3), HI("n", 40), HI("ratio", 2), HI("ring", 3), HI("seqs", 3),
HI("work", 3), HS("dtype", "f32") });
/* The proportional ladder: a partial rotary (rotary_dim < head_dim) with `ladder` head, so the
* denominator is head_dim and libavx's answer must agree with libref's on it. */
* frequency denominator is head_dim. */
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),
@@ -317,6 +420,17 @@ std::vector<Case> build_cases() {
}
add("rope_table", { HI("M", 12), HI("rot", 32), HF("theta", 10000.0), HF("scale", 1.0),
HS("dtype", "f32"), HI("head_dim", 64), HS("ladder", "head") });
/* A rotary wider than 1024 (libref takes up to 2048, i.e. 1024 frequencies), plain and with
* contiguous sections, and QSA's key at the same width. */
add("rope", { HI("M", 3), HI("head_dim", 1280), HI("n_head", 1), HI("n_head_kv", 1),
HF("theta", 10000.0), HF("scale", 1.0), HS("mode", "neox"),
HI("rotary_dim", 1280), HS("dtype", "f32") });
add("rope", { HI("M", 3), HI("head_dim", 1280), HI("n_head", 1), HI("n_head_kv", 1),
HF("theta", 10000.0), HF("scale", 1.0), HS("mode", "mrope"),
HI("rotary_dim", 1280), HS("sections", "214 213 213"), HS("dtype", "f32") });
add("qsa_block_key", { HI("M", 3), HI("n", 1280), HI("ratio", 2), HI("rotary_dim", 1280),
HF("eps", 1e-6), HF("theta", 10000.0), HF("scale", 1), HF("wadd", 1),
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" }) {
@@ -327,41 +441,39 @@ std::vector<Case> build_cases() {
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) });
/* Two table sides. A drawn grid is never larger than the table, so enlarging is
/* Two table sides. A drawn grid never exceeds the table, so upscaling is covered by
* avx_check's hand-built case. */
add("grid_embed_aa", { HI("M", 20), HI("n", 72), HI("side", 16), HS("dtype", dt) });
add("grid_embed_aa", { HI("M", 40), HI("n", 72), HI("side", 4), 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. */
/* MoE. Both `a_order` spellings, since the two grouped GEMMs of a routed block use
* different ones. */
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". */
/* The shared-expert fold: `shared`/`shared_gate` are always described, so always
* present; this case uses sigmoid, the one above "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) });
add("pair_argmax", { HI("M", 5), HI("n", 8), 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. */
/* "sorted", not "slot": libref refuses other spellings with RAD_E_UNSUPPORTED. */
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) });
/* `fp8a8`, the block-fp8 grid: libref describes a grouped GEMM's weight scale plane
* only at a dtype that names its grid. */
/* `fp8a8` (block fp8): libref describes a grouped GEMM's scale plane only for a
* dtype that names its grid. */
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", "fp8a8") });
}
/* The two classes at different widths: a gate/up pair whose odd experts are half as wide
/* 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),
@@ -370,9 +482,9 @@ std::vector<Case> build_cases() {
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", "fp8a8") });
/* Four classes at three widths -- a four-rank slice of a five-block expert is two blocks
* of one class and one of each other -- over ten experts, so classes 2 and 3 hold one
* fewer than 0 and 1: the gate/up pair and the down projection. */
/* Four classes at three widths (a four-rank slice of a five-block expert is two blocks of
* one class and one of each other), over ten experts, so classes 2 and 3 hold one fewer
* than 0 and 1; for the gate/up pair and the down projection. */
add("moe_gemm_q_mod4", { HI("M", 9), HI("N", 128), HI("K", 128), HI("N_1", 256),
HI("N_2", 128), HI("N_3", 128), HI("parts", 2),
HI("n_expert", 10), HI("top_k", 2), HI("group", 128),
@@ -383,21 +495,23 @@ std::vector<Case> build_cases() {
HS("dtype", "fp8a8") });
}
add("moe_scatter", { HI("M", 9), HI("n_expert", 8), HI("top_k", 2), HI("expert_base", 0) });
/* The draft head's rerank: f32 and bf16 activations over an f32 head, the whole vocabulary on
* this rank and a shard of it (candidates below vocab_off become pads). */
for (const char* dt : { "f32", "bf16" })
add("logit_rerank", { HI("M", 5), HI("R", 8), HI("n_vocab", 300), HI("n_embd", 259),
HI("vocab_off", 0), HS("dtype", dt) });
add("logit_rerank", { HI("M", 3), HI("R", 16), HI("n_vocab", 64), HI("n_embd", 128),
HI("vocab_off", 100), HS("dtype", "f32") });
/* 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.
/* Gated delta net. head_k = head_v = 32 and chunk 8 keep the states small enough to inspect
* while running every loop the 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_head_k`, `n_head_v` and `n_seq` are not op parameters: the gdn ops read head counts from
* their operands, so libref's shape hook cannot size them cold and declines without these
* hints (tools/opshapes.h takes the same three, as `ShapeCtx`, from container metadata).
* Without them every gdn case would be skipped.
*
* `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. */
* `n_seq` is 2 so that a wrong `cu` walk differs 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) });
@@ -422,50 +536,135 @@ std::vector<Case> build_cases() {
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. */
/* Collectives at world_size 1, the only width libavx serves. */
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. */
/* Sampling. n_vocab 517 exceeds every vector width and is not a multiple of any; n_cand 12 is
* a realistic candidate set after 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) });
/* k 7 and 20 (OpenAI's top_logprobs bound) against 517: the one-pass set starts full after
* seven columns, and an offset shard reports global ids. */
/* k 7 and 20 (OpenAI's top_logprobs bound) against 517 columns; the offset case checks that
* a shard reports global ids. */
for (int64_t k : { 7, 20 })
add("sample_logprobs", { HI("M", 5), HI("n_vocab", 517), HI("k", k), HI("vocab_off", 0) });
add("sample_logprobs", { HI("M", 3), HI("n_vocab", 517), HI("k", 5), HI("vocab_off", 1000) });
/* sample_merge_topk has no table case: libref cannot describe its packed (id, logit) words
* (ref_shapes.cpp), so avx_check_hand.cpp builds them. */
for (const char* op : { "sample_topp", "sample_minp", "sample_typical", "sample_xtc",
"sample_pick", "sample_merge_topk" })
"sample_pick" })
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. */
/* The drafter's walk: every step after the first reads its predecessor from the walk. Rank 64
* is whole vectors at every level, 37 is not; anchor stride 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") });
/* DFlash2's convolution: the 27B drafter's form (2 taps, groups of 16) over a narrower row,
* then groups that are no multiple of a vector, three taps and a one-row block. f16 rows take
* the path through f32 copies, bf16 and f32 the fused one. */
for (const char* dt : { "bf16", "f32" })
add("dflash_conv", { HI("T", 16), HI("hidden_size", 640), HI("taps", 2),
HI("group_size", 16), HI("NG", 40), HI("block_size", 4),
HS("dtype", dt) });
add("dflash_conv", { HI("T", 11), HI("hidden_size", 36), HI("taps", 3), HI("group_size", 4),
HI("NG", 9), HI("block_size", 5), HS("dtype", "f32") });
add("dflash_conv", { HI("T", 6), HI("hidden_size", 48), HI("taps", 2), HI("group_size", 48),
HI("NG", 1), HI("block_size", 1), HS("dtype", "bf16") });
add("dflash_conv", { HI("T", 11), HI("hidden_size", 36), HI("taps", 3), HI("group_size", 4),
HI("NG", 9), HI("block_size", 5), HS("dtype", "f16") });
/* Image generation (Qwen-Image 2.1, arch/qwenimage21), scaled down: the DiT's norms over rows
* that are not a multiple of any vector, the latent's 64 channels in lanes of 16 rows over two
* entries, the decoder's convolutions and shortcuts on the eight-column pictures libref picks
* (a channel count below and above the convolution's 48-column panel, every padding and
* resampling form, and 256 pixels for the bf16 outer-product path), and the DiT's attention:
* 40 rows (one query block and part of a second) against a 37-key prefix (two whole blocks
* and part of a third), both score forms. Several entries, missing blocks and column slices
* are avx_check_hand.cpp's. */
static const std::string kMul = [] {
std::string s;
for (int i = 0; i < 67; ++i) s += (i ? " " : "") + std::to_string(0.9 + 0.013 * i);
return s;
}();
static const std::string kAdd = [] {
std::string s;
for (int i = 0; i < 67; ++i) s += (i ? " " : "") + std::to_string(0.017 * i - 0.5);
return s;
}();
for (const char* dt : { "f32", "bf16" }) {
add("ln_mod", { HI("M", 7), HI("n", 645), HF("eps", 1e-6), HS("dtype", dt) },
EB(7, 645, dt[0] == 'f' ? 4 : 2, 2));
add("gate_add", { HI("M", 7), HI("n", 645), HS("dtype", dt) },
EB(7, 645, dt[0] == 'f' ? 4 : 2, 3));
for (int gated : { 1, 0 })
add("ln_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-6), HI("group", 128),
HI("gated", gated), HS("dtype", dt) });
for (int round : { 1, 0 })
add("timestep_embed", { HI("M", 3), HI("n", 256), HF("scale", 1000.0),
HF("max_period", 10000.0), HI("round", round),
HS("dtype", dt) });
add("lane_gather", { HI("M", 24), HI("n", 64), HI("stride", 16), HI("n_seq", 2),
HS("dtype", dt) });
add("lane_store", { HI("M", 12), HI("n", 64), HI("stride", 16), HS("dtype", dt) });
add("randn_lanes", { HI("M", 24), HI("n", 64), HI("stride", 16), HI("n_seq", 2),
HS("dtype", dt) });
add("flow_euler", { HI("M", 24), HI("n", 64), HI("stride", 16), HS("dtype", dt) });
for (const char* mode : { "fma", "inv" })
add("chan_affine", { HI("M", 9), HI("n", 67), HS("mul", kMul.c_str()),
HS("add", kAdd.c_str()), HS("mode", mode), HS("dtype", dt) });
for (const char* act : { "silu", "none" })
add("l2norm_chan", { HI("M", 9), HI("n", 645), HS("act", act), HS("dtype", dt) });
add("to_rgba8", { HI("M", 9), HI("n", 4), HS("dtype", dt) });
add("gelu_tanh", { HI("M", 6), HI("n", 645), HS("dtype", dt) });
add("scatter_add_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) });
struct Conv { int M, cin, cout, k, stride, up; const char* pad; };
static const Conv kConv[] = {
{ 64, 20, 24, 3, 1, 1, "same" }, { 64, 20, 52, 3, 1, 1, "same" },
{ 64, 4, 52, 3, 1, 1, "same" }, { 64, 20, 52, 1, 1, 1, "same" },
{ 64, 20, 12, 1, 1, 1, "same" }, { 64, 20, 52, 3, 2, 1, "down" },
{ 64, 20, 52, 3, 1, 2, "same" }, { 64, 20, 4, 3, 1, 1, "same" },
{ 256, 20, 52, 3, 1, 1, "same" },
};
for (const Conv& v : kConv)
add("conv2d_nhwc", { HI("M", v.M), HI("cin", v.cin), HI("cout", v.cout), HI("k", v.k),
HI("stride", v.stride), HS("pad", v.pad), HI("up", v.up),
HS("dtype", dt) },
0, 2.0 * v.M * v.cout * v.cin * v.k * v.k);
for (int ft : { 1, 2 }) {
add("d2s_add", { HI("M", 64), HI("cin", 24), HI("cout", 24), HI("ft", ft),
HS("dtype", dt) });
add("d2s_add", { HI("M", 64), HI("cin", 48), HI("cout", 24), HI("ft", ft),
HS("dtype", dt) });
add("s2d_avg_add", { HI("M", 64), HI("cin", 24), HI("cout", 24), HI("ft", ft),
HS("dtype", dt) });
add("s2d_avg_add", { HI("M", 64), HI("cin", 12), HI("cout", 24), HI("ft", ft),
HS("dtype", dt) });
}
for (const char* qk : { "bf16", "i8" })
for (int causal : { 0, 1 })
for (int hd : { 64, 72 })
add("attn_prefix_self", { HI("q_len", 40), HI("head_dim", hd), HI("gqa", 2),
HI("block_size", 16), HI("causal", causal),
HS("q_dtype", dt), HS("kv_dtype", dt),
HF("scale", 1.0 / std::sqrt((double)hd)),
HI("n_head", 4), HS("qk", qk) });
}
/* ================================================================== 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.
* Timed by rad-avx-bench, skipped by rad-avx-check. The cases above are sized to break kernels;
* speed depends on the cache hierarchy and needs real shapes.
*
* 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.
* Geometry of 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.
*
* `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. */
* `logits_gemm` at 32000 x 2048 is memory-bound: its 128 MiB bf16 weight fits no cache, so
* compare it with the DRAM triad, not the FMA ceiling. */
auto speed = [&](const char* op, std::vector<P> p, double bytes, double flops) {
c.push_back(Case{ op, std::move(p), bytes, flops, true });
};
@@ -475,7 +674,7 @@ std::vector<Case> build_cases() {
speed("gemm_nt", { HI("M", M), HI("N", 5632), HI("K", 2048), HS("dtype", "bf16") },
0, 2.0 * M * 5632 * 2048);
}
/* An encoder step: every token of the batch at once, at EmbeddingGemma 2's two FFN shapes. */
/* An encoder step (all tokens at once) at EmbeddingGemma 2's two FFN shapes. */
for (int M : { 2048 }) {
speed("gemm_nt", { HI("M", M), HI("N", 4096), HI("K", 512), HS("dtype", "bf16") },
0, 2.0 * M * 4096 * 512);
@@ -493,13 +692,14 @@ std::vector<Case> build_cases() {
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("quant_act_i8g", { 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. */
/* GDN at qwen35 model shape (k128/v128, chunk 64, 16 key heads, 48 value heads): chunk_scan
* over a 512 chunk (prefill) and recurrent_update at q_len 1 (decode). No rate: the traffic
* depends on the state layout. libref runs these scalar, so 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);
@@ -516,7 +716,7 @@ std::vector<Case> build_cases() {
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. */
/* Conv update at decode shape: one new token per 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);
@@ -525,15 +725,13 @@ std::vector<Case> build_cases() {
speed("sample_argmax", { HI("M", 1), HI("n_vocab", 32000) }, (double)32000 * 4, 0);
speed("sample_logprobs", { HI("M", 1), HI("n_vocab", 32000), HI("k", 20) }, (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. */
/* Decode attention over a real context: 16 query heads in groups of 4, 2048 cached keys. */
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. */
/* No rate: the KV bytes read depend on the context length drawn into `seqused`,
which this table does not control. */
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),
@@ -541,6 +739,43 @@ std::vector<Case> build_cases() {
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);
/* Qwen3.8-Flash-Next's indexer (arch/qwen4exp_fp8: 4 heads of 128, ratio 4, topk 512, a
* 7-row ring at depth 3) over 8K, 64K and 200K tokens of context: decode at one query and at
* one sequence's four verify rows, and a 2048-token prefill chunk at 64K. Decode streams the
* bf16 block keys (256 bytes a block), so it is rated in GB/s; the prefill chunk is FMA work.
* The bench sets every block complete and every query past all of them (avx_bench.cpp:
* model_shape). Page ids are drawn at random, which a block table need not be in practice. */
for (const int64_t blocks : { 2048, 16384, 50000 })
for (const int64_t M : { 1, 4 })
speed("qsa_score", { HI("M", M), HI("n", 128), HI("heads", 4), HI("blocks", blocks),
HI("seqs", 1), HS("dtype", "bf16") },
(double)blocks * (128 * 2 + 4) + (double)M * blocks * 4, 0);
speed("qsa_score", { HI("M", 2048), HI("n", 128), HI("heads", 4), HI("blocks", 16384),
HI("seqs", 1), HS("dtype", "bf16") },
0, 2.0 * 2048 * 4 * 128 * 16384);
for (const int64_t blocks : { 2048, 16384, 50000 })
for (const int64_t M : { 1, 4 })
speed("qsa_select", { HI("M", M), HI("blocks", blocks), HI("topk", 512),
HI("ratio", 4), HI("seqs", 1) },
(double)M * blocks * 8, 0);
speed("qsa_select", { HI("M", 2048), HI("blocks", 16384), HI("topk", 512), HI("ratio", 4),
HI("seqs", 1) }, 2048.0 * 16384 * 8, 0);
/* The tail and the work list: four decoding sequences, and a prefill chunk's volume (512
* sequences of four rows each completing a block, 2048 key rows staged). */
speed("qsa_tail_store", { HI("M", 4), HI("n", 128), HI("ratio", 4), HI("ring", 7),
HI("seqs", 4), HS("dtype", "bf16") }, 4.0 * 128 * 2 * 2, 0);
speed("qsa_work", { HI("M", 4), HI("n", 128), HI("ratio", 4), HI("ring", 7), HI("seqs", 4),
HI("work", 5), HS("dtype", "bf16") }, 4.0 * 4 * 128 * 2 * 2, 0);
speed("qsa_work", { HI("M", 2048), HI("n", 128), HI("ratio", 4), HI("ring", 7),
HI("seqs", 512), HI("work", 513), HS("dtype", "bf16") },
2048.0 * 128 * 2 * 2, 0);
/* The 27B DFlash2 drafter's convolution (arch/common/rad_block_dflash2.h: n_embd 5120, 2
* taps, groups of 16, a 16-row query block): one sequence's block and four. */
for (const int64_t T : { 16, 64 })
speed("dflash_conv", { HI("T", T), HI("hidden_size", 5120), HI("taps", 2),
HI("group_size", 16), HI("NG", 320), HI("block_size", 16),
HS("dtype", "bf16") },
(double)T * 5120 * 2 * 2 + (double)T * 2 * 320 * 2 + 2.0 * 5120 * 2, 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"),
@@ -550,5 +785,85 @@ std::vector<Case> build_cases() {
HF("scale", 1.0), HS("mode", "neox"), HI("rotary_dim", 128),
HF("wadd", 0) }, 0, 0);
/* Qwen-Image 2.1 (docs/ARCHITECTURES.md): the VAE decoder's widths 1152..144 and the DiT's
* 32 heads of 128 over 4096 rows. Each case is about 25 GFLOP so a one-thread run stays
* practical; libref is not timed past 2e10 (rad-avx-bench). A 512 x 512 picture's decoder
* runs its 1152-wide convolutions at 32 x 32 pixels, its 576-wide ones at 128 x 128 and its
* 144-wide ones at 512 x 512; the cases cut the pixels to keep the width (libref describes an
* eight-column picture, the same work per pixel). */
struct ConvSpeed { int64_t M, cin, cout, k, up; };
static const ConvSpeed kConvSpeed[] = {
{ 1024, 1152, 1152, 3, 1 }, /* mid block and up block 0, at 32 x 32 */
{ 4096, 576, 576, 3, 1 }, /* up block 2 */
{ 16384, 288, 288, 3, 2 }, /* up block 3's upsampler, nearest 2x then 3 x 3 */
{ 65536, 144, 144, 3, 1 }, /* up block 4, at the picture's resolution */
{ 262144, 144, 4, 3, 1 }, /* conv_out at 512 x 512: four output channels */
{ 1024, 1152, 3456, 1, 1 }, /* the middle attention's qkv, 1 x 1 */
};
for (const ConvSpeed& v : kConvSpeed)
speed("conv2d_nhwc", { HI("M", v.M), HI("cin", v.cin), HI("cout", v.cout), HI("k", v.k),
HI("stride", 1), HS("pad", "same"), HI("up", v.up),
HS("dtype", "bf16") },
0, 2.0 * (double)v.M * v.cout * v.cin * v.k * v.k);
/* The denoising attention: an image's 1024 latent rows (512 x 512) against a 256-key
* conditioning, all 32 heads; 4096 rows (1024 x 1024) over four heads (the cost is per head,
* and four heads of 128 query blocks fill the threads). Both score forms. */
for (const char* qk : { "bf16", "i8" }) {
speed("attn_prefix_self", { HI("q_len", 1024), HI("head_dim", 128), HI("gqa", 1),
HI("block_size", 16), HI("causal", 0), HS("q_dtype", "bf16"),
HS("kv_dtype", "bf16"), HF("scale", 0.08838834764831845),
HI("n_head", 32), HI("ctx", 256), HS("qk", qk) },
0, 4.0 * 1024 * (1024 + 256) * 128 * 32);
speed("attn_prefix_self", { HI("q_len", 4096), HI("head_dim", 128), HI("gqa", 1),
HI("block_size", 16), HI("causal", 0), HS("q_dtype", "bf16"),
HS("kv_dtype", "bf16"), HF("scale", 0.08838834764831845),
HI("n_head", 4), HI("ctx", 256), HS("qk", qk) },
0, 4.0 * 4096 * (4096 + 256) * 128 * 4);
}
/* The DiT's row ops over a 512 x 512 picture's 1024 rows of 4096, and the decoder's at its
* last level (512 x 512 pixels): bytes are the operands' reads and writes. */
speed("ln_mod", { HI("M", 1024), HI("n", 4096), HF("eps", 1e-6), HS("dtype", "bf16") },
1024.0 * 4096 * 2 * 2, 0);
speed("gate_add", { HI("M", 1024), HI("n", 4096), HS("dtype", "bf16") },
1024.0 * 4096 * 2 * 3, 0);
speed("ln_mod_quant_fp8", { HI("M", 1024), HI("n", 4096), HF("eps", 1e-6), HI("group", 128),
HI("gated", 1), HS("dtype", "bf16") },
1024.0 * 4096 * (2 * 3 + 1), 0);
speed("qk_norm_rope", { HI("M", 1024), HI("head_dim", 128), HI("n_head", 32),
HI("n_head_kv", 32), HF("theta", 10000.0), HF("eps", 1e-6),
HS("mode", "gptj_blocks"), HS("sections", "64"),
HS("dtype", "bf16") }, 1024.0 * 64 * 128 * 2 * 2, 0);
speed("l2norm_chan", { HI("M", 262144), HI("n", 144), HS("act", "silu"), HS("dtype", "bf16") },
262144.0 * 144 * 2 * 2, 0);
speed("d2s_add", { HI("M", 262144), HI("cin", 576), HI("cout", 288), HI("ft", 1),
HS("dtype", "bf16") }, 262144.0 * 288 * 2 * 2 + 65536.0 * 576 * 2, 0);
/* Qwen3.6-35B-A3B's routed experts in block fp8 (256 experts of 512 at top 8 over n_embd
* 2048): gate|up in two parts with the token-order activation, down with the sorted one. The
* bytes are the experts a call routes to at most, top_k * M of them. */
for (int M : { 1, 8, 512 }) {
const double ex = std::min(256.0, 8.0 * M);
speed("moe_gemm_q", { HI("M", M), HI("N", 1024), HI("K", 2048), HI("parts", 2),
HI("n_expert", 256), HI("top_k", 8), HI("group", 128),
HS("a_order", "token"), HS("dtype", "fp8a8") },
ex * 1024 * 2048, 2.0 * M * 8 * 1024 * 2048);
speed("moe_gemm_q", { HI("M", M), HI("N", 2048), HI("K", 512), HI("n_expert", 256),
HI("top_k", 8), HI("group", 128), HS("a_order", "sorted"),
HS("dtype", "fp8a8") },
ex * 2048 * 512, 2.0 * M * 8 * 2048 * 512);
}
/* Flash-Next's gated residual read (n 2560, hc 4, lowrank 320) at decode, a verify window and
* a prefill chunk; the bytes are the two mixing matrices in bf16, read once per launch. */
for (int M : { 1, 4, 512 })
speed("hc_read", { HI("M", M), HI("n", 2560), HI("hc", 4), HI("lowrank", 320),
HF("eps", 1e-6), HS("dtype", "bf16"), HF("wadd", 1), HI("inject", 1),
HI("group", 128), HI("rotate", 0) },
2.0 * 2 * 320 * 10240, 2.0 * 2 * M * 320 * 10240);
/* The DiT's feed-forward gate_up over 1024 rows, as the bf16 and the block-fp8 containers
* hold it: 61% of a block's FLOPs are in its three feed-forward products. */
speed("gemm_nt", { HI("M", 1024), HI("N", 12288), HI("K", 4096), HS("dtype", "bf16") }, 0,
2.0 * 1024 * 12288 * 4096);
speed("gemm_nt_q", { HI("M", 1024), HI("N", 12288), HI("K", 4096), HI("group", 128),
HS("dtype", "fp8a8") }, 0, 2.0 * 1024 * 12288 * 4096);
return c;
}
+593 -819
View File
File diff suppressed because it is too large. Load diff
+64
View File
@@ -0,0 +1,64 @@
/* avx_check.h -- what rad-avx-check's translation units share: the run's settings, the value
* comparison and the parallel rerun. */
#ifndef RAD_AVX_CHECK_H
#define RAD_AVX_CHECK_H
#include "avx_harness.h"
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
/* One run: the oracle, the library under test, and what it is held to. */
struct Check {
const Lib* ref = nullptr;
const Lib* lib = nullptr;
/* The library under test is libavx and is held to libavx's contract: every op libref
* implements (avx_check.cpp lists those not yet implemented), and the file-backed gather of
* embed_lookup_q with its init. Any other host library is checked op for op against libref, and what it does not
* implement is reported rather than failed. */
bool own = false;
/* Team size of the parallel rerun (avx_par_force), or 0 for none. */
int threads = 0;
bool verbose = false;
double tol_override = -1;
/* Only this op, or every op when empty. */
std::string only_op;
};
/* rad-kbench's error metric: 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;
};
Err compare(const float* got, const float* ref, int64_t n);
/* One output buffer of `n` elements of `dt`, the library's against the oracle's. Token and row ids
* (i32, u32, i64) must match exactly: widened to f32, two ids above 2^24 can compare equal and an
* off-by-one under the relative tolerance passes. Everything else is held to `tol` in rel_l2 with
* the finiteness pattern first. Returns false with the reason in `why`; `rel` gets the error. */
bool same_values(uint32_t dt, const void* ref, const void* got, int64_t n, double tol,
double* rel, std::string* why);
/* The serial run's outputs against a rerun with every parallel region forced to `threads` team
* threads (avx_par_force). libavx partitions only outer loops and never reduces across threads
* (avx_common.h), so the rerun must reproduce every byte. `outs` are the output buffers and
* `bytes` their sizes; `reset` restores every output and in-out buffer to its pre-launch bytes and
* `launch` runs the library's kernel once. Returns false with the reason in `why`. */
bool parallel_rerun(const Lib& lib, int threads, const std::vector<uint8_t*>& outs,
const std::vector<size_t>& bytes, const std::function<void()>& reset,
const std::function<int()>& launch, std::string* why);
/* The hand-built cases (avx_check_hand.cpp). Returns false on any failure, having printed it. */
bool hand_cases(const Check& ck);
/* embed_lookup_q over a file-backed table in `dir`, with two ranks and the reader racing, for
* `calls` calls whose ids are drawn from `seed` (avx_check_rows.cpp). Each table is written once
* per process and kept mapped, so later calls reuse it. */
bool row_gather_case(const Lib& lib, const std::string& dir, int64_t calls, uint64_t seed,
bool verbose, bool bf16);
/* embed_lookup_q's init with io_uring refused, and in this process (avx_check_rows.cpp). */
bool ngram_init_case(const Lib& lib);
#endif /* RAD_AVX_CHECK_H */
File diff suppressed because it is too large. Load diff
+160 -94
View File
@@ -1,31 +1,32 @@
/* avx_check_rows.cpp -- embed_lookup_q over a FILE-BACKED table, the form a model serves it in.
/* avx_check_rows.cpp -- embed_lookup_q over a file-backed table, as a model serves it.
*
* 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.
* The geometry table checks the op against libref over a heap buffer. A table in a container is
* read differently: through a shared row cache, direct file reads for misses and a reader thread
* one call ahead (avx_ngram.cpp). The failures there are about which bytes arrive (a slot claimed
* twice, a row decoded from a slot taken over, a wait on an abandoned claim), and libref has no
* such path, so the reference 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.
* Two threads act as ranks 0 and 1 of 2 over the same ids, released together, so each claims rows,
* waits on the other's claims and meets its own claim again when an id repeats. Half the ids come
* from a small hot set; 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. Each call also passes the next
* call's ids as `ahead`, so the reader thread races both ranks.
*
* 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`, and the filesystem
* there decides how the gather aligns its direct reads: by the alignment the filesystem reports
* (ext4, XFS), or by its block size where it reports none (btrfs, and a tmpfs since Linux 6.6). The
* case says which it ran. */
#include "avx_harness.h"
* Each output row is compared bit for bit with the file's bytes through the call's scale; a padding
* id must give a zero row. Rows are 40 codes, so the AVX-512 decode runs one 32-code step plus a
* masked tail. Direct reads align to the filesystem's reported DIO alignment (ext4, XFS) or to its
* block size where none is reported (btrfs, tmpfs since Linux 6.6); the case reports which.
*
* Each table is written once per process under a name of its own (mkostemp), stays mapped for the
* rest of the process and is unlinked once the gather has opened it: the ISA levels share the file
* reads and differ only in the decode. */
#include "avx_check.h"
#include <barrier>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <map>
#include <thread>
#include <cstddef>
@@ -41,16 +42,30 @@
#include <sys/wait.h>
#include <unistd.h>
/* EMBED_LOOKUP_Q'S INIT REFUSES A PROCESS THAT MAY NOT MAKE AN io_uring RING, and says why: Docker's
* default seccomp profile answers EPERM to io_uring_setup, and a server started that way used to
* load the whole model and then fail every request as "unsupported". A child process installs the
* same refusal as a seccomp filter and asks the kernel's init, which must refuse a gather into
* bf16 -- the one that reads through the ring -- name the Docker option on stderr, and accept a
* gather into f32, which reads the table as memory. Then this process asks: it must accept where a
* ring can be made and refuse where it cannot, as in a build sandbox. */
bool ngram_init_case(const Lib& avx) {
/* The errno of creating a ring as the gather does (avx_ngram.cpp: ReadRing::init), or 0. */
static int ring_probe() {
io_uring_params p{};
p.flags = IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN;
const long ring = syscall(__NR_io_uring_setup, 4096, &p);
if (ring < 0) return errno;
::close((int)ring);
return 0;
}
/* Ring memory can count against the locked-memory limit, which every process of the user shares,
* so a run beside other io_uring users can be refused one (ENOMEM) for a while. That is the
* machine, not the gather: the cases name it and skip. */
static const char* const kRingMemory = "io_uring ring memory refused (ENOMEM); the locked-memory "
"limit is shared with this user's other processes";
/* embed_lookup_q's init must refuse a process that cannot create an io_uring ring, and say why
* (Docker's default seccomp profile returns EPERM for io_uring_setup). A child installs that
* refusal as a seccomp filter; init must then refuse a bf16 gather (read through the ring), name
* the Docker option on stderr, and accept an f32 gather (read as memory). This process must then be
* accepted where a ring can be created and refused where it cannot, as in a build sandbox. */
bool ngram_init_case(const Lib& lib) {
const char* what = "embed_lookup_q's init";
const RadKernelInfo* r = avx.row("embed_lookup_q");
const RadKernelInfo* r = lib.row("embed_lookup_q");
if (!r || !r->init) {
std::printf(" %s: the row has no init\n", what);
return false;
@@ -114,53 +129,43 @@ bool ngram_init_case(const Lib& avx) {
std::printf(" %s, where io_uring is refused: refused, naming the Docker option\n", what);
}
io_uring_params p{};
const long ring = syscall(__NR_io_uring_setup, 1, &p);
const bool here = ring >= 0;
if (here) ::close((int)ring);
/* The init tests the ring once per process, so the probes bracket it. */
const int before = ring_probe();
void* inst = nullptr;
const int st = r->init(bf16, 2, 0, 1, &inst);
const int after = ring_probe();
if (st == RAD_E_UNSUPPORTED && (before == ENOMEM || after == ENOMEM)) {
std::printf(" %s, in this process: SKIPPED -- %s\n", what, kRingMemory);
return ok;
}
const bool here = before == 0;
const bool right = here ? st == RAD_OK : st == RAD_E_UNSUPPORTED;
std::printf(" %s, in this process (io_uring %s): %s\n", what, here ? "available" : "refused",
right ? (here ? "accepted" : "refused") : "FAIL");
return ok && right;
}
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;
/* A table file, written and mapped once per process. */
struct RowTable {
enum { OK, SKIP, FAIL } state = FAIL;
std::string path, note; /* note: the skip or failure reason, or the read granule */
const uint8_t* tab = nullptr;
bool unlinked = false;
};
const std::string path = dir + "/rad-avx-check-rows.bin";
static RowTable* row_table(const std::string& dir, bool bf16, int64_t V, int64_t rb) {
static std::map<std::pair<std::string, bool>, RowTable> tables;
const auto key = std::make_pair(dir, bf16);
if (auto it = tables.find(key); it != tables.end()) return &it->second;
RowTable& t = tables[key];
/* A name of its own, so a concurrent run cannot truncate the file under this one's mapping. */
std::string path = dir + "/rad-avx-check-rows.XXXXXX";
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; }
const int fd = ::mkostemp(path.data(), O_CLOEXEC);
if (fd < 0) { t.note = "cannot create " + path; return &t; }
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)) {
@@ -170,13 +175,11 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool
}
wrote = wrote && ::fsync(fd) == 0;
::close(fd);
if (!wrote) { ::unlink(path.c_str()); std::printf(" %s: short write\n", what);
return false; }
if (!wrote) { ::unlink(path.c_str()); t.note = "short write"; return &t; }
}
/* A filesystem without direct I/O -- one that refuses the open, as a tmpfs did before Linux
* 6.6, or one that reports the file has none -- is one the gather refuses by design, so the
* case cannot run there; it says so rather than counting a refusal per call. Every other
* filesystem the gather has to read, with or without a reported alignment. */
/* The gather refuses a filesystem without direct I/O (the O_DIRECT open fails, as on tmpfs
* before Linux 6.6, or it reports a zero DIO alignment), so the case is skipped there. Every
* other filesystem must work, with or without a reported alignment. */
bool reported = false;
{
const int dfd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC | O_DIRECT);
@@ -188,18 +191,62 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool
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;
t.state = RowTable::SKIP;
t.note = dir + " cannot do direct I/O";
return &t;
}
}
const char* granule = reported ? "the alignment the filesystem reports"
: "no alignment reported, read by the block size";
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);
if (map == MAP_FAILED) { ::unlink(path.c_str()); t.note = "mmap"; return &t; }
/* The mapping stays for the life of the process. libavx resolves a table to its file once, by
* the mapping's address range (avx_ngram.cpp: table_file), so no other file may be mapped at
* these addresses while the process runs. */
t.tab = static_cast<const uint8_t*>(map);
t.path = path;
t.note = reported ? "the alignment the filesystem reports"
: "no alignment reported, read by the block size";
t.state = RowTable::OK;
return &t;
}
bool row_gather_case(const Lib& lib, const std::string& dir, int64_t calls, uint64_t seed,
bool verbose, bool bf16) {
const RadKernelInfo* r = lib.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 has twice the row bytes and no scale, so it exercises the cache and the reads
* at a row size the E4M3 table never has. */
/* Misses are io_uring reads. Where a sandbox forbids io_uring the gather refuses every call by
* design, so the case is skipped with the reason. */
if (const int e = ring_probe()) {
std::printf(" %s: SKIPPED -- %s\n", what,
e == ENOMEM ? kRingMemory
: (std::string("io_uring is unavailable here (") +
std::strerror(e) + ")").c_str());
return true;
}
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;
RowTable* rt = row_table(dir, bf16, V, rb);
if (rt->state == RowTable::SKIP) {
std::printf(" %s: SKIPPED -- %s\n", what, rt->note.c_str());
return true;
}
if (rt->state != RowTable::OK) {
std::printf(" %s: %s\n", what, rt->note.c_str());
return false;
}
const char* granule = rt->note.c_str();
const uint8_t* tab = rt->tab;
uint64_t x = seed ? seed : 1;
auto rnd = [&x]() { x ^= x << 13; x ^= x >> 7; x ^= x << 17; return x; };
std::vector<int32_t> hotset((size_t)hot);
for (auto& h : hotset) h = (int32_t)(rnd() % (uint64_t)V);
@@ -229,7 +276,8 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool
};
std::barrier<> go(2);
int64_t bad[2] = {0, 0}, refused[2] = {0, 0};
int64_t bad[2] = {0, 0}, refused[2] = {0, 0}, failed[2] = {0, 0};
/* Each rank thread makes its own ring on its first call. */
auto rank = [&](int rk) {
uint16_t sc = rad_f32_to_bf16(scale);
std::vector<uint16_t> out((size_t)(M * n));
@@ -248,11 +296,15 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool
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. */
/* The last call passes no `ahead` (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; }
if (const int rc = r->launch(&a, nullptr); rc != RAD_OK) {
++refused[rk];
if (rc != RAD_E_UNSUPPORTED) ++failed[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) {
@@ -264,19 +316,33 @@ bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool
}
}
};
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());
auto race = [&] {
bad[0] = bad[1] = refused[0] = refused[1] = failed[0] = failed[1] = 0;
std::thread t0(rank, 0), t1(rank, 1);
t0.join();
t1.join();
};
/* Calls refused as unsupported with every delivered row right mean a ring the kernel would
* not make. Under contention for ring memory the case runs again on fresh threads, which make
* fresh rings, up to three times; it is skipped by name only if a probe saw ENOMEM meanwhile.
* Refusals without that evidence fail. */
bool pressure = false;
for (int attempt = 0; attempt < 3; ++attempt) {
race();
const bool ring_refused = refused[0] + refused[1] && bad[0] + bad[1] == 0 &&
failed[0] + failed[1] == 0;
if (!ring_refused) break;
if (ring_probe() == ENOMEM) pressure = true;
}
/* The gather holds its own descriptor from the first call on, so the name can go. */
if (!rt->unlinked) {
::unlink(rt->path.c_str());
rt->unlinked = true;
}
if (pressure && refused[0] + refused[1] && bad[0] + bad[1] + failed[0] + failed[1] == 0) {
std::printf(" %s: SKIPPED -- %s\n", what, kRingMemory);
return true;
}
const bool pass = bad[0] + bad[1] + refused[0] + refused[1] == 0;
if (verbose || !pass)
+138 -127
View File
@@ -1,31 +1,20 @@
/* avx_common.h -- what every kernel in this plugin needs and the ABI does not give it.
/* avx_common.h -- helpers every kernel in this plugin needs that the ABI does not provide.
*
* 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:
* rad_plugin.h already has the parameter readers, the absent-operand rule, the row-pitch helper
* and the narrowing conversions. This header adds three things:
*
* 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.
* Scratch arena. Every kernel converts rows to f32 before computing (avx_vec.h), so it needs row
* scratch. RadArgs::scratch does not fit: it is one buffer sized at declare, while the outer loop
* runs under OpenMP with a thread count unknown at declare. A thread_local arena grows to a
* high-water mark and is reused, so the hot path does not allocate (libref does the same).
*
* 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.
* Operand addressing. Every extent comes from a RadTensor, never from a parameter: a ranged
* parameter is collapsed to a band, so a loop bounded by `M` would run to the band's upper bound
* and walk off the arena (libref/ref_ops.h).
*
* 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.
* Threading. OpenMP over the outer dimension only, one thread owning whole output rows, no
* reduction() clause. Results are bit-identical across thread counts, so two runs of the same
* binary agree regardless of machine load and measurements stay comparable.
*/
#ifndef RAD_AVX_COMMON_H
#define RAD_AVX_COMMON_H
@@ -38,24 +27,44 @@
#include <cstring>
#include <cmath>
/* Scalar transcendentals as libref evaluates them: in double, rounded once to float. glibc's float
* routines differ between releases (2.41 made log1pf, tanhf and erff correctly rounded), so a float
* call would agree with libref on one host and not on another; the double routines are stable,
* and the rounded float is the same everywhere. The vector paths (avx_vec.h) are checked to a
* tolerance and do not use these. */
static inline float sc_exp(float x) { return (float)std::exp((double)x); }
static inline float sc_log(float x) { return (float)std::log((double)x); }
static inline float sc_log1p(float x) { return (float)std::log1p((double)x); }
static inline float sc_tanh(float x) { return (float)std::tanh((double)x); }
static inline float sc_erf(float x) { return (float)std::erf((double)x); }
static inline float sc_sin(float x) { return (float)std::sin((double)x); }
static inline float sc_cos(float x) { return (float)std::cos((double)x); }
static inline float sc_pow(float b, float e) { return (float)std::pow((double)b, (double)e); }
#ifdef _OPENMP
#include <omp.h>
#include <sched.h>
#include <atomic>
#include <cstdio>
#include <cstdlib>
/* THE TEAM IS ONE THREAD A PHYSICAL CORE, not one a logical CPU. These kernels are FMA- or
* bandwidth-bound, so an SMT sibling adds next to nothing to them -- and the engine runs threads
* of its own beside the team (a worker per stream, the scheduler, the HTTP server). A team as
* wide as the logical CPU count leaves those nowhere to run but on a core a team thread is
* spinning on, and a team barrier then waits for a descheduled thread: measured on a 16-core,
* 32-thread part, an encoder step of 576 tokens took 0.75 s at 32 threads and 0.09 s at 16.
* Counted over the process's affinity mask, so a pinned or containerised engine sizes its team to
* what it was given; OMP_NUM_THREADS, when set, is the operator's and wins, and a thread that
* asked OpenMP for fewer (omp_set_num_threads) gets fewer. */
/* The checker's override, set through avx_par_force (avx_isa.h): 0, or the team size every
* parallel region takes whatever its work threshold. Defined in avx_dispatch.cpp; one relaxed load
* per region. */
extern std::atomic<int> avx_par_threads;
static inline bool avx_par_forced() {
return avx_par_threads.load(std::memory_order_relaxed) > 0;
}
/* One team thread per physical core, not per logical CPU. These kernels are FMA- or
* bandwidth-bound, so an SMT sibling adds little, and the engine runs its own threads (stream
* workers, scheduler, HTTP server) beside the team. A team as wide as the logical CPU count makes
* team barriers wait on descheduled threads: on a 16-core, 32-thread part a 576-token encoder
* step takes 0.75 s at 32 threads and 0.09 s at 16. Cores are counted over the process affinity
* mask, so a pinned or containerised engine uses what it was given. OMP_NUM_THREADS, when set,
* wins, and a thread that asked for fewer (omp_set_num_threads) gets fewer. */
static inline int avx_team_size() {
/* The physical core count is a property of the process and counted once; the OpenMP request
* is the calling thread's and read every time, so a caller that asks for fewer threads
* (omp_set_num_threads, as the benchmark does for its single-thread figures) gets them. */
if (const int forced = avx_par_threads.load(std::memory_order_relaxed); forced > 0)
return forced;
/* The core count is per process and computed once; the OpenMP request is per calling thread
* and read on every call (the benchmark lowers it for single-thread figures). */
static const int cores = [] {
if (const char* e = std::getenv("OMP_NUM_THREADS"); e && *e) return 0;
cpu_set_t set;
@@ -83,15 +92,13 @@ static inline int avx_team_size() {
}
#define AVX_PRAGMA(x) _Pragma(#x)
#define AVX_PARALLEL_FOR AVX_PRAGMA(omp parallel for schedule(static) num_threads(avx_team_size()))
/* 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. */
/* Parallelise the outer loop only when the work pays for a fork/join, which costs a few
* microseconds; `rad-avx-bench --threads` measures the crossover. `cond` is pasted into the
* pragma text, so it must contain no comma. avx_par_force overrides it, so the checker runs every
* parallel body with several threads at its small geometries. */
#define AVX_PARALLEL_FOR_IF(cond) \
AVX_PRAGMA(omp parallel for schedule(static) if(cond) num_threads(avx_team_size()))
AVX_PRAGMA(omp parallel for schedule(static) if((cond) || avx_par_forced()) \
num_threads(avx_team_size()))
#else
#define AVX_PARALLEL_FOR
#define AVX_PARALLEL_FOR_IF(cond)
@@ -107,58 +114,20 @@ namespace avx {
* 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. */
/* Independent second and third buffers, for kernels with several rows live at once (gate and up,
* a and b, x and residual). */
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.
* Copied from libref/ref_common.h and must stay identical. They are the addressing contract:
* where element (r, i) lives, how a rank-3 tensor reads as [rows, cols], and what a strided view
* means. Diverging here fails the oracle check in a way that looks like a numerical bug.
*
* `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. */
* `numel` returns 0 for a null-data tensor; libref's shape checks rely on that to refuse an absent
* required operand. */
static inline int64_t numel(const RadTensor* t) {
if (!t || !t->data || t->rank == 0) return 0;
int64_t n = 1;
@@ -188,9 +157,9 @@ static inline int64_t offlin(const RadTensor* t, int64_t lin) {
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. */
/* Element offset of logical row `r` read as [rows, cols]. Leading axes use their own strides, so
* a [T, H, V] tensor read as [T*H, V] is correct even when H's stride is not V (the
* fused-projection column slice in docs/OPS.md). */
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;
@@ -207,17 +176,17 @@ static inline int64_t rowoff(const RadTensor* t, int64_t r, int64_t 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. */
/* The operand's row count, with the ranged parameter as a ceiling (libref/ref_common.h:
* band_rows). `M`, `numel` and `q_len` arrive as the band's upper bound, so the count comes from
* the operand; a count above the band is a caller bug and yields 0. */
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. */
/* Block size implied by a scale grid of `blocks` pieces over `ext` elements (libref/ref_gemm.h:
* grid_block): the power of two whose ceiling division gives `blocks`, not ext / blocks, because
* the 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;
@@ -227,11 +196,10 @@ static inline int64_t grid_block(int64_t ext, int64_t blocks) {
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. */
/* Stride between rows of `cols` elements, at any rank (libref/ref_gemm.h's rule). Rank 2 does not
* imply dense: attention receives a column slice of the fused QKV plane, [tokens, kv_heads *
* head_dim] with the full projection width as row stride, so the stride must not be derived from
* the shape. */
static inline int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
int64_t span = 1;
@@ -243,15 +211,13 @@ static inline int64_t row_stride(const RadTensor* t, int64_t cols) {
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. */
/* One element as f32 and back:
* - Packed codes. rad_load_f32 returns 0 for W4, W2 and MXFP4 (an unreadable dtype is a
* refusal), so strided or odd-offset reads of packed weights decode here, with libref's codes
* (ref_common.h: w4_code, w2_code, mxfp4_code), the same ones row_to_f32 unpacks in bulk.
* - Integer and packed-code stores to the dtypes listed in st_elem round to the nearest code and
* saturate, NaN storing 0, as libref's st_dt does; every other dtype (u16, bool, the floats)
* is rad_store_f32's. */
static inline float ld_elem(const void* p, uint32_t dt, int64_t i) {
switch (dt) {
case RAD_I4: {
@@ -282,16 +248,46 @@ static inline double round_sat(float v, double lo, double hi) {
return r < lo ? lo : (r > hi ? hi : r);
}
/* A packed code's low `bits` into element `i` of a bit stream, lowest bits first. The atomics
* touch only this element's bits, so rows written by different threads may share a byte. */
static inline void st_packed(void* p, int64_t i, int bits, unsigned c) {
const int per = 8 / bits;
uint8_t* b = (uint8_t*)p + i / per;
const int sh = (int)(i % per) * bits;
const uint8_t mask = (uint8_t)(((1u << bits) - 1u) << sh);
__atomic_fetch_and(b, (uint8_t)~mask, __ATOMIC_RELAXED);
__atomic_fetch_or(b, (uint8_t)((c << sh) & mask), __ATOMIC_RELAXED);
}
/* The e2m1 code nearest `v`, ties to the even code, saturating at 6; NaN is +0 (libref's). */
static inline unsigned e2m1_code(float v) {
static const float kMag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
if (v != v) return 0u;
const unsigned sign = std::signbit(v) ? 8u : 0u;
const float a = std::fabs(v);
unsigned best = 0;
for (unsigned c = 1; c < 8; ++c) {
const float d = std::fabs(kMag[c] - a), db = std::fabs(kMag[best] - a);
if (d < db || (d == db && (c & 1u) == 0u)) best = c;
}
return sign | best;
}
static inline void st_elem(void* p, uint32_t dt, int64_t i, float v) {
switch (dt) {
/* Packed codes: the nearest code, saturated, so a code ld_elem read stores back as itself
* (a gather or scatter of packed rows moves them exactly). */
case RAD_I4: st_packed(p, i, 4, (unsigned)(int)round_sat(v, -8.0, 7.0) & 0xFu); break;
case RAD_I2: st_packed(p, i, 2, (unsigned)(int)round_sat(v, -2.0, 1.0) & 0x3u); break;
case RAD_FP4E2M1: st_packed(p, i, 4, e2m1_code(v)); break;
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. */
/* 2^63 is the first float past the int64 range, so it is tested by comparison
* rather than used as a clamp value. */
const double r = round_sat(v, -9223372036854775808.0, 9223372036854775808.0);
((int64_t*)p)[i] = r >= 9223372036854775808.0 ? INT64_MAX : (int64_t)r;
break;
@@ -305,18 +301,31 @@ 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. */
/* `v` rounded through a store and load of dtype `dt` (libref's round_dt). */
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);
}
/* True when the row's elements are contiguous. A dense row converts with one call and is read as
* a flat f32 array; any other row goes through the strided gather. Nearly every operand is dense;
* docs/OPS.md names the exceptions. */
static inline bool dense_row(const RadTensor* t) { return laststride(t) == 1; }
/* The gemm_nt_q dtypes whose activation is quant_act_i8's, codes in the int8 WMMA's step order
* (libref/ref_common.h). */
static inline bool i8_steps_dtype(const char* dt) {
static const char* const kDtypes[] = { "w4a8", "w4a8_asym", "w8a8", "w2a8" };
for (const char* d : kDtypes)
if (dt && std::strcmp(dt, d) == 0) return true;
return false;
}
/* ================================================================== 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. */
* Laxer than rad_param_geti, as in libref: a tool or test may call a launch directly with no
* declare to enforce the type, so a range or a string spelling of an integer is read rather than
* refused. */
static inline const RadParam* p_find(const RadArgs* a, const char* k) {
return a ? rad_param_find(a->p, a->n_p, k) : nullptr;
}
@@ -347,6 +356,8 @@ static inline float p_f32(const RadArgs* a, const char* k, float dflt) {
return dflt;
}
/* An enumerated parameter spelled as a name or libr4d's integer; an unknown name is -1, for the
* caller to refuse (as libref). */
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);
@@ -354,7 +365,7 @@ static inline int p_enum(const RadArgs* a, const char* k, const char* const* nam
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;
return -1;
}
if (p->kind == RAD_P_INT) return (int)p->ival;
return dflt;
@@ -388,8 +399,8 @@ static inline void st_int_dt(uint32_t dt, void* p, int64_t i, int64_t v) {
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. */
/* Address of the byte holding element i, for dtypes whose element is not a whole byte. Packed
* codes are otherwise read through row_to_f32; `dequant` uses this to address 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) {
+87 -101
View File
@@ -1,33 +1,15 @@
/* avx_dispatch.cpp -- the one translation unit that may not contain a vector instruction.
/* avx_dispatch.cpp -- ISA detection and level selection; must contain no vector instruction.
*
* ============================== THE RULE THIS FILE EXISTS TO ENFORCE ==============================
* Every other object in the plugin is built with -mavx/-mavx2/-mavx512f and may only execute once
* this file has established that the CPU supports it. So this file is built with no -m flags, set
* as a target property in CMakeLists.txt. Avoiding intrinsics is not enough: under -mavx512f the
* compiler may auto-vectorise anything, such as the table copies below, and a SIGILL here would
* hit before main on exactly the machines the fallback is for.
*
* 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.
* Detection uses __builtin_cpu_supports, which also reads XCR0 via XGETBV: the OS must enable
* YMM/ZMM/mask state, and a VM or older kernel may leave it off while CPUID still reports AVX-512.
* AVX-512 needs F, BW, DQ and VL together: BW for the byte and word shuffles of the bf16 pack, DQ
* for the 64-bit integer forms, VL for the 128/256-bit encodings.
*/
#include "avx_isa.h"
#include "avx_common.h"
@@ -35,15 +17,14 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <atomic>
#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. */
* Built at load from the ABI's converters rather than typed out, so they cannot drift from
* rad_fp8e4m3_to_f32 / rad_fp8e5m2_to_f32. */
extern "C" { float avx_fp8e4m3_tab[256] = { 0 };
float avx_fp8e5m2_tab[256] = { 0 }; }
@@ -54,31 +35,34 @@ static void fp8_tables_init(void) {
}
}
/* ================================================================== detection */
static int g_detected = -1;
static int g_level = -1;
/* ================================================================== detection
* Atomics, since the first launches may run on several threads at once; every racer computes the
* same values. */
static std::atomic<int> g_detected{-1};
static std::atomic<int> g_level{-1};
extern "C" int avx_isa_detect(void) {
if (g_detected >= 0) return g_detected;
static int detect(void) {
#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;
return AVX_LEVEL_AVX512;
if (__builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma") &&
__builtin_cpu_supports("f16c"))
return AVX_LEVEL_AVX2;
if (__builtin_cpu_supports("avx")) return AVX_LEVEL_AVX;
return 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;
/* Not x86: the scalar level is a full implementation, just slow; rad_plugin_info().build_target
* reports "host". */
return AVX_LEVEL_SCALAR;
#endif
return g_detected;
}
extern "C" int avx_isa_detect(void) {
int d = g_detected.load(std::memory_order_relaxed);
if (d < 0) g_detected.store(d = detect(), std::memory_order_relaxed);
return d;
}
extern "C" const char* avx_isa_name(int level) {
@@ -100,44 +84,59 @@ extern "C" const AvxKernelTable* avx_table_for(int level) {
}
}
static const AvxKernelTable* g_tab = 0;
static std::atomic<const AvxKernelTable*> g_tab{nullptr};
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;
const AvxKernelTable* t = g_tab.load(std::memory_order_acquire);
if (t) return t;
const int level = avx_isa_detect();
g_level.store(level, std::memory_order_relaxed);
t = avx_table_for(level);
g_tab.store(t, std::memory_order_release);
return t;
}
extern "C" int avx_isa_level(void) {
if (g_level < 0) (void)avx_table_live();
return g_level;
if (g_level.load(std::memory_order_relaxed) < 0) (void)avx_table_live();
return g_level.load(std::memory_order_relaxed);
}
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. */
/* Clamp to what the CPU can execute and return the level selected, so a checker can report
* that it ran a lower level than it asked for. */
if (level < 0) level = 0;
if (level > cap) level = cap;
g_level = level;
g_tab = avx_table_for(level);
g_level.store(level, std::memory_order_relaxed);
g_tab.store(avx_table_for(level), std::memory_order_release);
return level;
}
/* ================================================================== the thread override
*
* Every check geometry is below the kernels' parallel thresholds, so without this the checker
* would run each OpenMP body on one thread only. */
#ifdef _OPENMP
std::atomic<int> avx_par_threads{0};
#endif
extern "C" int avx_par_force(int threads) {
#ifdef _OPENMP
if (threads < 0) threads = 0;
avx_par_threads.store(threads, std::memory_order_relaxed);
return threads;
#else
(void)threads;
return 0;
#endif
}
/* ================================================================== 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. */
* One baseline-compiled function per op, pointed at by the registry row, making one indirect call
* into the selected level's table. The rows themselves are not repointed: rad_kernel_at returns
* them as const from a static table, and the loader may read them before rad_plugin_open runs, so
* a row patched in open() would be briefly null. The extra indirect branch 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); \
@@ -147,15 +146,12 @@ AVX_OP_LIST(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.
* One growable arena per thread per slot. Only a call larger than any before it allocates, so the
* hot path is allocation-free.
*
* 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. */
* Aligned to 64 so _mm512_load_ps is legal on it (`new float[]` guarantees only 16). Kernels mostly
* use unaligned loads, which cost nothing extra on aligned addresses since Nehalem, but the GEMM
* packing buffers use aligned stores. */
namespace {
struct Arena {
@@ -164,18 +160,14 @@ struct Arena {
~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. */
/* Grow geometrically so increasing sizes do not realloc every call. 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. */
/* Allocation failure aborts. Callers do not check the result (most run inside an OpenMP
* body that cannot return a status), so returning the old smaller buffer would overflow
* the heap and returning null would fault with no diagnostic. */
if (!q) {
std::fprintf(stderr, "libavx: could not allocate %zu bytes of kernel scratch\n", want);
std::abort();
@@ -198,10 +190,8 @@ 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. */
* The loader resolves these exact names (rad_abi.h); a misspelling would silently skip init and
* leave the fp8 tables zero. The typedef checks below make a signature drift a compile error. */
extern "C" int rad_plugin_open(void) {
fp8_tables_init();
(void)avx_table_live();
@@ -215,15 +205,11 @@ extern "C" void rad_plugin_close(void) {}
/* ================================================================== 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.
* Exported for rad-avx-bench, which is baseline-compiled and cannot emit vector code itself. The
* per-level probes live in avx_support.cpp, built with the kernels' flags, so they measure the
* ceiling the kernels see, including any AVX-512 frequency offset under sustained load.
*
* 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. */
* Returns the FLOPs performed, not a rate; the caller owns the clock and takes the median. */
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);
+234 -170
View File
@@ -1,43 +1,29 @@
/* 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.
/* avx_elementwise.cpp -- add, mul, activations, gated products, row gather/scatter, cast, softmax
* and per-row scaling.
*
* ============================== THESE ARE MEMORY-BOUND, NOT COMPUTE-BOUND ==============================
* These ops are memory-bound: a constant number of touches and a few flops per element.
*
* 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 per row. `in_row`/`out_row` (avx_support.cpp) convert a whole row once
* (returning the operand's own pointer for f32), instead of libref's per-element ld_dt(), whose
* branch blocks vectorisation.
*
* 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.
* Fused forms round where libref rounds. E.g. `softmax` writes the unnormalised exponentials to
* `y`, reads them back through the output dtype and multiplies by 1/sum, so a bf16 result has
* two roundings; `rmsnorm_add` does the same with `residual_out`. Staying in f32 would be half an
* ulp more accurate and disagree with the oracle and the device kernels. The round trip uses a
* hot scratch buffer instead of the output operand.
*
* 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.
* Broadcasting: `mul` broadcasts one row down the rows (a bias's shape); `scale_rows` broadcasts one
* column across them (a per-token gate). They are separate ops because the two readings are
* ambiguous when rows == n, and a wrong guess gives plausible numbers.
*/
#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. */
/* Round a row through an operand's storage dtype and back, as an unfused store-and-reload would.
* A no-op for f32. */
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);
@@ -45,9 +31,8 @@ static inline void roundtrip(uint32_t dt, float* v, int64_t n, void* tmp) {
}
/* ------------------------------------------------------------------ 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. */
/* y = a op b over the output's extent. A one-row `b` is broadcast down the rows; nothing else
* broadcasts, so a shape bug fails instead of producing plausible numbers. */
template <bool MUL>
static int elementwise2(const RadArgs* a) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
@@ -90,7 +75,7 @@ AVX_KERNEL(mul_weight) {
if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE;
const bool scalar = numel(W) == 1;
if (!scalar && numel(W) != n) return RAD_E_SHAPE;
/* The gain, widened once: it is the same row for every row of x. */
/* Widened once; the same row applies to every row of x. */
float* wrow = (float*)scratch_raw((size_t)n * sizeof(float) + 64);
if (scalar) { const float v = ldt(W, 0); for (int64_t i = 0; i < n; ++i) wrow[i] = v; }
else for (int64_t i = 0; i < n; ++i) wrow[i] = ldt(W, i * laststride(W));
@@ -110,26 +95,24 @@ AVX_KERNEL(mul_weight) {
}
/* ------------------------------------------------------------------ act_mul */
/* y = act(a) * b over two operands, libref's contract: the activation is rounded to y's dtype
* before the product, because the unfused pair stores it.
/* y = act(a) * b. As in libref, the activation is rounded to y's dtype before the product,
* because the unfused pair stores it.
*
* silu and gelu_tanh are VECTORISED on vf_exp. An encoder's gated FFN puts this op on every token
* of every layer, and the scalar libm form was 9% of an EmbeddingGemma 2 step on a 9950X3D -- a
* per-element tanhf behind 2048 columns. gelu_tanh keeps the reference's own structure,
* silu and gelu_tanh are vectorised on vf_exp: in an encoder's gated FFN this op runs on every
* token of every layer, and scalar libm made it about 9% of an EmbeddingGemma 2 step. gelu_tanh
* keeps torch's structure,
*
* 0.5 g (1 + tanh z), z = sqrt(2/pi) (g + 0.044715 g^3), tanh z = (1 - e^(-2z)) / (1 + e^(-2z))
*
* and not the algebraically equal g / (1 + e^(-2z)): the two differ by an ulp or two of f32, and
* after the bf16 rounding the rearranged form moved an EmbeddingGemma 2 embedding measurably
* further from transformers' (cosine 0.999919 -> 0.999894 on one input; torch computes this same
* 0.5 g (1 + tanh) in f32). vf_exp saturates rather than overflowing, so the large-|g| limits come
* out as g and 0. erf has no vector form in this plugin, so gelu stays scalar. */
* rather than the algebraically equal g / (1 + e^(-2z)), which differs by an ulp or two and after
* bf16 rounding measurably moves embeddings away from transformers'. vf_exp saturates, so the
* large-|g| limits come out as g and 0. erf has no vector form here, so gelu stays scalar. */
static inline float act_of(int act, float g) {
if (act == 0) return g / (1.0f + std::exp(-g));
if (act == 1) return 0.5f * g * (1.0f + std::erf(g * 0.70710678118654752f));
if (act == 3) return 1.0f / (1.0f + std::exp(-g));
if (act == 0) return g / (1.0f + sc_exp(-g));
if (act == 1) return 0.5f * g * (1.0f + sc_erf(g * 0.70710678118654752f));
if (act == 3) return 1.0f / (1.0f + sc_exp(-g));
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
return 0.5f * g * (1.0f + std::tanh(k0 * (g + k1 * g * g * g)));
return 0.5f * g * (1.0f + sc_tanh(k0 * (g + k1 * g * g * g)));
}
/* sy[0..n) = act(g[0..n)) for silu (0) and gelu_tanh (2); the tail is the scalar form. */
@@ -174,8 +157,8 @@ AVX_KERNEL(act_mul) {
const float* g = in_row(A, rowoff(A, r, n), n, sa);
const float* u = in_row(B, rowoff(B, r, n), n, sb);
act_row(act, g, sy, n);
/* sa is free once the activation is taken (g is either sa or the tensor itself); sb may
* hold u, which the product still reads. */
/* sa is free once the activation is taken (g is sa or the tensor); sb may hold u, which
* is still needed. */
roundtrip(Y->dtype, sy, n, sa);
for (int64_t i = 0; i < n; ++i) sy[i] *= u[i];
out_row(Y, rowoff(Y, r, n), n, sy);
@@ -184,8 +167,8 @@ AVX_KERNEL(act_mul) {
}
/* ------------------------------------------------------------------ relu / clamp */
/* y = max(x, 0), and y = min(max(x, lo), hi) with lo and hi WEIGHTS of one element each (a
* clipped linear's range). Row-wise at each operand's own pitch, like the libref forms. */
/* y = max(x, 0), and y = min(max(x, lo), hi) with lo and hi one-element weights (a clipped
* linear's range). Row-wise at each operand's own pitch, as in libref. */
AVX_KERNEL(relu) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
@@ -231,15 +214,21 @@ AVX_KERNEL(clamp) {
}
/* ------------------------------------------------------------------ conv2d */
/* libref's segment-wise convolution over (time, width), channels innermost. The weight is turned
* once a launch from PyTorch's [cout, cin, kh, kw] into [kh][kw][cin][cout], so each input value is
* broadcast against a contiguous run of output channels: the inner loop is a vector FMA over cout
* rather than a dot product over cin. Same sum (in a different order), one rounding. */
/* libref's segment-wise convolution over (time, width), channels innermost. The weight is
* transposed once per launch from PyTorch's [cout, cin, kh, kw] (or [cout, cin, kw, kh] with
* t_last) to [kh][kw][cin][cout], so the inner loop is a vector FMA over cout rather than a dot
* product over cin. Same sum in a different order plus the optional bias, one rounding; then
* `act` and a second rounding, as libref does. */
AVX_KERNEL(conv2d) {
if (!a || a->n_t < 5 || !a->t[0].data || !a->t[1].data || !a->t[2].data || !a->t[4].data)
return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[4];
const RadTensor* V = a->t[3].data ? &a->t[3] : nullptr;
const RadTensor* B = a->n_t > 5 && a->t[5].data ? &a->t[5] : nullptr;
const bool tlast = p_int(a, "t_last", 0) != 0;
const char* act = p_str(a, "act", "none");
const bool gelu = !std::strcmp(act, "gelu");
if (!gelu && std::strcmp(act, "none")) return RAD_E_UNSUPPORTED;
const int64_t W = p_int(a, "width", 0), cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0);
const int64_t kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0);
const int64_t st = p_int(a, "stride", 1), pad = p_int(a, "pad", 0);
@@ -249,19 +238,25 @@ AVX_KERNEL(conv2d) {
return RAD_E_SHAPE;
const int64_t Wo = (W + 2 * pad - kw) / st + 1;
if (Wo <= 0 || numel(Wt) < cout * cin * kh * kw) return RAD_E_SHAPE;
if (B && numel(B) < cout) return RAD_E_SHAPE;
const int64_t S = numel(cu) - 1;
if (S <= 0) return RAD_E_SHAPE;
const int64_t rin = W * cin, rout = Wo * cout;
const int64_t Min = rows_of(X, rin), Mout = rows_of(Y, rout);
if (Min <= 0 || Mout <= 0 || ldi(cu, offlin(cu, S)) <= ldi(cu, offlin(cu, 0)))
return RAD_E_SHAPE; /* zero rows is not a call (docs/OPS.md) */
float* wt = (float*)scratch_raw((size_t)(kh * kw * cin * cout) * sizeof(float) + 64);
float* wt = (float*)scratch_raw((size_t)(kh * kw * cin * cout + cout) * sizeof(float) + 64);
float* bias = wt + kh * kw * cin * cout;
for (int64_t co = 0; co < cout; ++co) bias[co] = B ? ldt(B, offlin(B, co)) : 0.0f;
const int64_t ws = laststride(Wt);
for (int64_t co = 0; co < cout; ++co)
for (int64_t ci = 0; ci < cin; ++ci)
for (int64_t i = 0; i < kh; ++i)
for (int64_t j = 0; j < kw; ++j)
wt[((i * kw + j) * cin + ci) * cout + co] =
ldt(Wt, (((co * cin + ci) * kh + i) * kw + j) * ws);
ldt(Wt, (tlast ? ((co * cin + ci) * kw + j) * kh + i
: ((co * cin + ci) * kh + i) * kw + j) * ws);
for (int64_t s = 0; s < S; ++s) {
const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1));
@@ -302,15 +297,82 @@ AVX_KERNEL(conv2d) {
}
}
}
if (B)
for (int64_t wo = 0; wo < Wo; ++wo)
for (int64_t co = 0; co < cout; ++co) acc[wo * cout + co] += bias[co];
out_row(Y, rowoff(Y, o0 + to, rout), rout, acc);
if (gelu) {
/* The biased sum as y's dtype holds it, then the activation of the rounded value. */
const float* yr = in_row(Y, rowoff(Y, o0 + to, rout), rout, acc);
for (int64_t e = 0; e < rout; ++e) acc[e] = act_of(1, yr[e]);
out_row(Y, rowoff(Y, o0 + to, rout), rout, acc);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ conv2d_unfold */
/* libref's receptive fields as rows, a copy: each input row is widened once and the taps are
* gathered from it. */
AVX_KERNEL(conv2d_unfold) {
if (!a || 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], *cu = &a->t[1], *Y = &a->t[3];
const RadTensor* V = a->t[2].data ? &a->t[2] : nullptr;
const int64_t W = p_int(a, "width", 0), cin = p_int(a, "cin", 0);
const int64_t kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0);
const int64_t st = p_int(a, "stride", 1), pad = p_int(a, "pad", 0);
const int64_t cdiv = p_int(a, "cu_div", 1), vst = p_int(a, "valid_stride", 1);
const bool tlast = p_int(a, "t_last", 0) != 0;
if (W <= 0 || cin <= 0 || kh <= 0 || kw <= 0 || st <= 0 || pad < 0 || cdiv <= 0 || vst <= 0)
return RAD_E_SHAPE;
const int64_t Wo = (W + 2 * pad - kw) / st + 1, K = cin * kh * kw;
const int64_t S = numel(cu) - 1;
if (Wo <= 0 || S <= 0) return RAD_E_SHAPE;
const int64_t rin = W * cin, Min = rows_of(X, rin), Mout = rows_of(Y, K);
if (Min <= 0 || Mout <= 0 || ldi(cu, offlin(cu, S)) <= ldi(cu, offlin(cu, 0)))
return RAD_E_SHAPE; /* zero rows is not a call (docs/OPS.md) */
for (int64_t s = 0; s < S; ++s) {
const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1));
if (c0 % cdiv || c1 % cdiv || (c0 / cdiv) % st || c1 < c0) return RAD_E_SHAPE;
const int64_t t0 = c0 / cdiv, T = c1 / cdiv - t0;
if (T <= 0) continue;
const int64_t To = (T + 2 * pad - kh) / st + 1, o0 = t0 / st;
if (To <= 0) continue;
if (t0 + T > Min || (o0 + To) * Wo > Mout) return RAD_E_SHAPE;
if (V && numel(V) < (t0 + T - 1) * vst + 1) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(To * Wo * K >= AVX_PAR_MIN)
for (int64_t to = 0; to < To; ++to) {
float* row = scratch_f32((size_t)K);
float* sx = scratch_f32_b((size_t)(kh * rin));
const float** xr = (const float**)scratch_raw((size_t)kh * sizeof(const float*));
for (int64_t i = 0; i < kh; ++i) {
const int64_t ti = to * st - pad + i, tg = t0 + ti;
const bool ok = ti >= 0 && ti < T && !(V && ldi(V, offlin(V, tg * vst)) == 0);
xr[i] = ok ? in_row(X, rowoff(X, tg, rin), rin, sx + i * rin) : nullptr;
}
for (int64_t wo = 0; wo < Wo; ++wo) {
for (int64_t i = 0; i < kh; ++i)
for (int64_t j = 0; j < kw; ++j) {
const int64_t wi = wo * st - pad + j;
const float* xv = xr[i] && wi >= 0 && wi < W ? xr[i] + wi * cin : nullptr;
for (int64_t ci = 0; ci < cin; ++ci) {
const int64_t k = tlast ? (ci * kw + j) * kh + i : (ci * kh + i) * kw + j;
row[k] = xv ? xv[ci] : 0.0f;
}
}
out_row(Y, rowoff(Y, (o0 + to) * Wo + wo, K), K, row);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ conv1d_dw */
/* libref's causal depthwise convolution over time, the weight turned to [k][C] once a launch so
* a row is a vector FMA per tap. */
/* libref's causal depthwise convolution over time. The weight is transposed to [k][C] once per
* launch so each tap is a vector FMA over the row. */
AVX_KERNEL(conv1d_dw) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[3];
@@ -319,6 +381,8 @@ AVX_KERNEL(conv1d_dw) {
const int64_t S = numel(cu) - 1;
if (S <= 0) return RAD_E_SHAPE;
const int64_t Mx = rows_of(X, C), My = rows_of(Y, C);
if (Mx <= 0 || My <= 0 || ldi(cu, offlin(cu, S)) <= ldi(cu, offlin(cu, 0)))
return RAD_E_SHAPE; /* zero rows is not a call (docs/OPS.md) */
float* wt = (float*)scratch_raw((size_t)(K * C) * sizeof(float) + 64);
for (int64_t c = 0; c < C; ++c)
@@ -352,7 +416,7 @@ AVX_KERNEL(conv1d_dw) {
}
/* ------------------------------------------------------------------ rel_sinusoid */
/* libref's table, to the operation: the same f32 steps and the same libm calls. */
/* libref's table, with the same f32 steps and libm calls. */
AVX_KERNEL(rel_sinusoid) {
if (!rad_args_have(a, 1)) return RAD_E_INVAL;
const RadTensor* Y = &a->t[0];
@@ -368,19 +432,53 @@ AVX_KERNEL(rel_sinusoid) {
for (int64_t d = 0; d < rows; ++d) {
float* sy = scratch_f32((size_t)n);
for (int64_t i = 0; i < h; ++i) {
const float inv = std::exp((float)i * -inc);
const float inv = sc_exp((float)i * -inc);
const float ang = (float)d * inv;
sy[i] = std::sin(ang);
sy[h + i] = std::cos(ang);
sy[i] = sc_sin(ang);
sy[h + i] = sc_cos(ang);
}
out_row(Y, rowoff(Y, d, n), n, sy);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ seg_sinusoid */
/* libref's per-segment table, to the operation: position (r - start) mod period. */
AVX_KERNEL(seg_sinusoid) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *cu = &a->t[0], *Y = &a->t[1];
const int64_t n = p_int(a, "n", 0), period = p_int(a, "period", 0), cdiv = p_int(a, "cu_div", 1);
if (n <= 0 || n % 2 || period <= 0 || cdiv <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n), S = numel(cu) - 1;
if (rows <= 0 || S <= 0 || ldi(cu, offlin(cu, S)) <= ldi(cu, offlin(cu, 0)))
return RAD_E_SHAPE; /* zero rows is not a call (docs/OPS.md) */
const int64_t h = n / 2;
const double mt = (double)p_f32(a, "max_timescale", 10000.0f);
const float inc = (float)(std::log(mt / 1.0) / (double)(h - 1 > 1 ? h - 1 : 1));
for (int64_t s = 0; s < S; ++s) {
const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1));
if (c0 % cdiv || c1 % cdiv || c1 < c0 || c1 / cdiv > rows) return RAD_E_SHAPE;
const int64_t r0 = c0 / cdiv, r1 = c1 / cdiv;
AVX_PARALLEL_FOR_IF((r1 - r0) * n >= AVX_PAR_MIN)
for (int64_t r = r0; r < r1; ++r) {
float* sy = scratch_f32((size_t)n);
const int64_t p = (r - r0) % period;
for (int64_t i = 0; i < h; ++i) {
const float inv = sc_exp((float)i * -inc);
const float ang = (float)p * inv;
sy[i] = sc_sin(ang);
sy[h + i] = sc_cos(ang);
}
out_row(Y, rowoff(Y, r, n), n, sy);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ seg_mean */
/* One row a cu_seqlens segment: the mean of its rows, summed in double and rounded once, which is
* libref's arithmetic -- a pooled embedding should not depend on which host kernel pooled it. */
/* One output row per cu_seqlens segment: the mean of its rows, summed in double and rounded once,
* as in libref. */
AVX_KERNEL(seg_mean) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *cu = &a->t[1], *Y = &a->t[2];
@@ -388,7 +486,7 @@ AVX_KERNEL(seg_mean) {
const int64_t S = numel(cu) - 1;
if (n <= 0 || S <= 0 || numel(Y) < S * n) return RAD_E_SHAPE;
const int64_t total = ldi(cu, offlin(cu, S));
if (total < 0 || numel(X) < total * n) return RAD_E_SHAPE;
if (total <= 0 || numel(X) < total * n) return RAD_E_SHAPE; /* zero rows is not a call */
AVX_PARALLEL_FOR_IF(S >= 2)
for (int64_t s = 0; s < S; ++s) {
@@ -409,8 +507,8 @@ AVX_KERNEL(seg_mean) {
}
/* ------------------------------------------------------------------ pool_rows */
/* libref's: the mean of each k consecutive rows summed in f32 and rounded to y's dtype, then the
* multiplier and a second rounding -- the unfused pair. Parallel over output rows. */
/* As libref: the mean of each k consecutive rows, summed in f32 and rounded to y's dtype, then the
* multiplier and a second rounding (the unfused pair). Parallel over output rows. */
AVX_KERNEL(pool_rows) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
@@ -441,18 +539,17 @@ AVX_KERNEL(pool_rows) {
}
/* ------------------------------------------------------------------ scale_rows */
/* y[m, i] = x[m, i] * act(s[m]), then + add[m, i] if the optional residual is passed.
/* y[m, i] = x[m, i] * act(s[m]), plus add[m, i] when 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 activation applies to the per-row scalar, as a gate does (Qwen3.5-MoE scales its shared
* expert 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. */
* With a residual, the product is narrowed to y's dtype before the add, as libref (and a fused
* kernel) does by storing the product and reading it back. Done here in a scratch buffer. */
AVX_KERNEL(scale_rows) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
/* `add` (operand 2) is optional; the other three are required. */
if (a->n_t < 4 || !rad_arg_in(a, 0) || !rad_arg_in(a, 1) || !rad_arg_in(a, 3))
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));
@@ -469,10 +566,8 @@ AVX_KERNEL(scale_rows) {
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;
/* One value per row, so use libm's expf as the oracle does, not the vector polynomial. */
const float v = sig ? 1.0f / (1.0f + sc_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);
@@ -496,16 +591,12 @@ AVX_KERNEL(scale_rows) {
}
/* ------------------------------------------------------------------ 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.
/* y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The gate is the first half, the order in
* which rad-convert fuses gate and up into one weight.
*
* 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. */
* A bf16 output uses vf_silu_fast (avx_vec.h): the exact path's ~0.6 ulp is wasted on a store that
* rounds at 3e-3. f32 outputs keep the exact path. Only for ops whose product is consumed once;
* vf_sigmoid feeds gate chains whose errors accumulate. */
AVX_KERNEL(silu_mul) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
@@ -517,23 +608,21 @@ AVX_KERNEL(silu_mul) {
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. */
/* One in_row over the whole 2n row: the halves are adjacent, and one conversion saves a
* call and keeps the prefetcher on one 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. */
/* Keyed on the output dtype (see above). */
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];
sy[i] = (gi / (1.0f + sc_exp(-gi))) * u[i];
}
out_row(y, rowoff(y, r, n), n, sy);
continue;
@@ -544,7 +633,7 @@ AVX_KERNEL(silu_mul) {
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];
sy[i] = (gi / (1.0f + sc_exp(-gi))) * u[i];
}
out_row(y, rowoff(y, r, n), n, sy);
}
@@ -553,11 +642,8 @@ AVX_KERNEL(silu_mul) {
/* ------------------------------------------------------------------ gelu_mul
*
* y[i] = gelu_tanh(gate_up[i]) * gate_up[n + i], the gate the FIRST half exactly as in silu_mul.
* The activation keeps libref's ONE definition of gelu_tanh (act_gelu_tanh, std::tanh): the tree's
* rule for a non-polynomial activation is a single source of truth, so this runs libref's scalar
* formula into the f32 scratch rather than a second vectorised tanh whose agreement with the first
* would be a property of its coefficients -- the same decision the unary gelu above makes. */
* y[i] = gelu_tanh(gate_up[i]) * gate_up[n + i], gate first as in silu_mul. Uses libref's scalar
* gelu_tanh formula (act_gelu_tanh, std::tanh) rather than a second, vectorised definition. */
AVX_KERNEL(gelu_mul) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *gu = &a->t[0], *y = &a->t[1];
@@ -568,15 +654,14 @@ AVX_KERNEL(gelu_mul) {
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, as silu_mul does: the halves are adjacent and one
* conversion of 2n beats two of n. */
/* One in_row over the whole 2n row, as in silu_mul. */
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;
for (int64_t i = 0; i < n; ++i) {
const float x = g[i];
const float t = std::tanh(0.7978845608028654f * (x + 0.044715f * x * x * x));
const float t = sc_tanh(0.7978845608028654f * (x + 0.044715f * x * x * x));
sy[i] = 0.5f * x * (1.0f + t) * u[i];
}
out_row(y, rowoff(y, r, n), n, sy);
@@ -586,18 +671,12 @@ AVX_KERNEL(gelu_mul) {
/* ------------------------------------------------------------------ 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.
* These run over the whole tensor, as libref's `unary` does, in fixed L1-sized tiles (the op has
* no row length).
*
* 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. */
* gelu stays scalar on purpose: libref uses libm's erff, and a minimax erf polynomial would be a
* second definition of gelu. The dtype switch is still hoisted. If gelu lands on a hot path, a
* polynomial is the next step (--bench gelu); Qwen and Gemma use silu. */
enum { UN_GELU = 0, UN_SILU = 1, UN_SIGMOID = 2 };
template <int WHICH>
@@ -607,17 +686,16 @@ static int unary(const RadArgs* a) {
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. */
/* Strided: element at a time through `offlin`, as libref does. */
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));
if (WHICH == UN_GELU) o = 0.5f * v * (1.0f + sc_erf(v * 0.70710678118654752f));
else if (WHICH == UN_SILU) o = v / (1.0f + sc_exp(-v));
else o = 1.0f / (1.0f + sc_exp(-v));
stt(y, offlin(y, i), o);
}
return RAD_OK;
@@ -641,9 +719,9 @@ static int unary(const RadArgs* a) {
}
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));
if (WHICH == UN_GELU) so[i] = 0.5f * u * (1.0f + sc_erf(u * 0.70710678118654752f));
else if (WHICH == UN_SILU) so[i] = u / (1.0f + sc_exp(-u));
else so[i] = 1.0f / (1.0f + sc_exp(-u));
}
out_row(y, off, m, so);
}
@@ -655,8 +733,7 @@ AVX_KERNEL(silu) { return unary<UN_SILU>(a); }
AVX_KERNEL(sigmoid) { return unary<UN_SIGMOID>(a); }
/* ------------------------------------------------------------------ fill */
/* y = value over [M, n] at y's own row pitch, the value rounded once by the store. Nothing to
* vectorise that the store does not already do: it is a write of one number. */
/* y = value over [M, n] at y's own row pitch, rounded once by the store. */
AVX_KERNEL(fill) {
if (!rad_args_have(a, 1)) return RAD_E_INVAL;
const RadTensor* y = &a->t[0];
@@ -674,11 +751,9 @@ AVX_KERNEL(fill) {
}
/* ------------------------------------------------------------------ logit_softcap */
/* y = cap * tanh(x / cap). Its own list entry rather than another unary<WHICH>, because WHICH is
* a compile-time choice and `cap` is a runtime parameter -- the template has nowhere to put it.
* The vector path keeps the tree's one definition of the non-polynomial part: tanh(z) is
* 2*sigmoid(2z) - 1, so the work is vf_sigmoid's existing minimax exp plus two multiplies. The
* scalar fallback is libm's tanhf, which is what libref's oracle computes. */
/* y = cap * tanh(x / cap). Not a unary<WHICH> because `cap` is a runtime parameter. The vector
* path uses tanh(z) = 2*sigmoid(2z) - 1 on vf_sigmoid; the scalar tail uses libm's tanhf, as
* libref does. */
AVX_KERNEL(logit_softcap) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
@@ -692,7 +767,7 @@ AVX_KERNEL(logit_softcap) {
AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN)
for (int64_t i = 0; i < nel; ++i) {
const float v = ldt(x, offlin(x, i));
stt(y, offlin(y, i), cap * std::tanh(v / cap));
stt(y, offlin(y, i), cap * sc_tanh(v / cap));
}
return RAD_OK;
}
@@ -706,27 +781,22 @@ AVX_KERNEL(logit_softcap) {
float* s = scratch_f32((size_t)TILE);
float* so = scratch_f32_b((size_t)TILE);
const float* v = in_row(x, off, m, s);
const vf z = vf_set1(2.0f / cap); /* x / cap, doubled: the argument of the sigmoid */
const vf z = vf_set1(2.0f / cap); /* sigmoid argument: 2x / cap */
const vf c2 = vf_set1(2.0f * cap); /* 2*cap * sigmoid(...) */
const vf c1 = vf_set1(-cap); /* ... - cap */
int64_t i = 0;
for (; i + VF_N <= m; i += VF_N)
vf_storeu(so + i, vf_fma(c2, vf_sigmoid(vf_mul(vf_loadu(v + i), z)), c1));
for (; i < m; ++i)
so[i] = cap * std::tanh(v[i] / cap);
so[i] = cap * sc_tanh(v[i] / cap);
out_row(y, off, m, so);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ scale */
/* y = x * s, s a [1] weight broadcast over every element. A plain multiply by a scalar: the
* vector path is vf_mul against a broadcast, and the scalar fallback is a plain multiply. There is
* no non-polynomial part, so nothing is reused from the sigmoid path; it is its own list entry
* (rather than a `mul` with a [1] operand) for the same reason `mul` refuses a scalar broadcast --
* a silent choice between a row-broadcast and a scalar-broadcast is how a shape bug becomes a
* plausible number. The scalar is read once, outside the loop: a per-element reload of a [1]
* tensor is the same value every time and costs a load per element. */
/* y = x * s, with s a [1] weight broadcast over every element. A separate op rather than `mul`
* with a [1] operand, for the reason `mul` refuses a scalar broadcast (see the file header). */
AVX_KERNEL(scale) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *s = &a->t[1], *y = &a->t[2];
@@ -763,10 +833,9 @@ AVX_KERNEL(scale) {
}
/* ------------------------------------------------------------------ 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. */
/* y[i, :] = x[idx[i], :]. A negative index writes a zero row (embed_lookup's padding rule, used
* when a step has fewer rows than the buffer). An index >= x's row count is RAD_E_INVAL, 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];
@@ -779,10 +848,10 @@ AVX_KERNEL(gather_rows) {
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);
/* Matching whole-byte dtypes (the normal case) copy rows bytewise, which is faster than a
* widen/narrow round trip and cannot change the bits. A sub-byte row can start mid-byte. */
const bool same = x->dtype == y->dtype && dense_row(x) && dense_row(y) &&
rad_dtype_bits(x->dtype) % 8 == 0;
const size_t rowb = same ? (size_t)((rad_dtype_bits(x->dtype) * n) / 8) : 0;
AVX_PARALLEL_FOR_IF(M * n >= AVX_PAR_MIN)
@@ -807,10 +876,9 @@ AVX_KERNEL(gather_rows) {
}
/* ------------------------------------------------------------------ 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. */
/* x[idx[i], :] = v[i, :], the mirror of gather_rows. `x` is INOUT and partially written: rows no
* index names keep their contents, and a negative index writes nothing. Indices are distinct by
* contract (RAD_OPD_F_IDX_UNIQUE), so rows can be written by 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];
@@ -823,8 +891,9 @@ AVX_KERNEL(scatter_rows) {
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);
/* Bytewise row copy when the dtypes match, as in gather_rows. */
const bool same = v->dtype == x->dtype && dense_row(v) && dense_row(x) &&
rad_dtype_bits(x->dtype) % 8 == 0;
const size_t rowb = same ? (size_t)((rad_dtype_bits(x->dtype) * n) / 8) : 0;
AVX_PARALLEL_FOR_IF(M * n >= AVX_PAR_MIN)
@@ -844,13 +913,11 @@ AVX_KERNEL(scatter_rows) {
}
/* ------------------------------------------------------------------ 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.
/* Reads the tensors' own dtypes. `from`/`to` exist in the schema for the selector; a mismatch with
* the tensors is a caller bug (as in libref).
*
* 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. */
* Integer-to-integer casts take an integer path, so token ids and block indices above 2^24 are not
* rounded through f32. */
AVX_KERNEL(cast) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
@@ -884,14 +951,11 @@ AVX_KERNEL(cast) {
}
/* ------------------------------------------------------------------ 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.
/* Max-subtracted softmax in f32 over the last n elements of a row. The max subtraction is needed
* (a 60-nat logit range overflows) and every kernel this is checked against does it.
*
* 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. */
* As in libref, the exponentials are rounded through y's dtype before the 1/sum multiply, so a
* bf16 output has two roundings; done here in a scratch buffer instead of through `y`. */
AVX_KERNEL(softmax) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
@@ -918,7 +982,7 @@ AVX_KERNEL(softmax) {
acc = vf_add(acc, t);
}
float sum = vf_hsum(acc);
for (; i < n; ++i) { e[i] = std::exp(v[i] - mx); sum += e[i]; }
for (; i < n; ++i) { e[i] = sc_exp(v[i] - mx); sum += e[i]; }
roundtrip(y->dtype, e, n, tp);
const vf inv = vf_set1(1.0f / sum);
+320 -292
View File
File diff suppressed because it is too large. Load diff
+879 -622
View File
File diff suppressed because it is too large. Load diff
+207
View File
@@ -0,0 +1,207 @@
/* avx_gemm.h -- how the GEMM family reads its operands, and the two large-M drivers.
*
* Shared by avx_gemm.cpp (the ops, the decode-shaped driver) and avx_gemm_tile.cpp (the tile
* drivers). Compiled once per ISA level like every kernel source, so everything here lives in the
* level's inline namespace (avx_vec.h): the four objects never share a definition.
*
* The readings are copied from libref/ref_gemm.h and must match it: where an operand's (row, col)
* lives, and which scale covers it. Note `row_stride` (avx_common.h): a rank-3 [tokens, heads,
* width] activation read as [tokens, heads*width] has its row stride on the tokens axis, not
* stride[rank-2].
*/
#ifndef RAD_AVX_GEMM_H
#define RAD_AVX_GEMM_H
#include "avx_vec.h"
#include "avx_common.h"
#include "avx_planes.h"
namespace avx {
inline namespace AVX_SUFFIX {
/* A weight whose rows are produced by a decoder instead of read as stored: codes and their scales
* joined (avx_planes.h), widened to f32 with the scales folded in. Called from parallel regions;
* an implementation only writes `dst`.
*
* row the whole row, `K` columns
* cols columns [k0, k1) into dst[0, k1 - k0); k0 is a multiple of align(), and k1 is too or
* is the row's end */
struct RowDecoder {
virtual void row(int64_t r, float* dst) const = 0;
virtual void cols(int64_t r, int64_t k0, int64_t k1, float* dst) const = 0;
virtual int64_t align() const = 0;
/* The stored bytes cols(r, k0, k1) reads first (the codes), for a prefetch ahead of it. */
virtual void codes(int64_t r, int64_t k0, int64_t k1, const void** p, int64_t* bytes) const = 0;
};
struct Mat {
const RadTensor* t;
int64_t rs, cs;
const RowDecoder* dec = nullptr;
};
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;
}
/* n E8M0 exponents as f32, rad_e8m0_to_f32's values: e << 23, with 0 the subnormal 2^-127 and
* 0xFF a NaN. */
static inline void e8m0_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) {
const __m512i e = _mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*)(src + i)));
__m512i u = _mm512_slli_epi32(e, 23);
u = _mm512_mask_mov_epi32(u, _mm512_cmpeq_epi32_mask(e, _mm512_setzero_si512()),
_mm512_set1_epi32(0x00400000));
u = _mm512_mask_mov_epi32(u, _mm512_cmpeq_epi32_mask(e, _mm512_set1_epi32(0xff)),
_mm512_set1_epi32(0x7fc00000));
_mm512_storeu_si512((void*)(dst + i), u);
}
#elif AVX_LEVEL == 2
for (; i + 8 <= n; i += 8) {
const __m256i e = _mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*)(src + i)));
__m256i u = _mm256_slli_epi32(e, 23);
u = _mm256_blendv_epi8(u, _mm256_set1_epi32(0x00400000),
_mm256_cmpeq_epi32(e, _mm256_setzero_si256()));
u = _mm256_blendv_epi8(u, _mm256_set1_epi32(0x7fc00000),
_mm256_cmpeq_epi32(e, _mm256_set1_epi32(0xff)));
_mm256_storeu_si256((__m256i*)(dst + i), u);
}
#endif
for (; i < n; ++i) dst[i] = rad_e8m0_to_f32(src[i]);
}
/* A quantised operand's scale stream, as defined in libref/ref_gemm.h. `rblk` makes a
* DeepSeek-style [ceil(N/128)][ceil(K/128)] block grid readable: without it a 17408-row weight's
* 136-row scale plane would be read as 17408 rows. MXFP4 weights may carry e8m0 (u8) scales. */
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);
}
/* Groups [g0, g0 + n) of `row` into dst, the same values grp() returns, with the dtype
* resolved once rather than per scale. */
inline void row_groups(int64_t row, int64_t g0, int64_t n, float* dst) const {
const int64_t base = (rblk > 1 ? row / rblk : row) * rs + g0 * cs;
const uint8_t* b = (const uint8_t*)p;
if (cs == 1) {
switch (e8m0 ? (uint32_t)RAD_E8M0 : dt) {
case RAD_E8M0: e8m0_to_f32(b + base, dst, n); return;
case RAD_BF16: cvt_bf16_to_f32((const uint16_t*)p + base, dst, n); return;
case RAD_F16: cvt_f16_to_f32((const uint16_t*)p + base, dst, n); return;
case RAD_F32: std::memcpy(dst, (const float*)p + base, (size_t)n * 4); return;
default: break;
}
}
if (e8m0 || dt == RAD_E8M0) {
for (int64_t g = 0; g < n; ++g) dst[g] = rad_e8m0_to_f32(b[base + g * cs]);
} else if (dt == RAD_BF16) {
for (int64_t g = 0; g < n; ++g)
dst[g] = rad_bf16_to_f32(((const uint16_t*)p)[base + g * cs]);
} else if (dt == RAD_F16) {
for (int64_t g = 0; g < n; ++g)
dst[g] = rad_f16_to_f32(((const uint16_t*)p)[base + g * cs]);
} else if (dt == RAD_F32) {
for (int64_t g = 0; g < n; ++g) dst[g] = ((const float*)p)[base + g * cs];
} else {
for (int64_t g = 0; g < n; ++g) dst[g] = rad_load_f32(p, dt, base + g * cs);
}
}
};
static inline 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;
/* As libref: a rank-2 stream with fewer rows than the operand is a block grid, and a flat
* stream shorter than the row count is one scale per block of rows. */
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;
}
/* Columns [k0, k0 + n) of row r of a plain operand as raw f32 codes: the row converter where the
* columns are contiguous and start on a byte, element by element otherwise. */
static inline void widen_cols(const Mat& m, int64_t r, int64_t k0, int64_t n, float* dst) {
const RadTensor* t = m.t;
const int64_t base = r * m.rs + k0 * m.cs;
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, n);
return;
}
}
for (int64_t k = 0; k < n; ++k) dst[k] = ld_elem(t->data, t->dtype, base + k * m.cs);
}
/* ================================================================== the tile drivers
* (avx_gemm_tile.cpp). Y = A B^T (+ bias), the product gemm_drive forms, at any M. Each returns
* false when it does not apply, and the caller then computes all of Y another way.
*
* gemm_q_bf16 AVX512_BF16 parts: weight codes exact in bf16 (E4M3, int8, int4, e2m1) against
* an E4M3, int8 or bf16 activation; the group structure kept, as libref's
* gemm_tile_f32 any operands, both scales folded into the f32 operands (it may have written Y
* when it returns false: an E8M0 scale it cannot fold is found as it runs)
*
* SA must be coarse (no finer than the weight's group); gemm_drive takes the other case first. */
bool gemm_q_bf16(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);
bool gemm_tile_f32(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);
/* A batch of independent products in one parallel region, as a grouped GEMM's experts are. Job j
* computes Y[y0 + i][yc0 + c] = sum_k A[a0 + i][k] * B[b0 + c][k] (+ bias[c]) for i < M, c < N,
* k < K: rows of one batch activation, columns of its own weight. Batch row r is A's row
* arow[r] (or r with no map), and a negative entry a zero row. Every job's weight is the same
* format at the same group (SB.p null: unscaled); SA scales A's rows as libref's Scales. `ycols`
* is Y's logical width, which sets its row pitch. With `zero` (a zero-point grid's u8 plane, one
* per row and group of SB) the weight is (code - zero) * scale over u4 or u5 codes, which only the
* bf16 grouped driver takes. */
struct TileJob {
Mat mb;
Scales SB;
int64_t b0, a0, M, N, K, y0, yc0;
const RadTensor* bias;
avxp::JPlane zero;
};
bool gemm_q_bf16_jobs(const Mat& ma, const int64_t* arow, int64_t arows, const Scales* SA,
const TileJob* jobs, int64_t njobs, const RadTensor* Y, int64_t ycols);
bool gemm_tile_f32_jobs(const Mat& ma, const int64_t* arow, int64_t arows, const Scales* SA,
const TileJob* jobs, int64_t njobs, const RadTensor* Y, int64_t ycols);
} /* inline namespace AVX_SUFFIX */
} /* namespace avx */
#endif /* RAD_AVX_GEMM_H */
File diff suppressed because it is too large. Load diff
+1047
View File
File diff suppressed because it is too large. Load diff
+670
View File
@@ -0,0 +1,670 @@
/* avx_gen_attn.cpp -- attn_prefix_self: attention over a cached conditioning prefix and the pass's
* own rows (docs/OPS.md, "Image generation"), the diffusion transformer's attention.
*
* Keys of entry s, in order: its `seqused[s]` prefix positions in the paged cache, every one
* visible, then its own rows [cu[s], cu[s+1]) beside q, of which own row i sees j <= i with
* `causal` and all of them otherwise. A prefix key in a missing block (a negative table entry) is
* a zero key and a zero value that still takes its share of the softmax, as libref reads it.
*
* Flash-attention form. Each (entry, kv head)'s key sequence is packed once per launch into
* 64-key tiles, then a task is (entry, kv head, 32 query positions) with the gqa query heads of
* that kv head: per tile, S = Q K^T as broadcast-against-tile products (no horizontal sums), the
* causal mask, the online softmax (running max moved at tile boundaries), then O += P V. Packs are
* made for a group of kv heads at a time, at most ~64 MiB, so the packed tiles of the heads in
* flight stay near cache instead of all heads' at once.
*
* bf16 (AVX512_BF16 and bf16 q, k, v, cache, head_dim a multiple of 64): vdpbf16ps for both
* products, P rounded to bf16 for P V as PyTorch's CPU flash attention does (and
* avx_attn.cpp: attn_dense_bf16).
* f32 every other case: f32 tiles, vf FMAs, P in f32.
*
* The int8 score form (`qk` "i8"): the query and each prefix key are quantised per (row, head) by
* libref's rule (scale amax / 127, 1 for an all-zero row; code rint(clamp(x / scale, +-127))), the
* own keys arrive as codes and scales, and a score is ((dot * sq) * sk) * scale with the integer
* dot exact in f32 (|dot| < 2^24 up to head_dim 1024). Codes are exact in bf16 too, so the bf16
* path computes the same scores; only P V differs from libref, by the softmax order and P's
* rounding.
*
* Results differ from libref's two-pass softmax in summation order and the rescales' roundings,
* within the attention tolerance. Each output row is one task's, so they do not depend on the
* thread count.
*/
#include "avx_vec.h"
#include "avx_common.h"
#include <algorithm>
#include <vector>
using namespace avx;
namespace {
/* The widest head, libref's (its stack rows, and the int8 dot's exact range). */
enum { PS_HD_MAX = 1024 };
/* Keys per tile and query positions per task. */
enum { KT = 64, QB = 32 };
/* The packed tiles of the kv heads in flight. */
constexpr int64_t kPackBudget = (int64_t)64 << 20;
struct Geo {
const RadTensor *q, *k, *v, *kv, *bt, *su, *cu, *o, *kdes, *vdes, *k8, *ks;
bool i8;
int causal;
int64_t hd, gqa, kvh, qh, n_seq, bs, max_blocks, bt_rs, bt_cs;
int64_t q_rs, k_rs, v_rs, o_rs, k8_rs, ks_rs, sb, sh, so;
float scale;
};
inline int64_t cu_at(const RadTensor* cu, int64_t i) { return ldi(cu, offlin(cu, i)); }
/* One (entry, kv head)'s key sequence: P prefix keys then the entry's own rows from b0. */
struct Seq {
int64_t s, kh, P, b0, len, nk, ntile;
size_t off; /* bytes into the pack */
};
/* libref's per-row int8 rule: codes into `code` (may be `x`), the scale returned. */
inline float q8_row(const float* x, int64_t n, float* code) {
const float am = row_amax(x, n);
const float sc = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f;
const float inv = 1.0f / sc;
const vf vi = vf_set1(inv), lo = vf_set1(-127.0f), hi = vf_set1(127.0f);
int64_t d = 0;
#if AVX_LEVEL >= 1
for (; d + VF_N <= n; d += VF_N) {
const vf c = vf_min(vf_max(vf_mul(vf_loadu(x + d), vi), lo), hi);
#if AVX_LEVEL == 3
vf_storeu(code + d, _mm512_roundscale_ps(c, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC));
#else
vf_storeu(code + d, _mm256_round_ps(c, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC));
#endif
}
#else
(void)vi; (void)lo; (void)hi;
#endif
for (; d < n; ++d) code[d] = std::rint(std::min(std::max(x[d] * inv, -127.0f), 127.0f));
return sc;
}
/* Key (or value) j of `q`'s sequence as f32 into out[0, hd). A prefix key carries its entry's
* descale per element, as libref applies it. */
void key_f32(const Geo& g, const Seq& q, int64_t j, bool val, float* out) {
const int64_t hd = g.hd;
if (j < q.P) {
const int64_t blk = ldi(g.bt, q.s * g.bt_rs + (j / g.bs) * g.bt_cs);
if (blk < 0) {
for (int64_t d = 0; d < hd; ++d) out[d] = 0.0f;
return;
}
const int64_t base = blk * g.sb + q.kh * g.sh + (j % g.bs) * g.so + (val ? hd : 0);
row_to_f32(g.kv->dtype, byte_at(g.kv->data, g.kv->dtype, base), out, hd);
const RadTensor* des = val ? g.vdes : g.kdes;
const float m = des ? ldt(des, q.s * g.kvh + q.kh) : 1.0f;
if (m != 1.0f)
for (int64_t d = 0; d < hd; ++d) out[d] *= m;
return;
}
const int64_t row = q.b0 + j - q.P;
const RadTensor* t = val ? g.v : g.k;
const int64_t base = row * (val ? g.v_rs : g.k_rs) + q.kh * hd;
row_to_f32(t->dtype, byte_at(t->data, t->dtype, base), out, hd);
}
/* The int8 form's key j: codes into out and its scale. */
float key_i8(const Geo& g, const Seq& q, int64_t j, float* out) {
if (j < q.P) {
key_f32(g, q, j, false, out);
return q8_row(out, g.hd, out);
}
const int64_t row = q.b0 + j - q.P;
row_to_f32(g.k8->dtype, byte_at(g.k8->data, g.k8->dtype, row * g.k8_rs + q.kh * g.hd), out,
g.hd);
return ldt(g.ks, row * g.ks_rs + q.kh);
}
/* The keys a task's last query can see: all, or with `causal` up to its own row. */
inline int64_t visible_keys(const Geo& g, const Seq& q, int64_t q1) {
return g.causal ? std::min(q.nk, q.P + q1) : q.nk;
}
/* S *= scale, or the int8 form's ((S * sq[r]) * sk) * scale; then -inf past the tile's last key
* and, with `causal`, for own keys after a row's position. */
void finish_scores(const Geo& g, const Seq& q, float* S, int64_t R, int64_t t, int64_t q0,
const float* sq, const float* sk) {
const vf vs = vf_set1(g.scale);
for (int64_t r = 0; r < R; ++r) {
float* sr = S + r * KT;
if (g.i8) {
const vf vq = vf_set1(sq[r]);
int64_t j = 0;
for (; j + VF_N <= KT; j += VF_N)
vf_storeu(sr + j, vf_mul(vf_mul(vf_mul(vf_loadu(sr + j), vq), vf_loadu(sk + j)), vs));
for (; j < KT; ++j) sr[j] = ((sr[j] * sq[r]) * sk[j]) * g.scale;
} else {
int64_t j = 0;
for (; j + VF_N <= KT; j += VF_N) vf_storeu(sr + j, vf_mul(vf_loadu(sr + j), vs));
for (; j < KT; ++j) sr[j] *= g.scale;
}
const int64_t i = q0 + r / g.gqa;
const int64_t end = g.causal ? std::min(q.nk, q.P + i + 1) : q.nk;
for (int64_t j = std::max<int64_t>(0, end - t * KT); j < KT; ++j) sr[j] = -INFINITY;
}
}
/* The online softmax over one tile of R rows: m, l and acc (rows of `ld`) rescaled at a new
* maximum, S replaced by exp(S - m). A row with nothing visible in the tile becomes zeros. */
void softmax_tile(float* S, int64_t R, float* m, float* l, float* acc, int64_t ld, int64_t width) {
for (int64_t r = 0; r < R; ++r) {
float* sr = S + r * KT;
const float tmax = row_max(sr, KT);
if (tmax == -INFINITY) {
for (int64_t j = 0; j < KT; ++j) sr[j] = 0.0f;
continue;
}
if (tmax > m[r]) {
const float alpha = m[r] == -INFINITY ? 0.0f : sc_exp(m[r] - tmax);
if (alpha != 1.0f) {
float* ar = acc + r * ld;
const vf va = vf_set1(alpha);
int64_t d = 0;
for (; d + VF_N <= width; d += VF_N) vf_storeu(ar + d, vf_mul(vf_loadu(ar + d), va));
for (; d < width; ++d) ar[d] *= alpha;
l[r] *= alpha;
}
m[r] = tmax;
}
const vf vm = vf_set1(m[r]);
int64_t j = 0;
for (; j + VF_N <= KT; j += VF_N) vf_storeu(sr + j, vf_exp(vf_sub(vf_loadu(sr + j), vm)));
for (; j < KT; ++j) sr[j] = sc_exp(sr[j] - m[r]);
l[r] += row_sum(sr, KT);
}
}
/* out = acc / l (0 for a row that saw nothing), stored to `o` at its row and head. */
void store_rows(const Geo& g, const Seq& q, int64_t q0, int64_t R, float* acc, int64_t ld,
const float* m, const float* l) {
for (int64_t r = 0; r < R; ++r) {
const int64_t row = q.b0 + q0 + r / g.gqa, h = q.kh * g.gqa + r % g.gqa;
float* ar = acc + r * ld;
const float inv = (m[r] == -INFINITY || l[r] <= 0.0f) ? 0.0f : 1.0f / l[r];
const vf vi = vf_set1(inv);
int64_t d = 0;
for (; d + VF_N <= g.hd; d += VF_N) vf_storeu(ar + d, vf_mul(vf_loadu(ar + d), vi));
for (; d < g.hd; ++d) ar[d] *= inv;
out_row(g.o, row * g.o_rs + h * g.hd, g.hd, ar);
}
}
/* ================================================================== the f32 form
*
* A tile packed as Kt [hd][64] (each dimension's 64 keys contiguous, so a query element broadcast
* against four vectors gives 4 * VF_N scores) and V [64][hp], hp the head rounded up to 4 * VF_N
* with zero columns, so P V runs whole vectors. The int8 form's key scales follow, [64]. */
#if AVX_LEVEL == 3
constexpr int RB = 6;
#else
constexpr int RB = 2;
#endif
constexpr int64_t CK = 4 * VF_N;
/* The next row block of a tile: `top` rows, except that the last two blocks are kept at four or
* more (32 rows go 6 6 6 6 4 4). A one- or two-row block has four or eight accumulators, too few
* to cover the dot product's latency, and would cost nearly as much as a full one. */
inline int row_block(int64_t left, int top) {
if (top < 4) return left >= top ? top : (int)left;
if (left >= top + 4 || left == top) return top;
return left > top ? (int)(left - 4) : (int)left;
}
/* fn<mb>(args...) for a block of 1..6 rows. */
#define PS_ROWS(fn, mb, ...) \
switch (mb) { \
case 6: fn<6>(__VA_ARGS__); break; \
case 5: fn<5>(__VA_ARGS__); break; \
case 4: fn<4>(__VA_ARGS__); break; \
case 3: fn<3>(__VA_ARGS__); break; \
case 2: fn<2>(__VA_ARGS__); break; \
default: fn<1>(__VA_ARGS__); break; \
}
inline int64_t f32_hp(int64_t hd) { return (hd + CK - 1) / CK * CK; }
inline size_t f32_tile_floats(int64_t hd) { return (size_t)(hd * KT + KT * f32_hp(hd) + KT); }
void pack_tile_f32(const Geo& g, const Seq& q, int64_t t, float* tile, float* row) {
const int64_t hd = g.hd, hp = f32_hp(hd);
float* Kt = tile;
float* Vt = tile + hd * KT;
float* sk = Vt + KT * hp;
for (int64_t jj = 0; jj < KT; ++jj) {
const int64_t j = t * KT + jj;
float* vr = Vt + jj * hp;
if (j >= q.nk) {
for (int64_t d = 0; d < hd; ++d) Kt[d * KT + jj] = 0.0f;
for (int64_t d = 0; d < hp; ++d) vr[d] = 0.0f;
sk[jj] = 0.0f;
continue;
}
sk[jj] = g.i8 ? key_i8(g, q, j, row) : (key_f32(g, q, j, false, row), 1.0f);
for (int64_t d = 0; d < hd; ++d) Kt[d * KT + jj] = row[d];
key_f32(g, q, j, true, vr);
for (int64_t d = hd; d < hp; ++d) vr[d] = 0.0f;
}
}
/* S[i][0, 64) = Q[i] . K for MB_ rows of Q (pitch ldq) over the packed Kt. */
template <int MB_>
inline void qk_f32(const float* Q, int64_t ldq, const float* Kt, int64_t hd, float* S) {
for (int64_t c = 0; c < KT; c += CK) {
vf acc[MB_][4];
for (int i = 0; i < MB_; ++i)
for (int v = 0; v < 4; ++v) acc[i][v] = vf_zero();
for (int64_t d = 0; d < hd; ++d) {
const float* kr = Kt + d * KT + c;
const vf k0 = vf_loadu(kr), k1 = vf_loadu(kr + VF_N);
const vf k2 = vf_loadu(kr + 2 * VF_N), k3 = vf_loadu(kr + 3 * VF_N);
for (int i = 0; i < MB_; ++i) {
const vf b = vf_set1(Q[i * ldq + d]);
acc[i][0] = vf_fma(b, k0, acc[i][0]);
acc[i][1] = vf_fma(b, k1, acc[i][1]);
acc[i][2] = vf_fma(b, k2, acc[i][2]);
acc[i][3] = vf_fma(b, k3, acc[i][3]);
}
}
for (int i = 0; i < MB_; ++i)
for (int v = 0; v < 4; ++v) vf_storeu(S + i * KT + c + v * VF_N, acc[i][v]);
}
}
/* acc[i][0, hp) += P[i] . V for MB_ rows over the tile's `kt` keys. */
template <int MB_>
inline void pv_f32(float* acc, int64_t hp, const float* Pm, const float* Vt, int64_t kt) {
for (int64_t c = 0; c < hp; c += CK) {
vf o[MB_][4];
for (int i = 0; i < MB_; ++i)
for (int v = 0; v < 4; ++v) o[i][v] = vf_loadu(acc + i * hp + c + v * VF_N);
for (int64_t j = 0; j < kt; ++j) {
const float* vr = Vt + j * hp + c;
const vf v0 = vf_loadu(vr), v1 = vf_loadu(vr + VF_N);
const vf v2 = vf_loadu(vr + 2 * VF_N), v3 = vf_loadu(vr + 3 * VF_N);
for (int i = 0; i < MB_; ++i) {
const vf p = vf_set1(Pm[i * KT + j]);
o[i][0] = vf_fma(p, v0, o[i][0]);
o[i][1] = vf_fma(p, v1, o[i][1]);
o[i][2] = vf_fma(p, v2, o[i][2]);
o[i][3] = vf_fma(p, v3, o[i][3]);
}
}
for (int i = 0; i < MB_; ++i)
for (int v = 0; v < 4; ++v) vf_storeu(acc + i * hp + c + v * VF_N, o[i][v]);
}
}
void task_f32(const Geo& g, const Seq& q, const uint8_t* pack, int64_t q0, int64_t q1) {
const int64_t hd = g.hd, hp = f32_hp(hd), R = (q1 - q0) * g.gqa, R_MAX = QB * g.gqa;
float* frame = scratch_f32((size_t)(R_MAX * hp + R_MAX * hd + R_MAX * KT + 3 * R_MAX + hp) + 64);
float* acc = frame;
float* Q = acc + R_MAX * hp;
float* S = Q + R_MAX * hd;
float* m = S + R_MAX * KT;
float* l = m + R_MAX;
float* sq = l + R_MAX;
for (int64_t r = 0; r < R; ++r) {
const int64_t row = q.b0 + q0 + r / g.gqa, h = q.kh * g.gqa + r % g.gqa;
float* qr = Q + r * hd;
row_to_f32(g.q->dtype, byte_at(g.q->data, g.q->dtype, row * g.q_rs + h * hd), qr, hd);
sq[r] = g.i8 ? q8_row(qr, hd, qr) : 1.0f;
m[r] = -INFINITY;
l[r] = 0.0f;
}
std::memset(acc, 0, sizeof(float) * (size_t)(R * hp));
const int64_t nvis = visible_keys(g, q, q1);
const size_t tf = f32_tile_floats(hd);
for (int64_t t = 0; t * KT < nvis; ++t) {
const float* tile = (const float*)(pack + q.off) + (size_t)t * tf;
const float* Kt = tile;
const float* Vt = tile + hd * KT;
const float* sk = Vt + KT * hp;
for (int64_t r = 0, mb; r < R; r += mb) {
mb = row_block(R - r, RB);
PS_ROWS(qk_f32, mb, Q + r * hd, hd, Kt, hd, S + r * KT);
}
finish_scores(g, q, S, R, t, q0, sq, sk);
softmax_tile(S, R, m, l, acc, hp, hp);
const int64_t kt = std::min<int64_t>(KT, q.nk - t * KT);
for (int64_t r = 0, mb; r < R; r += mb) {
mb = row_block(R - r, RB);
PS_ROWS(pv_f32, mb, acc + r * hp, hp, S + r * KT, Vt, kt);
}
}
store_rows(g, q, q0, R, acc, hp, m, l);
}
/* ================================================================== the bf16 form
*
* A tile packed as kp [hd/2][64] u32, key j's dimensions (2d, 2d+1) as one bf16 pair, and
* vp [32][hd] u32, keys (2k, 2k+1) at column d as one pair; the int8 form's key scales follow,
* [64] f32. Codes are integers of at most 127 in magnitude, exact in bf16. */
#if AVX_LEVEL == 3
#define PS_BF16 __attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16")))
inline size_t bf16_tile_bytes(int64_t hd) {
return (size_t)(hd / 2 * KT) * 4 + (size_t)(KT / 2 * hd) * 4 + (size_t)KT * 4;
}
/* A key row's hd bf16 values (the cache's or the own rows' own bits, or exact codes), and for the
* int8 form its scale. `row` holds hd floats. */
float key_bf16(const Geo& g, const Seq& q, int64_t j, bool val, uint16_t* out, float* row) {
const int64_t hd = g.hd;
if (g.i8 && !val) {
const float sk = key_i8(g, q, j, row);
row_from_f32(RAD_BF16, row, out, hd);
return sk;
}
const uint16_t* src = nullptr;
if (j < q.P) {
const int64_t blk = ldi(g.bt, q.s * g.bt_rs + (j / g.bs) * g.bt_cs);
if (blk >= 0)
src = (const uint16_t*)g.kv->data + blk * g.sb + q.kh * g.sh + (j % g.bs) * g.so +
(val ? hd : 0);
} else {
const int64_t r = q.b0 + j - q.P;
src = (const uint16_t*)(val ? g.v : g.k)->data + r * (val ? g.v_rs : g.k_rs) + q.kh * hd;
}
if (src) std::memcpy(out, src, (size_t)hd * 2);
else std::memset(out, 0, (size_t)hd * 2);
return 1.0f;
}
void pack_tile_bf16(const Geo& g, const Seq& q, int64_t t, uint8_t* tile, float* row,
uint16_t* kv2) {
const int64_t hd = g.hd, D2 = hd / 2;
uint32_t* kp = (uint32_t*)tile;
uint32_t* vp = kp + D2 * KT;
float* sk = (float*)(vp + (KT / 2) * hd);
uint16_t* ka = kv2;
uint16_t* va = kv2 + 2 * hd;
for (int64_t k2 = 0; k2 < KT / 2; ++k2) {
for (int e = 0; e < 2; ++e) {
const int64_t jj = 2 * k2 + e, j = t * KT + jj;
uint16_t* kr = ka + e * hd;
uint16_t* vr = va + e * hd;
if (j >= q.nk) {
std::memset(kr, 0, (size_t)hd * 2);
std::memset(vr, 0, (size_t)hd * 2);
sk[jj] = 0.0f;
continue;
}
sk[jj] = key_bf16(g, q, j, false, kr, row);
key_bf16(g, q, j, true, vr, row);
for (int64_t d2 = 0; d2 < D2; ++d2)
kp[d2 * KT + jj] = (uint32_t)kr[2 * d2] | ((uint32_t)kr[2 * d2 + 1] << 16);
}
uint32_t* vo = vp + k2 * hd;
for (int64_t d = 0; d < hd; ++d) vo[d] = (uint32_t)va[d] | ((uint32_t)va[hd + d] << 16);
}
}
/* S[i][0, 64) = Q[i] . K over the packed tile, MB_ query rows given as bf16 row pointers. */
template <int MB_>
PS_BF16 inline void qk_bf16(const uint16_t* const* qr, const uint32_t* kp, int64_t D2, float* S) {
__m512 acc[MB_][4];
#pragma GCC unroll 8
for (int i = 0; i < MB_; ++i)
#pragma GCC unroll 4
for (int v = 0; v < 4; ++v) acc[i][v] = _mm512_setzero_ps();
for (int64_t d2 = 0; d2 < D2; ++d2) {
const uint32_t* kr = kp + d2 * KT;
const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)(kr));
const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 16));
const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 32));
const __m512bh b3 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 48));
#pragma GCC unroll 8
for (int i = 0; i < MB_; ++i) {
uint32_t pr;
std::memcpy(&pr, qr[i] + 2 * d2, 4);
const __m512bh a = (__m512bh)_mm512_set1_epi32((int)pr);
acc[i][0] = _mm512_dpbf16_ps(acc[i][0], a, b0);
acc[i][1] = _mm512_dpbf16_ps(acc[i][1], a, b1);
acc[i][2] = _mm512_dpbf16_ps(acc[i][2], a, b2);
acc[i][3] = _mm512_dpbf16_ps(acc[i][3], a, b3);
}
}
#pragma GCC unroll 8
for (int i = 0; i < MB_; ++i)
#pragma GCC unroll 4
for (int v = 0; v < 4; ++v) _mm512_storeu_ps(S + i * KT + 16 * v, acc[i][v]);
}
/* acc[i][c0, c0 + 64) += P[i] . V, MB_ rows of bf16 P pairs (pp[i * 32 + k2]) against the
* tile's value pairs. */
template <int MB_>
PS_BF16 inline void pv_bf16(float* acc, int64_t hd, const uint32_t* pp, const uint32_t* vp,
int64_t K2, int64_t c0) {
__m512 o[MB_][4];
#pragma GCC unroll 8
for (int i = 0; i < MB_; ++i)
#pragma GCC unroll 4
for (int v = 0; v < 4; ++v) o[i][v] = _mm512_loadu_ps(acc + i * hd + c0 + 16 * v);
for (int64_t k2 = 0; k2 < K2; ++k2) {
const uint32_t* vr = vp + k2 * hd + c0;
const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)(vr));
const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 16));
const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 32));
const __m512bh b3 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 48));
#pragma GCC unroll 8
for (int i = 0; i < MB_; ++i) {
const __m512bh a = (__m512bh)_mm512_set1_epi32((int)pp[i * 32 + k2]);
o[i][0] = _mm512_dpbf16_ps(o[i][0], a, b0);
o[i][1] = _mm512_dpbf16_ps(o[i][1], a, b1);
o[i][2] = _mm512_dpbf16_ps(o[i][2], a, b2);
o[i][3] = _mm512_dpbf16_ps(o[i][3], a, b3);
}
}
#pragma GCC unroll 8
for (int i = 0; i < MB_; ++i)
#pragma GCC unroll 4
for (int v = 0; v < 4; ++v) _mm512_storeu_ps(acc + i * hd + c0 + 16 * v, o[i][v]);
}
/* A row of 64 probabilities to 32 bf16 key pairs, round to nearest even. */
PS_BF16 inline void p_pairs(const float* sr, uint32_t* pr) {
_mm512_storeu_si512((void*)pr,
(__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 16), _mm512_loadu_ps(sr)));
_mm512_storeu_si512((void*)(pr + 16), (__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 48),
_mm512_loadu_ps(sr + 32)));
}
PS_BF16 void task_bf16(const Geo& g, const Seq& q, const uint8_t* pack, int64_t q0, int64_t q1) {
const int64_t hd = g.hd, D2 = hd / 2, R = (q1 - q0) * g.gqa, R_MAX = QB * g.gqa;
float* frame = scratch_f32((size_t)(R_MAX * hd + R_MAX * KT + 3 * R_MAX + R_MAX * KT / 2 +
R_MAX * hd / 2 + hd) + 64);
float* acc = frame;
float* S = acc + R_MAX * hd;
float* m = S + R_MAX * KT;
float* l = m + R_MAX;
float* sq = l + R_MAX;
uint32_t* pp = (uint32_t*)(sq + R_MAX);
uint16_t* qcodes = (uint16_t*)(pp + R_MAX * KT / 2);
float* row = (float*)(qcodes + R_MAX * hd);
const uint16_t* qrow[16 * QB];
for (int64_t r = 0; r < R; ++r) {
const int64_t qrw = q.b0 + q0 + r / g.gqa, h = q.kh * g.gqa + r % g.gqa;
const uint16_t* src = (const uint16_t*)g.q->data + qrw * g.q_rs + h * hd;
if (g.i8) {
row_to_f32(RAD_BF16, src, row, hd);
sq[r] = q8_row(row, hd, row);
uint16_t* c = qcodes + r * hd;
row_from_f32(RAD_BF16, row, c, hd);
qrow[r] = c;
} else {
sq[r] = 1.0f;
qrow[r] = src;
}
m[r] = -INFINITY;
l[r] = 0.0f;
}
std::memset(acc, 0, sizeof(float) * (size_t)(R * hd));
const int64_t nvis = visible_keys(g, q, q1);
const size_t tb = bf16_tile_bytes(hd);
for (int64_t t = 0; t * KT < nvis; ++t) {
const uint8_t* tile = pack + q.off + (size_t)t * tb;
const uint32_t* kp = (const uint32_t*)tile;
const uint32_t* vp = kp + D2 * KT;
const float* sk = (const float*)(vp + (KT / 2) * hd);
for (int64_t r = 0, mb; r < R; r += mb) {
mb = row_block(R - r, 6);
PS_ROWS(qk_bf16, mb, qrow + r, kp, D2, S + r * KT);
}
finish_scores(g, q, S, R, t, q0, sq, sk);
softmax_tile(S, R, m, l, acc, hd, hd);
for (int64_t r = 0; r < R; ++r) p_pairs(S + r * KT, pp + r * 32);
const int64_t K2 = (std::min<int64_t>(KT, q.nk - t * KT) + 1) / 2;
for (int64_t c0 = 0; c0 < hd; c0 += 64)
for (int64_t r = 0, mb; r < R; r += mb) {
mb = row_block(R - r, 6);
PS_ROWS(pv_bf16, mb, acc + r * hd, hd, pp + r * 32, vp, K2, c0);
}
}
store_rows(g, q, q0, R, acc, hd, m, l);
}
#endif
} /* namespace */
/* ------------------------------------------------------------------ attn_prefix_self */
AVX_KERNEL(attn_prefix_self) {
if (a->n_t < 12) return RAD_E_INVAL;
Geo g{};
g.q = &a->t[0]; g.k = &a->t[1]; g.v = &a->t[2]; g.kv = &a->t[3];
g.bt = &a->t[4]; g.su = &a->t[5]; g.cu = &a->t[6]; g.o = &a->t[11];
g.kdes = rad_arg_in(a, 7);
g.vdes = rad_arg_in(a, 8);
g.k8 = rad_arg_in(a, 9);
g.ks = rad_arg_in(a, 10);
g.i8 = std::strcmp(p_str(a, "qk", "bf16"), "i8") == 0;
if (g.i8 != (g.k8 != nullptr) || g.i8 != (g.ks != nullptr)) return RAD_E_INVAL;
if (g.i8 && (g.kdes || g.vdes)) return RAD_E_UNSUPPORTED;
g.hd = p_int(a, "head_dim", 0);
g.gqa = p_int(a, "gqa", 1);
g.causal = (int)p_int(a, "causal", 0);
g.bs = g.kv->rank == 4 ? g.kv->shape[2] : p_int(a, "block_size", 0);
if (g.hd <= 0 || g.gqa <= 0 || g.bs <= 0) return RAD_E_SHAPE;
if (g.hd > PS_HD_MAX) return RAD_E_UNSUPPORTED;
g.kvh = g.kv->rank == 4 ? g.kv->shape[1] : 0;
if (g.kvh <= 0) return RAD_E_SHAPE;
g.qh = g.kvh * g.gqa;
g.n_seq = numel(g.cu) - 1;
if (g.n_seq <= 0 || numel(g.su) < g.n_seq) return RAD_E_SHAPE;
if (cu_at(g.cu, g.n_seq) - cu_at(g.cu, 0) <= 0) return RAD_E_SHAPE;
g.max_blocks = g.bt->rank >= 2 ? g.bt->shape[1] : numel(g.bt) / g.n_seq;
g.bt_rs = g.bt->rank >= 2 ? g.bt->stride[0] : g.max_blocks;
g.bt_cs = g.bt->rank >= 2 ? g.bt->stride[1] : 1;
for (int64_t s = 0; s < g.n_seq; ++s)
if (ldi(g.su, offlin(g.su, s)) > g.max_blocks * g.bs) return RAD_E_SHAPE;
g.q_rs = row_stride(g.q, g.qh * g.hd);
g.k_rs = row_stride(g.k, g.kvh * g.hd);
g.v_rs = row_stride(g.v, g.kvh * g.hd);
g.o_rs = row_stride(g.o, g.qh * g.hd);
g.k8_rs = g.i8 ? row_stride(g.k8, g.kvh * g.hd) : 0;
g.ks_rs = g.i8 ? row_stride(g.ks, g.kvh) : 0;
g.sb = g.kv->stride[0]; g.sh = g.kv->stride[1]; g.so = g.kv->stride[2];
g.scale = p_f32(a, "scale", 1.0f / std::sqrt((float)g.hd));
/* ---- which form, and each (entry, kv head)'s key sequence */
[[maybe_unused]] bool bf16 = false;
#if AVX_LEVEL == 3
static const bool have_bf16 = __builtin_cpu_supports("avx512bf16");
bf16 = have_bf16 && g.hd % 64 == 0 && g.gqa <= 16 && !g.kdes && !g.vdes &&
g.q->dtype == RAD_BF16 && g.kv->dtype == RAD_BF16 && g.v->dtype == RAD_BF16 &&
(g.i8 || g.k->dtype == RAD_BF16);
#endif
const size_t tile_bytes =
#if AVX_LEVEL == 3
bf16 ? bf16_tile_bytes(g.hd) :
#endif
f32_tile_floats(g.hd) * sizeof(float);
/* Kept at their high-water size; the parallel regions read them through pointers taken on
* this thread. */
static thread_local std::vector<Seq> seqs;
static thread_local std::vector<uint8_t> pack;
static thread_local std::vector<int64_t> tile_of, task_of;
seqs.clear();
for (int64_t kh = 0; kh < g.kvh; ++kh)
for (int64_t s = 0; s < g.n_seq; ++s) {
Seq q{};
q.s = s; q.kh = kh;
q.P = ldi(g.su, offlin(g.su, s));
q.b0 = cu_at(g.cu, s);
q.len = std::max<int64_t>(0, cu_at(g.cu, s + 1) - q.b0);
/* A negative prefix count makes key j own row b0 + j - P, as libref indexes it. */
q.nk = std::max<int64_t>(0, q.P + q.len);
q.ntile = (q.nk + KT - 1) / KT;
seqs.push_back(q);
}
/* ---- kv heads in groups whose packs fit the budget: pack each group, then run its tasks */
size_t i0 = 0;
while (i0 < seqs.size()) {
size_t i1 = i0, bytes = 0;
do {
/* Whole kv heads: an entry's tasks of one head share nothing with another head's. */
const int64_t kh = seqs[i1].kh;
size_t hb = 0, j = i1;
for (; j < seqs.size() && seqs[j].kh == kh; ++j) hb += (size_t)seqs[j].ntile * tile_bytes;
if (i1 > i0 && bytes + hb > (size_t)kPackBudget) break;
for (; i1 < j; ++i1) {
seqs[i1].off = bytes;
bytes += (size_t)seqs[i1].ntile * tile_bytes;
}
} while (i1 < seqs.size());
pack.resize(bytes + 64);
uint8_t* pk = pack.data();
tile_of.assign(1, 0);
task_of.assign(1, 0);
for (size_t i = i0; i < i1; ++i) {
tile_of.push_back(tile_of.back() + seqs[i].ntile);
task_of.push_back(task_of.back() + (seqs[i].len + QB - 1) / QB);
}
const int64_t n_tiles = tile_of.back(), n_tasks = task_of.back();
const int64_t n_grp = (int64_t)(i1 - i0);
const Seq* sq0 = seqs.data() + i0;
const int64_t* t_of = tile_of.data();
const int64_t* k_of = task_of.data();
AVX_PARALLEL_FOR_IF(n_tiles * KT * g.hd >= AVX_PAR_MIN)
for (int64_t u = 0; u < n_tiles; ++u) {
const int64_t i = (int64_t)(std::upper_bound(t_of, t_of + n_grp + 1, u) - t_of) - 1;
const Seq& q = sq0[i];
const int64_t t = u - t_of[i];
uint8_t* tile = pk + q.off + (size_t)t * tile_bytes;
float* row = scratch_f32((size_t)(4 * g.hd + 64));
#if AVX_LEVEL == 3
if (bf16) {
pack_tile_bf16(g, q, t, tile, row, (uint16_t*)(row + g.hd + 16));
continue;
}
#endif
pack_tile_f32(g, q, t, (float*)tile, row);
}
#ifdef _OPENMP
#pragma omp parallel for schedule(dynamic, 1) num_threads(avx_team_size()) \
if(n_tasks > 1 || avx_par_forced())
#endif
for (int64_t u = 0; u < n_tasks; ++u) {
const int64_t i = (int64_t)(std::upper_bound(k_of, k_of + n_grp + 1, u) - k_of) - 1;
const Seq& q = sq0[i];
const int64_t q0 = (u - k_of[i]) * QB, q1 = std::min(q0 + QB, q.len);
#if AVX_LEVEL == 3
if (bf16) {
task_bf16(g, q, pk, q0, q1);
continue;
}
#endif
task_f32(g, q, pk, q0, q1);
}
i0 = i1;
}
return RAD_OK;
}
+30 -33
View File
@@ -1,27 +1,24 @@
/* 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. */
/* avx_had.h -- Hadamard rotation, fp8 group quantiser and the shared fp8-fusion epilogue, 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 (avx_hc.cpp).
* Compiled per level with its includer; include 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. */
/* Widest rotation supported. libr4d caps `had` at 512 (the largest power of two dividing a
* per-rank K of 8704); 4096 matches libref's cap so both refuse the same requests. A wider request
* returns RAD_E_UNSUPPORTED rather than rotating a narrower block, whose output would look
* plausible but be 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. */
* One stride `h` of the transform over a g-element block; strides run 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). */
/* In-register stride for h < VF_N: permute each lane with its partner at stride h, then lanes with
* (i & h) == 0 take self + partner and the others partner - self. */
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);
@@ -34,7 +31,6 @@ static inline void fwht_small(float* v, int64_t g, int64_t h) {
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) {
@@ -84,39 +80,38 @@ static inline void fwht_row(float* v, int64_t n, int64_t 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) {
* out[k0, k1) = v[k0, k1) / scale, clamped to +-top, with scale = amax / top (1 for an all-zero
* group): `top` 448 is E4M3's finite range, 127 int8's. */
static inline void fp8_group(const float* v, float* out, int64_t k0, int64_t k1, float* scale_out,
float top = 448.0f) {
const float amax = row_amax(v + k0, k1 - k0);
const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float sc = amax > 0.0f ? amax * (1.0f / top) : 1.0f;
const float inv = 1.0f / sc;
const vf vi = vf_set1(inv), hi = vf_set1(448.0f), lo = vf_set1(-448.0f);
const vf vi = vf_set1(inv), hi = vf_set1(top), lo = vf_set1(-top);
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);
out[i] = t > top ? top : (t < -top ? -top : 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. */
* A fused fp8 op replaces a pair that writes a bf16 tensor and then quantises it. So the codes are
* taken over the bf16-narrowed value whatever the activation dtype, and `out_bf16` holds that
* value (libref's contract, ref_quant.cpp). The helpers below therefore narrow before quantising. */
/* v[0, n) narrowed to bf16 and read back, in place. `tmp` holds n floats, which is room for the n
* bf16 in between. */
/* Round v[0, n) through bf16 in place. `tmp` holds n floats (room for the n bf16). */
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. */
/* out = act(gate) * up, narrowed to bf16. act 0 is silu (down_proj's input), 1 is sigmoid (a
* gated attention's o_proj input). `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;
@@ -131,16 +126,18 @@ static inline void gate_bf16(const float* gv, const float* uv, float* out, int64
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. */
/* Writes row r of the codes `q` and group scales `s` over v[0, n), in groups of `g` (the last may
* be short), and v itself into `ob` when given. `codes` holds n floats. An int8 `q` takes
* quant_act_i8g's codes (libref/ref_quant.cpp: fp8_row). */
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;
const float top = q->dtype == RAD_I8 ? 127.0f : 448.0f;
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);
fp8_group(v, codes, k0, k1, &sc, top);
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
out_row(q, rowoff(q, r, n), n, codes);
+282 -123
View File
@@ -1,19 +1,17 @@
/* avx_harness.h -- opening a plugin, sizing its operands, drawing them, and the geometry table.
/* avx_harness.h -- plugin loading, operand sizing and drawing, 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.
* Shared by rad-avx-check and rad-avx-bench so that both run the same extents from one table
* (tools/opshapes.h does the same for rad-kbench and rad-tune). Header-only for two translation
* units, so everything is `static` or `inline`. Neither binary links a plugin: both dlopen by path,
* so the results describe the .so the engine would load.
*/
#ifndef RAD_AVX_HARNESS_H
#define RAD_AVX_HARNESS_H
#include "rad_abi.h"
#include "rad_plugin.h"
#include "rad_sample.h"
#include "avx_common.h"
#include <dlfcn.h>
@@ -35,11 +33,12 @@ struct Lib {
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. */
/* libavx-only exports; null for other plugins, which tells a caller it cannot sweep ISA
* levels or force its parallel regions. */
int (*isa_force)(int) = nullptr;
int (*isa_detect)() = nullptr;
const char* (*isa_name)(int) = nullptr;
int (*par_force)(int) = nullptr;
bool open(const char* p) {
path = p;
@@ -56,14 +55,14 @@ struct Lib {
isa_force = (int (*)(int))sym("avx_isa_force");
isa_detect = (int (*)())sym("avx_isa_detect");
isa_name = (const char* (*)(int))sym("avx_isa_name");
par_force = (int (*)(int))sym("avx_par_force");
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. */
/* Same rule as the engine's loader: refuse any version but this one, so the tool never
* measures a plugin the engine would not load. */
std::fprintf(stderr, "%s: ABI %u, this tool is built for %u\n", p, abi(),
RAD_ABI_VERSION);
return false;
@@ -90,17 +89,124 @@ struct Lib {
}
return nullptr;
}
/* True when some row of the op runs on the host, i.e. can be launched with host pointers. */
bool host_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 && k->domain == RAD_DOMAIN_HOST)
return true;
}
return false;
}
/* The host row the selector would resolve this geometry to: every constraint holds, highest
* priority, earlier declaration on a tie (core/plugin/select.cpp). A constraint on a derived
* parameter the geometry does not name is skipped, and a "device." key never holds, as
* without an engine nothing measured the machine. Tunables are not chosen; the kernel reads its
* defaults. Null when no host row admits the geometry. */
const RadKernelInfo* select(const char* op, const RadParam* p, int n_p) const {
const RadOpSchema* sch = schema(op);
const RadKernelInfo* best = nullptr;
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 || k->domain != RAD_DOMAIN_HOST)
continue;
bool ok = true;
for (int c = 0; c < k->n_constraints && ok; ++c)
ok = constraint_holds(k->constraints[c], sch, p, n_p);
if (ok && (!best || k->priority > best->priority)) best = k;
}
return best;
}
static bool constraint_holds(const RadConstraint& c, const RadOpSchema* sch, const RadParam* p,
int n_p) {
static const size_t kFact = std::strlen(RAD_DEVICE_FACT_PREFIX);
if (!c.key || std::strncmp(c.key, RAD_DEVICE_FACT_PREFIX, kFact) == 0) return false;
const RadParam* v = rad_param_find(p, n_p, c.key);
if (!v) {
for (int i = 0; sch && i < sch->n_params; ++i)
if (sch->params[i].key && !std::strcmp(sch->params[i].key, c.key))
return sch->params[i].required == RAD_DERIVED;
return false;
}
char num[32];
const char* sv = v->kind == RAD_P_STR ? v->sval : nullptr;
if (c.op == RAD_C_IN) {
if (!sv) {
if (v->kind != RAD_P_INT) return false;
std::snprintf(num, sizeof num, "%lld", v->ival);
sv = num;
}
const size_t len = std::strlen(sv);
for (const char* t = c.sval ? c.sval : ""; *t;) {
while (*t == ' ') ++t;
const char* e = t;
while (*e && *e != ' ') ++e;
if ((size_t)(e - t) == len && len && !std::strncmp(t, sv, len)) return true;
t = e;
}
return false;
}
if (v->kind != RAD_P_INT) return false;
switch (c.op) {
case RAD_C_EQ: return v->ival == c.ival;
case RAD_C_LE: return v->ival <= c.ival;
case RAD_C_GE: return v->ival >= c.ival;
case RAD_C_DIV: return c.ival != 0 && v->ival % c.ival == 0;
default: return false;
}
}
};
/* ================================================================== guarded buffers
*
* Every buffer a kernel is handed has H_GUARD bytes of a known pattern on each side, checked after
* the launch: a write past either end of an operand or of the scratch shows up as a changed guard
* rather than as a corrupted neighbour that may never be read. */
enum { H_GUARD = 64 };
static inline uint8_t h_guard_byte(size_t i) { return (uint8_t)(0xA5u ^ (uint8_t)(i * 29u)); }
struct GBuf {
std::vector<uint8_t> v;
size_t n = 0;
void assign(const uint8_t* src, size_t bytes) {
n = bytes;
v.resize(bytes + 2 * H_GUARD);
for (size_t i = 0; i < H_GUARD; ++i) {
v[i] = h_guard_byte(i);
v[H_GUARD + bytes + i] = h_guard_byte(i + 1);
}
if (bytes) {
if (src) std::memcpy(v.data() + H_GUARD, src, bytes);
else std::memset(v.data() + H_GUARD, 0, bytes);
}
}
void assign(const std::vector<uint8_t>& src) { assign(src.data(), src.size()); }
uint8_t* data() { return v.data() + H_GUARD; }
const uint8_t* data() const { return v.data() + H_GUARD; }
size_t size() const { return n; }
bool empty() const { return n == 0; }
/* 0 when both guards are intact, otherwise -1 for the leading guard and 1 for the trailing. */
int guard_hit() const {
if (v.empty()) return 0;
for (size_t i = 0; i < H_GUARD; ++i)
if (v[i] != h_guard_byte(i)) return -1;
for (size_t i = 0; i < H_GUARD; ++i)
if (v[H_GUARD + n + i] != h_guard_byte(i + 1)) return 1;
return 0;
}
};
/* ================================================================== 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.
* Values follow the fill laws in RadOpdDesc (rad_abi.h). A gated-delta-net `g` is an intra-chunk
* cumulative sum of log-decays; drawn as normals, the oracle overflows to 2e38 and the comparison
* tests the input rather than the kernel. The same holds for sigmoid gates, unit-triangular
* factors, unit-norm keys and every index operand (a KV slot indexes n_blocks * block_size, a
* block-table entry n_blocks); an index drawn out of range tests only out-of-range handling.
*/
static inline uint64_t hsplitmix(uint64_t& x) {
uint64_t z = (x += 0x9E3779B97F4A7C15ull);
@@ -127,7 +233,8 @@ struct Opd {
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 */
std::vector<uint8_t> master; /* the drawn bytes */
GBuf a, b; /* one guarded copy per side */
};
static inline int64_t desc_numel(const RadOpdDesc& d) {
@@ -140,11 +247,9 @@ 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. */
/* W4, W2 and MXFP4 have no store in the ABI's accessor, so the codes are written directly. Both
* plugins decode them with libref's codes (libref/ref_common.h), so the bytes mean the same to
* both sides, which is all 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;
@@ -156,6 +261,17 @@ static inline void h_narrow(const float* src, uint32_t dt, int64_t n, void* dst)
}
return;
}
if (dt == RAD_E8M0) {
/* An MX block's exponent byte: the power of two nearest the drawn magnitude, so a scale
* drawn at weight size lands near 2^-6, not at the store's 0 (2^-127). */
uint8_t* b = (uint8_t*)dst;
for (int64_t i = 0; i < n; ++i) {
const float a = std::fabs(src[i]);
const long e = a > 0.0f && std::isfinite(a) ? 127 + std::lrint(std::log2(a)) : 127;
b[i] = (uint8_t)(e < 1 ? 1 : (e > 254 ? 254 : e));
}
return;
}
if (dt == RAD_I2) {
uint8_t* b = (uint8_t*)dst;
std::memset(b, 0, dt_bytes(dt, n));
@@ -169,33 +285,9 @@ static inline void h_narrow(const float* src, uint32_t dt, int64_t n, void* dst)
for (int64_t i = 0; i < n; ++i) rad_store_f32(dst, dt, i, src[i]);
}
/* Packed codes decode with libref's codes, through avx_common.h's ld_elem. */
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);
for (int64_t i = 0; i < n; ++i) dst[i] = avx::ld_elem(src, dt, i);
}
static inline void h_draw(std::vector<Opd>& o, size_t k, int64_t M, uint64_t seed) {
@@ -203,27 +295,49 @@ static inline void h_draw(std::vector<Opd>& o, size_t k, int64_t M, uint64_t see
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;
/* A weight table (a MoE layer's experts) is described stacked, [n_expert, ...], and drawn as
* any weight; left undrawn, every expert would be zeros and the product would compare zeros. */
const bool weight = d.role == RAD_OPD_WEIGHT || d.role == RAD_OPD_WTAB;
if (d.role != RAD_OPD_IN && d.role != RAD_OPD_INOUT && !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;
const bool idx_pre = (d.d.flags & RAD_OPD_F_IDX_PREFIX) != 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. */
/* Integer and packed codes are whole numbers, so a draw at weight scale would store every
* code as 0 and the product would compare zeros with zeros. They are drawn to span their grid
* instead: int8 at sigma 40, the 4- and 2-bit codes at unit sigma (h_narrow scales a 4-bit
* draw by 3). */
const bool codes = d.d.dtype == RAD_I8 || d.d.dtype == RAD_I4 || d.d.dtype == RAD_I2 ||
d.d.dtype == RAD_FP4E2M1;
if (codes && !is_index) {
fill_normal(tmp.data(), n, seed, d.d.dtype == RAD_I8 ? 40.0f : 1.0f);
} else if (weight && !is_index) {
/* Sigma 0.02, the size of real checkpoint weights. At unit variance an fp8 quantiser's
* amax would be orders of magnitude away from anything a 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. */
/* Cumulative sequence lengths over [0, T]: the batch's shape, not random. */
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_pre) {
/* A routing histogram's offsets (moe_scatter's `expert_offset`): non-decreasing from 0 to
* idx_max - 1. Drawn at random they are a malformed histogram, which a binary and a linear
* search read differently with neither wrong. Sorted draws, pinned at both ends. */
uint64_t s2 = seed;
const int64_t top = d.d.idx_max > 0 ? d.d.idx_max - 1 : 0;
for (int64_t i = 0; i < n; ++i)
tmp[(size_t)i] = (float)(hsplitmix(s2) % (uint64_t)(top + 1));
std::sort(tmp.begin(), tmp.end());
tmp[0] = 0.0f;
tmp[(size_t)(n - 1)] = (float)top;
} 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. */
/* Distinct scatter destinations: two writes to one slot race, and the two plugins would
* resolve the race differently. */
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);
@@ -245,13 +359,12 @@ static inline void h_draw(std::vector<Opd>& o, size_t k, int64_t M, uint64_t see
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]));
tmp[(size_t)i] = 1.0f / (1.0f + sc_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. */
/* Unit diagonal, small off-diagonal. `A` is the chunked delta rule's intra-chunk
* matrix I + tril(diag(beta) K K^T, -1), which is unit lower triangular; that is what
* keeps its inverse bounded. A random diagonal would make the comparison measure the
* input's condition number. */
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;
@@ -272,7 +385,7 @@ static inline void h_draw(std::vector<Opd>& o, size_t k, int64_t M, uint64_t see
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)]));
acc -= sc_log1p(sc_exp(tmp[(size_t)(t * heads + h)]));
tmp[(size_t)(t * heads + h)] = acc;
}
}
@@ -293,11 +406,10 @@ static inline void h_draw(std::vector<Opd>& o, size_t k, int64_t M, uint64_t see
/* ================================================================== 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.
* The only op-specific knowledge in these tools, given as parameters; shapes come from libref's
* `opd_shape`. Values are small but not degenerate: rows wider than a vector, more than one row, a
* dividing group and, where allowed, a row length that is not a multiple of the vector width, to
* exercise the tail.
*/
struct P { const char* k; int kind; long long i; const char* s; double d; };
@@ -313,33 +425,24 @@ static inline RadParam h_mk(const P& p) {
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. */
/* Bytes moved and flops done, for the bench's rate columns. 0 means no rate is reported (the
* cost is not a simple function of the geometry). */
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. */
/* Timed at a real model shape but not checked there; rad-avx-check skips it. A 640-wide row
* exercises every code path a 2048-wide one does, but speed depends on the cache hierarchy
* and needs the real shape. Same split as tools/kfixture.h. */
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.
/* Total token count of the batch, which the cumulative-length draw divides across sequences and
* which 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. */
* It is not always the ranged parameter. An op banded on `M` is banded on the total
* (`gdn_conv_prep`: activation [M, conv_dim], cu spans M). An op banded on `q_len` is banded on
* the per-sequence length (`gdn_conv_update`: activation [n_seq * q_len, conv_dim], q_len candidate
* rows per sequence), so the total is q_len * n_seq. With cu summing to q_len instead, libref
* derives a doubled head count from numel(q) / (T * head_k) and refuses the case with RAD_E_SHAPE.
* `attn_paged` is also banded on `q_len`; libref describes it at one sequence. */
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;
@@ -357,11 +460,6 @@ static inline const char* case_dtype(const Case& c) {
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;
@@ -377,18 +475,17 @@ static inline std::string case_str(const Case& c) {
}
/* ================================================================== 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. */
* Operands sized by the oracle's description, drawn once and copied into one buffer per side, so
* both plugins see byte-identical inputs. */
struct Prepared {
bool ok = false;
bool skipped = false; /* the oracle declined this geometry -- a real answer */
bool skipped = false; /* the oracle declined this geometry */
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;
GBuf sa, sb; /* each side's scratch, when its kernel asks for one */
};
static inline void h_build_tensors(std::vector<Opd>& opd, bool side_a,
@@ -409,10 +506,64 @@ static inline void h_build_tensors(std::vector<Opd>& opd, bool side_a,
}
}
/* `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. */
/* The samplers' per-row `params` are a RadSampleParams struct (abi/rad_sample.h). libref describes
* them with RAD_FILL_SAMPLE_PARAMS and the history with RAD_OPD_F_IDX_HISTORY, laws h_draw does not
* implement: it draws such a plane as normals, whose integer fields and `flags` are bit patterns
* no stage acts on, and such a history as uniform ids, which never repeat. Each row is written as
* a request instead, rows differing in temperature, top-p, min-p and typical-p, with every stage
* switched on except on the last row, which is greedy. The history's second half repeats its
* first, so DRY finds repeats to penalise. rad-kbench draws the laws themselves. */
static inline void h_sampler_rows(Prepared& pr, const Case& c) {
if (std::strncmp(c.op, "sample_", 7) != 0) return;
Opd* params = nullptr;
Opd* hist = nullptr;
for (size_t k = 0; k < pr.opd.size(); ++k) {
const char* nm = pr.schema->operands[k].name;
if (!nm || pr.opd[k].absent || pr.opd[k].d.rank != 2) continue;
if (!std::strcmp(nm, "params")) params = &pr.opd[k];
if (!std::strcmp(nm, "history") && pr.opd[k].d.dtype == RAD_I32) hist = &pr.opd[k];
}
const int64_t words = (int64_t)(sizeof(RadSampleParams) / 4);
if (!params || rad_dtype_bits(params->d.dtype) != 32 || params->d.shape[1] != words) return;
const int64_t M = params->d.shape[0];
const int64_t hw = hist ? hist->d.shape[1] : 0;
for (int64_t r = 0; r < M; ++r) {
RadSampleParams sp{};
sp.seed = 0x5eed0000u + (uint64_t)r;
sp.pos = 7 * (uint64_t)r;
sp.temp = 0.6f + 0.2f * (float)(r % 4);
sp.top_p = 0.9f - 0.1f * (float)(r % 3);
sp.min_p = 0.02f + 0.03f * (float)(r % 3);
sp.typical_p = 0.95f - 0.1f * (float)(r % 3);
sp.rep_penalty = 1.1f;
sp.freq_penalty = 0.2f;
sp.pres_penalty = 0.3f;
sp.xtc_probability = r % 2 ? 0.5f : 1.0f;
sp.xtc_threshold = 0.05f;
sp.dry_multiplier = 0.8f;
sp.dry_base = 1.75f;
sp.top_k = r % 2 ? 0 : 8;
sp.penalty_last_n = r % 3 ? (int32_t)hw : -1;
sp.dry_allowed_length = 2;
sp.dry_penalty_last_n = -1;
sp.hist_off = 0;
sp.hist_len = (int32_t)hw;
sp.mask_row = r % 2 ? (int32_t)r : -1;
sp.flags = RAD_SP_PENALTY | RAD_SP_XTC | RAD_SP_DRY | RAD_SP_LOGPROBS |
(sp.mask_row >= 0 ? RAD_SP_MASK : 0);
if (r == M - 1 && M > 1) sp.flags = RAD_SP_GREEDY;
std::memcpy(params->master.data() + (size_t)r * sizeof sp, &sp, sizeof sp);
}
if (hist)
for (int64_t r = 0; r < hist->d.shape[0]; ++r) {
int32_t* row = (int32_t*)hist->master.data() + r * hw;
for (int64_t j = hw / 2; j < hw; ++j) row[j] = row[j - hw / 2];
}
}
/* `describe` is the kernel whose opd_shape sizes the operands. A correctness check passes the
* oracle's, since the reference semantics define the extents; a benchmark of a kernel with no
* oracle passes its own (as tools/opshapes.h does for rad-kbench). */
static inline Prepared h_prepare(const Lib& oracle, const RadKernelInfo* describe, const Case& c,
const RadKernelInfo* ka, const RadKernelInfo* kb) {
Prepared pr;
@@ -425,7 +576,7 @@ static inline Prepared h_prepare(const Lib& oracle, const RadKernelInfo* describ
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 */
d.idx_const = -1; /* the ABI's "draw"; a hook that leaves it gets the default */
if (describe->opd_shape(pr.params.data(), (int)pr.params.size(), i, &d) < 0) {
pr.skipped = true;
return pr;
@@ -435,8 +586,8 @@ static inline Prepared h_prepare(const Lib& oracle, const RadKernelInfo* describ
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. */
/* A rank the ABI cannot express is a hook bug; it must not become a zero-extent buffer
* that every comparison passes vacuously. */
if (!o.absent && (d.rank == 0 || d.rank > RAD_MAX_RANK)) { pr.skipped = true; return pr; }
}
@@ -448,8 +599,11 @@ static inline Prepared h_prepare(const Lib& oracle, const RadKernelInfo* describ
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_sampler_rows(pr, c);
for (Opd& o : pr.opd) {
o.a.assign(o.master);
o.b.assign(o.master);
}
h_build_tensors(pr.opd, true, &pr.ta);
@@ -461,25 +615,30 @@ static inline Prepared h_prepare(const Lib& oracle, const RadKernelInfo* describ
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. */
/* Honour the scratch hook; a kernel that declares one and gets null would fault. */
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 (n > 0) {
pr.sa.assign(nullptr, (size_t)n);
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; }
if (n > 0) {
pr.sb.assign(nullptr, (size_t)n);
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). */
/* Restore both sides to the drawn bytes. A loop that relaunches an op with an INOUT operand must
* reset between iterations, or each iteration computes something different (twenty runs of
* `rope` rotate the tensor twenty times over). */
static inline void h_reset(Prepared& pr) {
for (Opd& o : pr.opd) {
if (o.absent || o.n <= 0) continue;
+158 -183
View File
@@ -1,12 +1,9 @@
/* avx_hc.cpp -- the GATED RESIDUAL pair and the MTP head's entry.
/* avx_hc.cpp -- the gated residual pair (hc_read / hc_write) 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.
* Gated residual: Qwen4-Exp's replacement for pre-norm + residual add. The residual stream is `hc`
* times the model width (hidden 2560 at hc 4 is a 10240-wide stream), entered as hc copies of the
* embedding and collapsed once at the end. Each block reads a mix of the streams and writes its
* output back into all of them; both the mix and the per-stream write gain are data-dependent.
*
* hc_read N = grouped_rmsnorm(h) one rsqrt per n-wide stream, one gain of
* hc*n over all of them, `1 + w`
@@ -15,86 +12,51 @@
* 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):
* Three independent facts any implementation must match (docs/OPS.md); each fails silently:
* - The write updates the unnormed `h`, not `N`. Writing into `N` re-normalises the residual at
* every connection and diverges within a few layers while still producing fluent text.
* - The mix is a mean over the hc dimension, not a sum.
* - Each gate argument has its own `/ hc` (before the silu and before the inject sigmoid).
*
* 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.
* Rounding: the reference model's grouped norm returns `.type_as(x)`, so both matrix products and
* the final multiply read a bf16 `N`. As in libref, N is rounded through h's dtype (per row here,
* via the row converter); likewise the silu output, the sigmoid gate, and `x` before the optional
* fp8 quantiser reads it back.
*
* 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.
* hc_read runs as three parallel passes over the mixing matrices' rows, each row decoded in the
* kernel (E4M3 codes times their scales, or a plain row widened) into the thread's own buffer and
* met by every token row before the next: `down` [lowrank, hc*n] over its rows, then `up` [hc*n,
* lowrank] over the n output columns (hc rows each). A decode step reads each matrix once, spread
* over the team, and no widened copy of either is written. The token rows' norms, gates and mixes
* live in one scratch_raw block between the passes, since a second scratch_raw call may
* reallocate the first while workers read it.
*/
#include "avx_vec.h"
#include "avx_common.h"
#include "avx_planes.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);
/* Row r of a weight plane `cols` wide as f32, addressed as libref does (rowoff / laststride) so
* strided or rank-3 weights work. A joined plane (codes and a scale, avx_planes.h) decodes; `jr`
* is its view. */
static void plane_row(const RadTensor* t, const avxp::ScaledRows* jr, int64_t r, int64_t cols,
float* dst) {
if (jr) {
scaled_row(*jr, r, cols, dst);
return;
}
const int64_t st = laststride(t), b = rowoff(t, r, cols);
if (st == 1) row_to_f32(t->dtype, byte_at(t->data, t->dtype, b), dst, cols);
else for (int64_t i = 0; i < cols; ++i) dst[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. */
/* Sum of squares in f64, unlike avx_norm.cpp's f32, matching libref's split: `rmsnorm` is checked
* against fast kernels and accumulates in f32, while this norm is an internal step of a fused op.
* Scalar: one reduction per stream, dominated by the two matrix products. */
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];
@@ -102,11 +64,9 @@ static float rsqrt_meansq_f64(const float* v, int64_t n, float 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. */
/* The wide stream's initial value: hc identical copies of the embedding, one launch per step. A
* separate op because the embedding lookup's output width is n. The streams diverge at the first
* connection, where each gets its own write gain. */
AVX_KERNEL(hc_enter) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor* x = &a->t[0];
@@ -123,9 +83,7 @@ AVX_KERNEL(hc_enter) {
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. */
/* One contiguous stream at a time (libref interleaves streams, writing at stride n). */
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]);
@@ -135,8 +93,8 @@ AVX_KERNEL(hc_enter) {
/* ------------------------------------------------------------------ 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. */
/* Not `rad_args_have(a, 6)`: operand 4 (the inject weight) is optional and absent on the
* final mixer. Operands 0..3 and 5 are required. */
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;
@@ -149,7 +107,7 @@ AVX_KERNEL(hc_read) {
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* rq = rad_arg_in(a, 9); /* rotated fp8 form, for a w4a8h consumer */
const RadTensor* rs = rad_arg_in(a, 10);
const int64_t n = p_int(a, "n", 0);
@@ -161,11 +119,24 @@ AVX_KERNEL(hc_read) {
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 (rows <= 0 || numel(x) < rows * n || numel(w) < hn) return RAD_E_SHAPE;
/* Plain mixing matrices, or codes and a scale joined (`mix` e4m3), libref's reading: a plain
* matrix's dtype is what its gate is narrowed to, a joined one's gates are narrowed to h's. */
avxp::ScaledRows jd, ju;
const bool jdown = avxp::is_joined(down), jup = avxp::is_joined(up);
if (jdown) {
if (const int st = avxp::scaled_rows(down, lr, hn, &jd); st != RAD_OK) return st;
} else if (numel(down) < lr * hn) {
return RAD_E_SHAPE;
}
if (jup) {
if (const int st = avxp::scaled_rows(up, hn, lr, &ju); st != RAD_OK) return st;
} else if (numel(up) < hn * lr) {
return RAD_E_SHAPE;
}
const uint32_t ddt = jdown ? h->dtype : down->dtype, udt = jup ? h->dtype : up->dtype;
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. */
/* An inject weight without an `inj` output (consumed by hc_write) is a caller error. */
if (injw && (!inj || !inj->data || numel(inj) < rows * hc)) return RAD_E_SHAPE;
int64_t g = 0, ngrp = 0;
@@ -175,10 +146,8 @@ AVX_KERNEL(hc_read) {
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. */
/* The rotated form is had_quant_act_fp8 of the stored `x`: each scale group is rotated whole,
* so the group must be a power of two that tiles the row. */
int64_t rg = 0;
if (rq && rq->data) {
rg = p_int(a, "group", 0);
@@ -188,40 +157,40 @@ AVX_KERNEL(hc_read) {
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. */
/* The gain, the inject rows (hc of them, widened once), and the token rows' norms N [rows][hn],
* gates D [rows][lr] and mixes X [rows][n], in one scratch_raw block (see header). */
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;
const size_t o_inj = pad(o_gain + (size_t)hn);
const size_t o_N = pad(o_inj + (injw ? (size_t)hc * (size_t)hn : 0));
const size_t o_D = pad(o_N + (size_t)rows * (size_t)hn);
const size_t o_X = pad(o_D + (size_t)rows * (size_t)lr);
const size_t total = o_X + (size_t)rows * (size_t)n + 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;
float* NP = blk + o_N;
float* DP = blk + o_D;
float* XP = blk + o_X;
{
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);
if (injw)
for (int64_t c = 0; c < hc; ++c) plane_row(injw, nullptr, c, hn, iw + c * hn);
const avxp::ScaledRows* jdp = jdown ? &jd : nullptr;
const avxp::ScaledRows* jup_p = jup ? &ju : nullptr;
const float invhc = 1.0f / (float)hc;
/* ---- grouped norm: one rsqrt per stream, the full-width gain, then one round trip through
* h's dtype for the whole wide row. */
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);
float* N = NP + r * hn;
float* tmp = scratch_f32((size_t)hn);
const float* hv = in_row(h, rowoff(h, r, hn), 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);
@@ -235,68 +204,71 @@ AVX_KERNEL(hc_read) {
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 read gate's first product, hc*n -> lowrank, and the silu, one row of `down` at a
* time against every token row. */
AVX_PARALLEL_FOR_IF(rows * lr * hn >= 65536)
for (int64_t j = 0; j < lr; ++j) {
float* wr = scratch_f32((size_t)hn);
plane_row(down, jdp, j, hn, wr);
for (int64_t r = 0; r < rows; ++r) {
const float t = dotf(NP + r * hn, wr, hn) / (float)hc;
DP[r * lr + j] = narrow1(ddt, t / (1.0f + sc_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) {
/* ---- the second product, lowrank -> hc*n, its sigmoid, and the mix: the mean over the
* streams. Output column i reads `up` rows c*n + i of every stream c. */
AVX_PARALLEL_FOR_IF(rows * lr * hn >= 65536)
for (int64_t i = 0; i < n; ++i) {
float* ur = scratch_f32((size_t)(hc * lr));
for (int64_t c = 0; c < hc; ++c) plane_row(up, jup_p, c * n + i, lr, ur + c * lr);
for (int64_t r = 0; r < rows; ++r) {
const float* N = NP + r * hn;
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];
const float gv = dotf(DP + r * lr, ur + c * lr, lr);
acc += narrow1(udt, 1.0f / (1.0f + sc_exp(-gv))) * N[c * n + i];
}
xv[i] = acc * invhc;
XP[r * n + 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]);
}
AVX_PARALLEL_FOR_IF(rows >= 2)
for (int64_t r = 0; r < rows; ++r) {
float* N = NP + r * hn;
float* xv = XP + r * n;
float* tmp = scratch_f32((size_t)hn);
out_row(x, rowoff(x, r, n), n, xv);
/* ---- 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)));
stt(inj, ib + c * is, 2.0f / (1.0f + sc_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. */
/* ---- optional fp8 form of x, taken from the stored (narrowed) value rather than the
* accumulator, as a fused kernel must, so the two agree bit for bit. */
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. */
float* qv = N; /* the row's norm is dead here; its storage takes the codes. */
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);
}
float sc;
fp8_group(xv, qv, k0, k1, &sc);
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]);
out_row(q, rowoff(q, r, n), n, qv);
}
/* ---- the optional ROTATED fp8 form of x, from the same stored values. */
/* ---- 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;
@@ -308,17 +280,15 @@ AVX_KERNEL(hc_read) {
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]);
out_row(rq, rowoff(rq, r, n), n, rc);
}
}
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. */
/* h[s] += inj[s] * y for each of the hc streams, in place, on the unnormed stream the paired read
* received. */
AVX_KERNEL(hc_write) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor* y = &a->t[0];
@@ -363,36 +333,27 @@ AVX_KERNEL(hc_write) {
/* ================================================================== mtp_enter
*
* THE MULTI-TOKEN-PREDICTION HEAD'S ENTRY, for a model whose residual stream is `hc` wide.
* Entry of the multi-token-prediction head for a model with an `hc`-wide residual stream.
*
* 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.
* A pre-norm MTP head usually joins the trunk's hidden state and the next token's embedding with one
* `fc` over their concatenation. Qwen4-Exp's hidden state is the wide stream and the checkpoint has
* two square matrices: `fc_h` is applied to each of the hc sub-streams, and one n-wide embedding
* product is 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.
* `ngroup` is not determined by the checkpoint: a [hc*n] gain fits both a grouped norm (hc rsqrts)
* and a flat one (one rsqrt over the wide row). No per-op oracle distinguishes them (the draft
* acceptance rate does), so it is a parameter fixed 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.
* Run as a GEMM. libref converts `fc_h` and `fc_e` inside the innermost loop, `rows * hc` times.
* Here the norms are first materialised into panels ([rows*hc, n] hidden, [rows, n] embedding),
* then each output column i widens row i of `fc_h` and `fc_e` once and contracts it against every
* panel row. The whole [n, n] weight is never widened (26 MiB per matrix at n = 2560); each weight
* element is still converted once.
*/
AVX_KERNEL(mtp_enter) {
if (!rad_args_have(a, 7)) return RAD_E_INVAL;
@@ -416,7 +377,19 @@ AVX_KERNEL(mtp_enter) {
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;
/* Plain fc matrices, or codes and a scale joined (`fc` e4m3), as hc_read's. */
avxp::ScaledRows jh, je;
const bool jfh = avxp::is_joined(fc_h), jfe = avxp::is_joined(fc_e);
if (jfh) {
if (const int st = avxp::scaled_rows(fc_h, n, n, &jh); st != RAD_OK) return st;
} else if (numel(fc_h) < n * n) {
return RAD_E_SHAPE;
}
if (jfe) {
if (const int st = avxp::scaled_rows(fc_e, n, n, &je); st != RAD_OK) return st;
} else if (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;
@@ -441,8 +414,8 @@ AVX_KERNEL(mtp_enter) {
}
}
/* 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. */
/* Phase one: both norms into the panels, rounded to their source tensor's dtype (the
* reference model's `.type_as(x)`). */
AVX_PARALLEL_FOR_IF(rows * hn >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* buf = scratch_f32((size_t)hn);
@@ -470,17 +443,19 @@ AVX_KERNEL(mtp_enter) {
}
}
/* Phase two: one output column at a time, so each weight row is widened exactly once. */
/* Phase two: one output column at a time, so each weight row is widened 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);
const int64_t fhb = jfh ? 0 : rowoff(fc_h, i, n), fhs = laststride(fc_h);
const int64_t feb = jfe ? 0 : rowoff(fc_e, i, n), fes = laststride(fc_e);
if (jfh) scaled_row(jh, i, n, fh);
else 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);
if (jfe) scaled_row(je, i, n, fe);
else 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) {
+50 -56
View File
@@ -1,49 +1,34 @@
/* avx_isa.h -- what this machine can execute, and the one list of ops the whole plugin is built
* around.
/* avx_isa.h -- CPU feature detection, and the single list of ops the plugin is built around.
*
* ============================== WHY A DISPATCH AT ALL ==============================
* Why dispatch. The plugin is a shared object the engine dlopens (spec.md §2) and runs on machines
* it was not built on, so -march=native is out: an AVX-512 build SIGILLs on older CPUs. A baseline
* build gives up most of the machine (an AVX-512 rmsnorm moves 64 bytes a cycle, SSE2 16). So the
* kernels are compiled once per ISA level into separate objects with their own -m flags, and one
* baseline translation unit (avx_dispatch.cpp) picks between them at load. Nothing outside the
* per-level objects may contain an instruction above the baseline: the dispatcher, registry and
* schemas are built without -m flags, since a stray intrinsic there would fault before dispatch.
*
* 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.
* Levels:
* AVX_LEVEL_SCALAR (0) x86-64 baseline. The compiler uses SSE2 for scalar float, but nothing is
* hand-vectorised. Always selectable; every other level is checked
* against it.
* 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.
* Nearly every x86 machine since 2013.
* AVX_LEVEL_AVX512 (3) AVX-512 F/BW/DQ/VL. Besides the width: 32 vector registers instead of 16
* (room for the GEMM microkernel's 12x2 accumulator block) and write
* masks, which remove the scalar tail loops.
*
* 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.
* AVX-512 is checked as the conjunction F && BW && DQ && VL: Knights Landing has F without the
* others. __builtin_cpu_supports is used instead of raw CPUID because it also checks XGETBV; a CPU
* may enumerate AVX-512 while the OS has not enabled ZMM state, and using it then faults.
*
* ============================== 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).
* AVX_OP_LIST is the only place the op set is written. It generates the table struct, the four
* table declarations, the registry's baseline thunks and the harness's op enumeration. An op
* missing a definition at any level is a link error, never a null table entry. (libref uses the
* same technique for its shape hooks, libref/ref_ops.h.)
*/
#ifndef RAD_AVX_ISA_H
#define RAD_AVX_ISA_H
@@ -68,17 +53,17 @@ int avx_isa_detect(void);
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. */
/* Force a level; for the checker only. An exported symbol rather than an environment variable, so
* a deployment cannot change what a kernel computes by accident and the engine never reaches it.
* Returns the level selected, min(requested, detected): a level the CPU cannot execute would
* SIGILL. */
int avx_isa_force(int level);
/* Run every parallel region with `threads` team threads whatever its work threshold, or restore
* the thresholds with 0; for the checker only, like avx_isa_force. Returns the team size now
* forced, 0 when the plugin was built without OpenMP. */
int avx_par_force(int threads);
/* ================================================================== 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. */
@@ -94,9 +79,11 @@ int avx_isa_force(int level);
X(scale_rows) X(scale) X(fill) X(act_mul) \
X(seg_mean) X(mul_weight) X(pool_rows) X(relu) \
X(clamp) X(conv2d) X(conv1d_dw) X(rel_sinusoid) \
X(seg_sinusoid) X(conv2d_unfold) \
/* ---- 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(quant_act_i8) X(quant_act_i8g) 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) X(givens_rotate) X(givens_dense_quant) \
/* ---- gemm and the vocabulary edges */ \
X(gemm_nt) X(gemm_nt_bias) X(gemm_nt_q) X(gemm_nt_q_bias) \
@@ -104,6 +91,7 @@ int avx_isa_force(int level);
/* ---- attention */ \
X(attn_paged) X(attn_dense) X(kv_store) X(rope) \
X(rope_table) X(qk_norm_rope) X(qsa_block_key) X(attn_local_rel) \
X(qsa_score) X(qsa_select) X(qsa_tail_store) X(qsa_work) \
/* ---- 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) \
@@ -113,14 +101,20 @@ int avx_isa_force(int level);
X(gdn_recurrent_update) X(gdn_conv_recurrent_update) X(gdn_gated_rmsnorm) \
/* ---- collectives */ \
X(all_reduce) X(all_gather) \
/* ---- image generation */ \
X(ln_mod) X(gate_add) X(ln_mod_quant_fp8) X(timestep_embed) \
X(gather_rows2) X(lane_gather) X(lane_store) X(randn_lanes) \
X(flow_euler) X(chan_affine) X(conv2d_nhwc) X(l2norm_chan) \
X(d2s_add) X(s2d_avg_add) X(to_rgba8) X(gelu_tanh) \
X(scatter_add_rows) X(attn_prefix_self) \
/* ---- 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(sample_logprobs) X(dflash_select)
X(sample_logprobs) X(dflash_select) X(dflash_conv)
/* 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. */
/* One ISA level's table: one member per op, in AVX_OP_LIST order. A missing definition is a link
* error from that level's avx_table.cpp object. */
typedef struct AvxKernelTable {
#define AVX_DECL_MEMBER(nm) int (*nm)(const RadArgs*, RadStream);
AVX_OP_LIST(AVX_DECL_MEMBER)
@@ -135,7 +129,7 @@ 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. */
/* The live table the thunks call. Repointed by avx_isa_force. */
const AvxKernelTable* avx_table_live(void);
#ifdef __cplusplus
+93 -150
View File
@@ -1,41 +1,26 @@
/* avx_misc.cpp -- the PLE pair, the hashed n-gram ids, and the two collectives.
/* avx_misc.cpp -- the PLE pair, the hashed n-gram ids, and the two collectives. Mostly scalar:
*
* 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 vectorises the per-stream norms and the gated broadcast of `v`. The dot between the
* two normed streams is accumulated in f64, as in libref: it feeds a signed square root, whose
* relative sensitivity is unbounded near zero, so an f32 reduction over a 10240-wide product
* would move the gate past tolerance on rows near the hinge.
*
* 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 width-4 depthwise convolution with taps `dilation` apart; channels are the
* parallel axis and the four-term inner loop has nothing to vectorise.
*
* 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, using torch's arithmetic (a
* wrapping 64-bit multiply and a flooring modulo).
*
* 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.
* all_reduce / all_gather serve world size 1 only and refuse wider worlds (see below).
*/
#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. */
/* Reciprocal RMS of one n-wide stream, accumulated in f64 as libref's `group_rsqrt`. The rsqrt is
* per stream while the gain spans all hc*n; that is 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];
@@ -43,21 +28,18 @@ static float group_rsqrt_f64(const float* v, int64_t n, float 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
/* k [M][hc*n] key_proj(embedding), unnormed
* q [M][hc*n] the incoming hyper-connection stream, unnormed
* 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
* gv [M][hc*n] out, unnormed: read by the residual add
* gvn [M][hc*n] out, normed: read by the convolution
*
* 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 third norm is taken over gv as stored (rounded through its dtype), which is why this op owns
* all three norms.
*
* 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. */
* Signed square root in the reference's order: clamp the magnitude to `gate_eps`, take the root,
* reapply the sign. Other orders differ near zero, where the gate usually sits. */
AVX_KERNEL(ple_gate) {
if (!rad_args_have(a, 8)) return RAD_E_INVAL;
const RadTensor* k = &a->t[0];
@@ -70,12 +52,12 @@ AVX_KERNEL(ple_gate) {
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. */
/* Rows come from `v` ([M, n]); the `M` parameter is the band's upper bound. */
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. */
/* Floor for the gate's magnitude 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;
@@ -83,8 +65,8 @@ AVX_KERNEL(ple_gate) {
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. */
/* The three gains, widened once with `wadd` folded in, in one allocation: a second
* scratch_raw call could 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;
@@ -98,7 +80,6 @@ AVX_KERNEL(ple_gate) {
}
}
const int64_t gls = laststride(gv), gnls = laststride(gvn);
AVX_PARALLEL_FOR_IF(M >= 2)
for (int64_t m = 0; m < M; ++m) {
@@ -116,8 +97,7 @@ AVX_KERNEL(ple_gate) {
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. */
/* f64: the dot feeds the signed square root (see the file header). */
double dot = 0;
for (int64_t d = 0; d < n; ++d) {
const int64_t j = c * n + d;
@@ -128,7 +108,7 @@ AVX_KERNEL(ple_gate) {
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 float g = 1.0f / (1.0f + sc_exp(-s));
const vf vg = vf_set1(g);
int64_t d = 0;
@@ -136,12 +116,9 @@ AVX_KERNEL(ple_gate) {
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]);
out_row(gv, gb, hn, out);
/* 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. */
/* Third norm over gv as stored: round `out` through gv's dtype in scratch. */
if (gv->dtype != RAD_F32) {
row_from_f32(gv->dtype, out, kv, hn);
row_to_f32(gv->dtype, kv, out, hn);
@@ -153,31 +130,30 @@ AVX_KERNEL(ple_gate) {
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]);
out_row(gvn, nb, hn, qv);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ ple_conv */
/* PLE's dilated depthwise convolution, silu AFTER it, and the residual add folded in.
/* PLE's dilated depthwise convolution, then silu, with the residual add folded in. Two rules,
* both silent when broken:
*
* TWO RULES THAT ARE NOT DERIVABLE AND ARE BOTH SILENT WHEN WRONG:
* `has_init` zero means the slot holds no history: the window before the first token is zeros.
* Otherwise a new sequence on a recycled slot convolves the previous sequence's tail into its
* first (width-1)*dilation tokens.
*
* 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 selects the window left behind (full contract: libref's
* ref_ple.cpp). Present, this is a decode step whose drafts may be rejected: the history read is
* offset by num_accepted - 1 and the state keeps the shifted history followed by every input of
* the step, so a next step that kept k tokens reads at k - 1. Absent, every token commits and the
* last (width-1)*dilation inputs land at offset zero.
*
* `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. */
/* ONE BODY FOR ple_conv AND causal_conv1d (LFM2's short convolution: undilated, no activation, no
* residual), as in libref, so the two cannot disagree about the window's layout. */
* The state is written in a second pass after all reads, since a sequence longer than the window
* would otherwise overwrite history it still reads.
*
* One body serves ple_conv and causal_conv1d (LFM2's short convolution: undilated, no activation,
* no residual), as in libref, so both use the same window layout. */
struct ConvOps {
const RadTensor *x, *w, *cs, *cu, *resid, *sidx, *hini, *nacc, *y;
bool silu;
@@ -189,14 +165,14 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) {
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. */
/* Rows come from `x` ([M, n]); the `M` parameter is the band's upper bound. */
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. */
/* The read window is a stack array (9 at PLE's shape); wider windows are refused rather than
* overflowing. Same bound as libref. */
enum { kHistMax = 64 };
if (hist_len > kHistMax) return RAD_E_UNSUPPORTED;
@@ -208,9 +184,8 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) {
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. */
/* Validate every sequence before writing any (an OpenMP body cannot return): the state must
* be deep enough for the offset and for the window a decode step leaves behind. */
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;
@@ -225,7 +200,7 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) {
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. */
/* [n_slots, n, state_len], dense, the same layout as gdn's conv state. */
const int64_t cs_slot = n * state_len, cs_ch = state_len;
AVX_PARALLEL_FOR_IF(N * n >= 64)
@@ -243,10 +218,8 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) {
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. */
/* Taps read once per channel (libref reads them per output element). Kept in scratch, not
* on the stack, so `width` needs no bound of its own. */
float* tap = scratch_f32((size_t)wid);
for (int64_t j = 0; j < wid; ++j) tap[j] = ldt(w, c * wrow + j * wcol);
@@ -259,7 +232,7 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) {
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 + (o.silu ? acc / (1.0f + std::exp(-acc)) : acc));
stt(y, (bos + t) * yrow + c * ycol, r + (o.silu ? acc / (1.0f + sc_exp(-acc)) : acc));
}
}
@@ -304,7 +277,7 @@ AVX_KERNEL(ple_conv) {
rad_arg_in(a, 6), rad_arg_in(a, 7), rad_arg_in(a, 8), true });
}
/* ple_conv's operands without `resid`, at dilation one and with no activation. */
/* ple_conv's operands without `resid`, dilation 1, no activation. */
AVX_KERNEL(causal_conv1d) {
if (a->n_t < 8) return RAD_E_INVAL;
if (p_int(a, "dilation", 1) != 1) return RAD_E_INVAL;
@@ -315,25 +288,16 @@ AVX_KERNEL(causal_conv1d) {
/* ------------------------------------------------------------------ ngram_ids
*
* ids[m][h] = (hash of the n-gram ending at m) % vocab[h] + offset[h].
* ids[m][h] = (hash of the n-gram ending at m) % vocab[h] + offset[h], in torch's arithmetic:
*
* THE ARITHMETIC IS TORCH'S, NOT C's, and both differences bite:
* Signed overflow is UB in C++ but wraps in torch, so the multiply goes through uint64.
* `torch.remainder` floors where C's `%` truncates, so the modulo is written out.
*
* 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.
* Neither matters on a real checkpoint (multipliers are bounded by (2^63-1)//vocab_size, so real
* products are non-negative); they make random test inputs match torch.
*
* `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. */
* Once a shift reaches EOS, every longer shift is EOS too, so the cut is carried. A cold slot's
* window is EOS, 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);
}
@@ -354,24 +318,24 @@ AVX_KERNEL(ngram_ids) {
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. */
/* Optional ids for the prompt that follows: `tok` holds that many more tokens after the
* step's, continuing the last sequence. The state window is still 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. */
/* Rows come from `tok` minus the prompt ahead; the `M` parameter is the band's upper bound. */
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 (M <= 0 || ngram < 2 || eos < 0) return RAD_E_SHAPE;
/* Heads form `ngram - 1` blocks of `heads_per_ngram`; block b uses 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 (ngram > 8) return RAD_E_UNSUPPORTED; /* the shift window is a stack array */
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;
@@ -380,8 +344,8 @@ AVX_KERNEL(ngram_ids) {
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. */
/* The state must hold 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;
@@ -393,8 +357,7 @@ AVX_KERNEL(ngram_ids) {
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. */
/* Per-head tables read once (libref reads them in the innermost loop). */
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;
@@ -406,9 +369,8 @@ AVX_KERNEL(ngram_ids) {
}
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. */
/* Serial over sequences, as in libref: the per-sequence work is a short integer loop, too
* little to pay for a parallel region. */
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));
@@ -439,8 +401,8 @@ AVX_KERNEL(ngram_ids) {
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. */
/* Mixes are extended in place: the (b+2)-gram's is the (b+1)-gram's XOR one more
* term. */
int64_t mixed = 0;
int64_t blk = -1;
for (int64_t k = 0; k < ngram; ++k) {
@@ -460,9 +422,9 @@ AVX_KERNEL(ngram_ids) {
}
}
/* 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. */
/* State window, written after all reads, in ple_conv's layout: with `num_accepted`, the
* history shifted by one followed by every id of the step; without, the last `ctx` ids at
* offset zero. */
const int64_t base = rowoff(st, slot, W);
if (nacc) {
for (int64_t i = 0; i + 1 < ctx; ++i)
@@ -482,37 +444,21 @@ AVX_KERNEL(ngram_ids) {
/* ================================================================== the collectives
*
* WORLD SIZE 1 ONLY, AND THAT IS A DELIBERATE LIMIT RATHER THAN AN OMISSION.
* World size 1 only, by design. libref implements real host collectives (one process, one thread
* per rank, a shared address space: a rendezvous, read every rank's pointer, rendezvous again),
* which lets the host backend exercise tensor-parallel graphs without a second card. That state (a
* barrier, a generation counter, a timeout) must exist once per process: a second copy in this
* plugin would form a separate rendezvous group, and ranks would deadlock whenever selection put
* them in different plugins. So above world 1 these return RAD_E_UNSUPPORTED and the selector
* falls through to libref.
*
* 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. */
* `exact` is honoured one way, as in libref: exact=0 permits a lossy wire but there is none here,
* so both settings get the exact result. */
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. */
/* The element count comes from the operand; the `numel` parameter 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;
@@ -520,8 +466,7 @@ AVX_KERNEL(all_reduce) {
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. */
/* In place: nothing to do. With a separate destination, copy x into it. */
if (!y) return RAD_OK;
if (rad_tensor_is_contiguous(x) && rad_tensor_is_contiguous(y)) {
const int64_t TILE = 8192;
@@ -539,16 +484,14 @@ AVX_KERNEL(all_reduce) {
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. */
/* The element count comes from the operand; the `numel` parameter 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. */
/* `row` has no effect at world 1 but is still validated, so an invalid graph fails the same
* way at world 1 as at world 2. */
const int64_t row = p_int(a, "row", 0);
if (row < 0 || (row > 0 && nel % row)) return RAD_E_SHAPE;
+993 -275
View File
File diff suppressed because it is too large. Load diff
+162 -260
View File
@@ -1,63 +1,34 @@
/* 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).
/* avx_ngram.cpp -- the row source for embed_lookup_q, and the table's stored layout.
* Baseline-compiled (no -m flags), like avx_dispatch.cpp; the vector decode comes from the calling
* level (avx_rows.h).
*
* ============================== WHY THIS GATHER IS A HOST KERNEL ==============================
* Why a host kernel. The n-gram embedding is 320,001,536 rows of 160 E4M3 bytes (51.2 GB), read 16
* rows per token. The engine's mechanisms for oversized weights do not fit that access pattern:
* Tier::SSD + DeviceStaged stages whole movement units, Site::DeviceZeroCopy needs pinned host RAM,
* and hipHostRegister on the mapping would pin all 51.2 GB. core/format/radfile.cpp mmaps the
* container, so the table already sits at a host address backed by an NVMe file. The gather runs
* on the host over that mapping and only the [T, n_embd] bf16 result crosses the link. The placement
* planner puts an op on the host when all its weight operands are Site::Host (core/runtime/ctx.cpp),
* so the table must be a weight operand (a plain `gather_rows` input would not trigger it), and a
* production host kernel is needed since libref is not served (rad_gate_reference_kernels).
*
* 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:
* Row cache plus direct reads. Decoding a row takes a few dozen cycles; fetching it is the cost,
* and at decode about half the rows a step wants have never been read before. The page cache is
* the wrong cache: a buffered miss costs the submitting thread ~4 us (page allocation, insertion,
* block mapping, bio), serialising a call's cold rows, and it keeps a 4 KiB page per 160-byte row
* (pages average ~1 useful row out of 25). So RowCache (below) holds rows, shared by every gathering
* thread, and a miss is an O_DIRECT read of the aligned span holding the row (~2 us to submit,
* 512 bytes instead of 4096). With eight varied sequences a 2^19-row cache (80 MiB) misses 51.0% of
* rows against 50.6% for an unbounded one.
*
* 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.
* Each miss is read once. Every rank gathers every row. A thread claims a missing row by marking
* its slot LOADING, reads it and publishes it READY; others wait instead of re-reading. Ranks start
* at different rows of a call, so the misses are split between them with no barrier.
*
* 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; direct_granule below finds the alignment the
* reads keep, including on a filesystem that does not report one. */
* The file is found from the mapping: the ABI passes a pointer, so /proc/self/maps gives the file
* and offset, once per table. A table not backed by a file (a test's heap buffer) is read as
* memory. A file on a filesystem without direct I/O is refused; direct_granule finds the read
* alignment, also where the filesystem reports none. */
#include "avx_rows.h"
#include "avx_common.h"
@@ -89,35 +60,33 @@
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. */
/* Prefetch distance, in rows, for cache lookups and decodes. Rows are scattered over an 80 MiB
* cache and the set words over 4 MiB, so each is an L3 or DRAM miss. */
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). */
/* One read of a row's aligned span: row m of the call, its key, and its cache slot (-1: decoded
* straight from the read, not cached). */
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. */
/* Per-thread working state for a call, kept between calls so steady-state calls do not
* allocate. */
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. */
/* One decode batch: each row's source and destination and, for cached rows, 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. */
/* Sources and destinations for rows decoded from a read's bounce buffer. */
std::vector<const uint8_t*> bsrc;
std::vector<uint16_t*> bdst;
uint8_t* bounce = nullptr;
@@ -126,9 +95,8 @@ struct Gather {
enum : uint8_t { PAD = 16, DONE };
/* A buffer of at least `bytes` on a page and on `align`, a power of two: a direct read's
* buffer has to keep the file's granule, which a filesystem with large blocks puts above a
* page. */
/* A buffer of at least `bytes`, aligned to max(page, `align`) (a power of two): direct reads
* need the file's granule, which can exceed a page on large-block filesystems. */
uint8_t* bounce_for(size_t bytes, size_t align) {
if (align < 4096) align = 4096;
if (bytes > bounce_bytes || align > bounce_align) {
@@ -149,9 +117,8 @@ inline Gather& gather_state() {
#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. */
/* The file behind a table: its mapping's address range, the file offset of the range's first byte,
* an O_DIRECT fd, and the granule reads must align to. `fd` is -1 for memory with no file. */
struct TableFile {
const uint8_t* lo = nullptr;
const uint8_t* hi = nullptr;
@@ -160,23 +127,18 @@ struct TableFile {
long long align = 0;
};
/* THE GRANULE OF A DIRECT READ of `t`'s file, opened for them as `t.fd`: the alignment a read's
* file offset, its length and its buffer's address must all keep. 0, with `*why` saying why, when
* the file cannot be read that way. [p, p + n) is the table, inside the mapping, and `ino` the
* mapped file's inode.
/* Granule of a direct read of `t`'s file (`t.fd`): the alignment the file offset, length and buffer
* address must all keep. Returns 0, with `*why`, if the file cannot be read that way. [p, p + n) is
* the table inside the mapping; `ino` is the mapped file's inode.
*
* STATX_DIOALIGN is the filesystem's own answer, and not every filesystem gives one: btrfs does
* direct reads and reports nothing, and so does a tmpfs since Linux 6.6. Without the report the
* granule is the file's block size, stx_blksize. No block filesystem's direct reads need more --
* a filesystem's blocks are never smaller than its device's sectors -- and btrfs needs exactly
* that: its sector size, below which it does not refuse a direct read but serves it through the
* page cache instead.
* STATX_DIOALIGN is used when reported. btrfs (and tmpfs since Linux 6.6) does direct reads but
* reports nothing; then the granule is stx_blksize. No block filesystem needs more (blocks are never
* smaller than device sectors), and btrfs needs exactly its sector size: below it, it silently
* serves direct reads through the page cache.
*
* Reported or not, one read proves the granule before any row is served: a span of the table at
* an offset and into a buffer each aligned to the granule and to no more, which has to return the
* bytes the mapping holds there. That catches a filesystem refusing the granule and a file that is
* not the one mapped. A btrfs serving the read through the page cache returns the right bytes and
* passes it; the block size is what keeps btrfs off that path. */
* One test read then proves the granule: a span at an offset and into a buffer aligned to the
* granule and no more, which must return the bytes the mapping holds. This catches a refused
* granule and a file that is not the one mapped. */
long long direct_granule(const TableFile& t, const uint8_t* p, long long n, unsigned long long ino,
const char* path, const char** why) {
struct statx sx;
@@ -204,7 +166,7 @@ long long direct_granule(const TableFile& t, const uint8_t* p, long long n, unsi
return 0;
}
/* An odd multiple of the granule, so neither the offset nor the buffer keeps more than it. */
/* An odd multiple of the granule, so neither offset nor buffer is over-aligned. */
const long long tab_lo = t.off + (long long)(p - t.lo);
long long o = (tab_lo + a - 1) & ~(a - 1);
if ((o / a) % 2 == 0) o += a;
@@ -234,10 +196,9 @@ long long direct_granule(const TableFile& t, const uint8_t* p, long long n, unsi
return a;
}
/* 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. */
/* The file behind [p, p + n): the mapping holding `p`, extended over following mappings of the same
* file (madvise on a sub-range splits a mapping). Looked up once per table and kept for the life of
* the process; rank threads share the entry and fd (reads use explicit offsets). */
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;
@@ -267,7 +228,7 @@ const TableFile* table_file(const uint8_t* p, long long n, int* err) {
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 */
if (inode == 0 || name.empty() || name[0] != '/') break; /* not file-backed */
found = true;
t->lo = (const uint8_t*)(uintptr_t)lo;
t->off = (long long)off;
@@ -303,22 +264,21 @@ const TableFile* table_file(const uint8_t* p, long long n, int* err) {
return known.back().get();
}
/* ============================== THE ROW CACHE ==============================
/* ============================== 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:
* Set-associative: a row's key (its byte offset in the file) hashes to a set of kWays slots; 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.
* `owner` is the loading thread, so a thread meeting its own claim (a row twice in one call) does
* not wait on itself. Readers copy a READY slot's bytes and re-read the word: bytes are rewritten
* only after the word leaves READY, so an unchanged word means a valid copy (a seqlock). Victims are
* chosen by CLOCK over per-slot reference bits kept outside the word (so marking a row used never
* fails a reader's check); LOADING slots are never victims.
*
* 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. */
* A set's eight words are one 64-byte line. The arrays are anonymous mappings, so memory is
* committed only as slots fill. */
struct RowCache {
static constexpr int kWays = 8;
static constexpr uint64_t kRows = 1ull << 19;
@@ -331,7 +291,7 @@ struct RowCache {
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 */
std::atomic<uint32_t> published{0}; /* bumped (and waited on) as each batch lands */
static uint64_t ready(uint64_t key) { return key << 10 | READY; }
@@ -345,9 +305,8 @@ struct RowCache {
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. */
/* The slot holding `key`: READY (HIT), loading by this thread (MINE) or another (THEIRS); or a
* slot claimed for it now (CLAIMED); or NONE when every slot of the set is loading. */
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;
@@ -367,7 +326,7 @@ struct RowCache {
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. */
* clear them all, so this fails only if 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);
@@ -384,12 +343,12 @@ struct RowCache {
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. */
/* Bytes are rewritten only after this (seqlock, 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. */
/* The set changed between the scan and the claim: retry. */
}
}
};
@@ -401,8 +360,7 @@ T* anon_array(size_t count) {
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. */
/* The cache for `n`-byte rows of `tf`, created on first use and kept for the process lifetime. */
RowCache* row_cache(const TableFile* tf, long long n) {
static std::mutex mu;
static std::vector<std::unique_ptr<RowCache>> caches;
@@ -422,11 +380,31 @@ RowCache* row_cache(const TableFile* tf, long long n) {
return caches.back().get();
}
/* This thread's owner tag in a LOADING word: distinct for every thread that gathers, 1..255. */
/* This thread's owner tag for LOADING words, 1..255, or 0 while 255 live threads hold one (such a
* thread cannot gather through the cache). A thread holds LOADING words only inside a call, so its
* tag is returned for reuse when it exits. */
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 Pool {
std::mutex mu;
std::vector<uint32_t> free;
uint32_t next = 0;
};
static Pool& pool = *new Pool; /* never destroyed: threads may exit after statics are */
struct Tag {
uint32_t v = 0;
Tag() {
std::lock_guard<std::mutex> lk(pool.mu);
if (!pool.free.empty()) { v = pool.free.back(); pool.free.pop_back(); }
else if (pool.next < 255) v = ++pool.next;
}
~Tag() {
if (!v) return;
std::lock_guard<std::mutex> lk(pool.mu);
pool.free.push_back(v);
}
};
static thread_local const Tag me;
return me.v;
}
struct ReadRing {
@@ -439,11 +417,10 @@ struct ReadRing {
io_uring_cqe *cqes = nullptr;
void *sq_ring = nullptr, *cq_ring = nullptr;
size_t sq_sz = 0, cq_sz = 0, sqe_sz = 0;
int err = 0; /* the errno that stopped init(), for ring_refusal() */
int err = 0; /* errno from a failed init(), for ring_refusal() */
/* 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. */
/* SINGLE_ISSUER and DEFER_TASKRUN: the ring is thread-local, and its thread only waits for
* batches it has just submitted, so completions run when it asks for them. */
bool init() {
io_uring_params p;
std::memset(&p, 0, sizeof p);
@@ -489,9 +466,8 @@ struct ReadRing {
}
~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. */
/* Reads the aligned span holding each row of `r[0, count)` (count <= entries) into `bounce`,
* one span per `stride` bytes, submitting and waiting in one call. Short reads fail. */
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;
@@ -531,9 +507,8 @@ struct ReadRing {
}
};
/* 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. */
/* This thread's ring, made on its first gather. Null if it could not be made, with the errno in
/* This thread's ring, created on its first gather over a file and destroyed at thread exit (each
* rank thread has its own, so they never contend). Null if it could not be made, with the errno in
* `*why`. */
inline ReadRing* read_ring(int* why) {
static thread_local bool tried = false;
@@ -549,10 +524,9 @@ inline ReadRing* read_ring(int* why) {
return r.get();
}
/* WHY THIS PROCESS CANNOT MAKE A RING, said in terms of what to change. Docker's default seccomp
* profile is by far the commonest: it answers EPERM to io_uring_setup, and so does the
* kernel.io_uring_disabled sysctl. A kernel too old for SINGLE_ISSUER and DEFER_TASKRUN answers
* EINVAL. */
/* Explains a ring failure in terms of the fix. EPERM: Docker's default seccomp profile or the
* kernel.io_uring_disabled sysctl. EINVAL: a kernel without SINGLE_ISSUER / DEFER_TASKRUN.
* ENOMEM: the ring's memory refused, e.g. over a locked-memory limit shared with other processes. */
std::string ring_refusal(int e) {
std::string s = "libavx: the n-gram table is read through io_uring, and this process cannot "
"make a ring (" + std::string(std::strerror(e)) + "). ";
@@ -565,11 +539,14 @@ std::string ring_refusal(int e) {
else if (e == EINVAL)
s += "The ring needs IORING_SETUP_SINGLE_ISSUER and IORING_SETUP_DEFER_TASKRUN, which "
"Linux 6.1 added.";
else if (e == ENOMEM)
s += "The kernel refused the ring's memory. It can count against the locked-memory limit "
"(ulimit -l), which every process of this user shares: raise it (LimitMEMLOCK= in a "
"systemd unit, --ulimit memlock=-1 for Docker) or stop other io_uring users.";
return s;
}
/* Whether this process can make the ring every gathering thread makes: 0, or the errno that
* stopped it. Asked once, by making one and closing it. */
/* 0 if this process can create a ring, else the errno. Tested once by creating and closing one. */
int ring_errno() {
static const int e = [] {
ReadRing r;
@@ -578,10 +555,9 @@ int ring_errno() {
return e;
}
/* 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. */
/* Reads `reads` through the ring in batches: rows with a slot are copied into the cache and
* published READY; rows without one are decoded directly into their output rows. On a failed read,
* every unpublished claim is released (word back to EMPTY) so no 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) {
@@ -622,17 +598,15 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g,
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. */
/* out[m] = decoded row ids[m] - voff for every m < M, through the cache: find or claim each row
* starting at row `first`, read this thread's claims, wait for rows other threads are reading, then
* decode from the cache. A row whose slot is taken over during the decode is read again directly. */
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. */
/* `n` is a row's bytes (cache and file offsets); `ne` its elements (decode and padding). */
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; };
@@ -666,9 +640,9 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG
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. */
/* Wait for rows other threads claimed to turn READY. `published` is read before the words, so
* a batch landing after the scan makes the wait return at once. Released claims (failed reads)
* and reused slots are read by this thread instead. */
while (!g.waits.empty()) {
const uint32_t e = rc.published.load(std::memory_order_acquire);
size_t keep = 0;
@@ -684,9 +658,8 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG
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. */
/* Decode all READY rows in one batch: each word is read before the bytes and again after the
* batch (the seqlock), and rows whose word changed are read again. */
g.src.clear();
g.dst.clear();
g.dm.clear();
@@ -716,21 +689,17 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG
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 ==============================
/* ============================== 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.
* A prefill chunk gathers `heads` rows per token (32,768 for a 2048-token chunk); on unseen text
* most are file reads (~30 ms per chunk on NVMe), during which the issuing thread waits and the card
* idles. 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, which claims, reads and publishes the
* missing rows while the chunk runs. The next call waits for LOADING rows as it would for the other
* rank's.
*
* 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. */
* Both ranks hand over the same ids; a repeated list is dropped. A failed read releases its claims
* and the next call reads those rows itself. The reader is detached and never destroyed. */
struct AheadJob {
const TableFile* tf = nullptr;
RowCache* rc = nullptr;
@@ -742,7 +711,7 @@ struct AheadReader {
std::mutex mu;
std::condition_variable cv;
std::deque<AheadJob> q;
uint64_t last = 0; /* the last id list taken, hashed */
uint64_t last = 0; /* hash of the last id list accepted */
void run() {
Gather& g = gather_state();
@@ -765,7 +734,7 @@ struct AheadReader {
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. */
/* Every read has a slot, so nothing is decoded and there is no output. */
(void)read_and_publish(*j.tf, *j.rc, *rr, g, g.reads, j.n, 0, nullptr, nullptr,
nullptr, 0);
}
@@ -781,7 +750,7 @@ AheadReader* ahead_reader() {
return r;
}
/* Hand the rows of `q.ahead` -- rows a later call will gather -- to the reader. */
/* Hands the rows of `q.ahead` (to be gathered by a later call) 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; }
@@ -808,61 +777,9 @@ void read_ahead(const TableFile& tf, RowCache& rc, const avx::RowGather& q) {
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
@@ -872,25 +789,18 @@ int avx::row_gather(const RowGather& q, RowDecode decode) {
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);
}
/* Cost has two regimes: repeated prompts hit the cache and read nothing, while varied serving
* makes about half of each step's rows new NVMe reads. A benchmark that repeats one prompt
* only measures the first. /proc/<pid>/io shows which regime applied. */
/* 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. */
/* bf16 value of every E4M3 code at this call's scale, built with the ABI's converters (so it
* matches libref); the decode is a table lookup. */
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. */
/* File-backed tables go through the shared cache; others are read from memory. The caller
* has already refused ids past the table, which matters once they become file offsets. */
int ferr = RAD_OK;
const TableFile* tfile = table_file(q.tab, q.n_vocab * q.row_bytes, &ferr);
if (!tfile) return ferr;
@@ -909,8 +819,7 @@ int avx::row_gather(const RowGather& q, RowDecode decode) {
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. */
/* Queue the rows a later call will gather, after this call's own rows. */
if (q.ahead && q.n_ahead > 0) read_ahead(*tfile, *rc, q);
return RAD_OK;
}
@@ -933,39 +842,34 @@ int avx::row_gather(const RowGather& q, RowDecode decode) {
return RAD_OK;
}
/* ============================== THE TABLE'S ENCODING, AND ITS ONE SCALE ==============================
/* ============================== the table's encoding and its one scale ==============================
*
* Asked at declare, not by a step (spec §4.3).
* Checked at declare (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.)
* The table is row-major E4M3 with one bf16 scale for the whole table, `fp8_e4m3*bf16[*x*]` (the
* shipped format). E4M3 carries its own exponent, a row's dynamic range is only ~2.3x, and the
* error is flat across scales from 2^-13 to 2^-10, so a per-row scale would buy a few percent of
* error for 1.25% more bytes. (INT8 in the same byte would do much better; 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. */
* The table is stored as is, so it can be read in place from the container's mapping (a relayout
* would copy 51 GB). This hook only validates; any other quantisation is refused. The one other
* accepted form is the checkpoint's plain bf16 table (102 GB), read the same way with no scale. */
namespace {
enum { EQ_TOK = 0, EQ_WTE, EQ_SCALE, EQ_X, EQ_AHEAD };
} /* namespace */
/* RAD_E_UNSUPPORTED is the accepted answer: the plane is stored as is (rad_abi.h, RadLayoutFn). */
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;
const int* sel, const RadTensor* pl, int n, RadLayout*) {
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. */
/* Or the checkpoint's plain bf16 table, with no scale plane; rows go through the same
* cache. */
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;
@@ -985,14 +889,12 @@ extern "C" int avx_layout_ngram(const RadParam* p, int n_p, int operand, const R
return RAD_E_UNSUPPORTED;
}
/* ============================== THE INSTANCE: CAN THIS PROCESS READ THE TABLE ==============================
/* ============================== the instance: can this process read the table ==============================
*
* Every miss of the gather into bf16 is an io_uring read, and a process that may not make a ring
* fails every step that gathers: the first request fails, after the whole model has loaded, and
* the engine stops. So the instance asks at declare, before a byte is loaded, and refuses with
* the reason. A gather into any other dtype takes the general path, which reads the table as
* memory and makes no ring. rad-convert declares without instances -- it launches nothing -- so a
* sandbox that forbids io_uring still converts the model. */
* A bf16 gather reads misses through io_uring, so a process that cannot create a ring would fail
* its first request after the whole model loaded. The instance checks at declare and refuses with
* the reason. Gathers into other dtypes read the table as memory and need no ring. rad-convert
* declares without instances, so a sandbox without io_uring can still convert models. */
extern "C" int avx_init_ngram(const RadParam* p, int n_p, int rank, int world_size, void** out) {
(void)rank;
(void)world_size;
+49 -75
View File
@@ -1,48 +1,28 @@
/* avx_norm.cpp -- rmsnorm, rmsnorm_add and layernorm.
/* avx_norm.cpp -- rmsnorm, rmsnorm_add, layernorm and the vision position-table adds.
*
* ============================== ONE PASS OVER THE ROW, TWICE ==============================
* Each norm is a reduction followed by a scale, so two passes over the row. The row is converted
* to f32 scratch once and both passes read the scratch (libref converts per element, three times
* per element in rmsnorm_add).
*
* 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 is `row_sumsq` (avx_support.cpp), a four-accumulator vector tree. It does not sum
* in libref's ascending-index order, which is why the bf16 tolerance for a norm is 4e-3, not 0.
*
* 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.
* Rounding contracts:
* `wadd` is GemmaRMSNorm's `1 +`, added in f32 after the weight is widened, never to the stored
* bf16 gain (Qwen3.5, Qwen3-Next and Gemma store a zero-centred gain; `1 + w` in bf16 loses 0.3%
* per channel). libr4d's fused norms do the same.
*
* ============================== 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.
* `rmsnorm_add` takes the variance from the unrounded f32 sum but multiplies the sum after it is
* narrowed into residual_out, as vLLM's fused_add_rms_norm does. Keeping f32 throughout would
* disagree with every fused kernel this is checked against.
*/
#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. */
/* Widen the gain once per launch, not once per row, into a caller buffer built before the
* parallel region and shared by all threads. `wadd` is folded in here, once per gain element. */
static void widen_gain(const RadTensor* w, int64_t n, float wadd, float* out) {
const int64_t ws = laststride(w);
if (ws == 1) {
@@ -63,7 +43,7 @@ static void widen_gain(const RadTensor* w, int64_t n, float wadd, float* out) {
AVX_KERNEL(rmsnorm) {
if (!a || a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[2];
/* An absent gain is one (libref's reading), and `wadd` belongs to a gain. */
/* An absent gain is 1 (as in libref); `wadd` requires a gain. */
const RadTensor* w = a->t[1].data ? &a->t[1] : nullptr;
const int64_t n = p_int(a, "n", w && w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-6f);
@@ -76,7 +56,7 @@ AVX_KERNEL(rmsnorm) {
float* gain = (float*)scratch_raw((size_t)n * sizeof(float));
if (w) widen_gain(w, n, wadd, gain);
else for (int64_t i = 0; i < n; ++i) gain[i] = 1.0f;
/* `mult` folded into the gain: the row is scaled before its one rounding. */
/* `mult` is folded into the gain, so the row is scaled before its single rounding. */
const float mult = p_f32(a, "mult", 1.0f);
if (mult != 1.0f)
for (int64_t i = 0; i < n; ++i) gain[i] *= mult;
@@ -99,9 +79,7 @@ AVX_KERNEL(rmsnorm) {
}
/* ------------------------------------------------------------------ rmsnorm_p */
/* y = x * rsqrt(mean(x^2) + eps) -- the rmsnorm with no gain. Same one-conversion, two-pass shape
* and same four-accumulator sum of squares as rmsnorm; the only difference is there is no weight
* to widen and no gain to multiply in, because the op has no `w` at all. */
/* y = x * rsqrt(mean(x^2) + eps): rmsnorm without a gain operand. */
AVX_KERNEL(rmsnorm_p) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
@@ -167,19 +145,15 @@ AVX_KERNEL(rmsnorm_add) {
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... */
/* 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. */
/* ...and narrowed for the multiply by a round trip through `sr`, rather than re-reading
* the operand. `sr` is the only free buffer: `gain` lives in the launching thread's
* scratch_raw arena, and another scratch_raw call inside the parallel region could
* reallocate it under the other threads. `sr` holds 4n bytes, enough for any dtype, and
* `rv` (possibly `sr`) is dead once 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);
@@ -196,9 +170,8 @@ AVX_KERNEL(rmsnorm_add) {
}
/* ------------------------------------------------------------------ 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. */
/* y = (x - mean) * rsqrt(var + eps) * w + b, with the biased variance (divide by n). `b` is
* optional: a model without a bias passes a null operand. */
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];
@@ -210,9 +183,8 @@ AVX_KERNEL(layernorm) {
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). */
/* Gain and bias are widened once, into one allocation: a second scratch_raw 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;
@@ -230,12 +202,9 @@ AVX_KERNEL(layernorm) {
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. */
/* Two passes (mean, then squared deviations), as in libref. The one-pass E[x^2] - E[x]^2
* cancels catastrophically when the mean is large relative to the spread, as in a
* post-attention residual; the extra pass reads a row already in L1. */
const float mean = row_sum(v, n) / (float)n;
const vf vm = vf_set1(mean);
vf acc = vf_zero();
@@ -266,10 +235,17 @@ AVX_KERNEL(layernorm) {
}
/* ------------------------------------------------------------------ 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. */
/* `v` rounded to an activation dtype (f32, bf16 or f16), as the position term is stored. */
static inline float round_act(uint32_t dt, float v) {
if (dt == RAD_BF16) return rad_bf16_to_f32(rad_f32_to_bf16(v));
if (dt == RAD_F16) return rad_f16_to_f32(rad_f32_to_f16(v));
return v;
}
/* Adds a learned side x side position table, resampled bilinearly to each row's grid (corners
* aligned, edge taps clamped). Matches libref's grid_embed operation for operation: four taps
* summed in f32 in the same order, rounded to x's dtype, then added and rounded again. One row per
* vision-tower patch, off the step path, so it is scalar. */
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];
@@ -307,8 +283,7 @@ AVX_KERNEL(grid_embed) {
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));
const float pe = round_act(x->dtype, acc);
stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe);
}
}
@@ -316,11 +291,11 @@ AVX_KERNEL(grid_embed) {
}
/* ------------------------------------------------------------------ grid_embed_aa */
/* The table resampled as torch's F.interpolate(bilinear, align_corners=False, antialias=True) does
* it -- SigLIP2's position embedding -- and added in: libref's grid_embed_aa, operation for
* operation. Per axis a triangle filter on half-pixel centres, widened by the scale when
* shrinking, its taps inside the table normalised; the rows summed first, f32, rounded once
* before the add. A coordinate outside its grid is clamped into it. */
/* Adds the table resampled as torch's F.interpolate(bilinear, align_corners=False,
* antialias=True) does (SigLIP2's position embedding); matches libref's grid_embed_aa. Per axis: a
* triangle filter on half-pixel centres, widened by the scale when shrinking, with the in-table
* taps normalised. Rows are summed first in f32 and rounded once before the add. Out-of-grid
* coordinates are clamped. */
static void aa_taps(int64_t at, int64_t size, int64_t side, float* w, int64_t* lo, int64_t* cnt) {
if (size < 1) size = 1;
at = at < 0 ? 0 : (at >= size ? size - 1 : at);
@@ -371,8 +346,7 @@ AVX_KERNEL(grid_embed_aa) {
row += ldt(tab, rowoff(tab, (h0 + y) * side + w0 + c, n) + i * ts) * ww[c];
acc += row * wh[y];
}
float pe = acc;
if (x->dtype == RAD_BF16) pe = rad_bf16_to_f32(rad_f32_to_bf16(pe));
const float pe = round_act(x->dtype, acc);
stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe);
}
}
+175
View File
@@ -0,0 +1,175 @@
/* avx_planes.cpp -- decoding the rows of a weight joined over several planes (avx_planes.h),
* compiled once per ISA level. The GEMM's packing, the head rescore and the mixing matrices widen
* such a row to f32 here, scale folded in, where a plain row would go through row_to_f32. */
#include "avx_vec.h"
#include "avx_common.h"
#include "avx_planes.h"
namespace avx {
inline namespace AVX_SUFFIX {
/* n E4M3 or int8 codes, each times `s`. The E4M3 decode is avx_vec.h's reconstruction
* (cvt_fp8e4m3_to_f32), so the code's value is bit-exact before the one rounding of the
* product. */
void decode_scaled(uint32_t dt, const uint8_t* src, float s, float* dst, int64_t n) {
int64_t i = 0;
if (dt == RAD_I8) {
const int8_t* q = (const int8_t*)src;
#if AVX_LEVEL == 3
const __m512 vs = _mm512_set1_ps(s);
for (; i + 16 <= n; i += 16)
_mm512_storeu_ps(dst + i, _mm512_mul_ps(_mm512_cvtepi32_ps(_mm512_cvtepi8_epi32(
_mm_loadu_si128((const __m128i*)(q + i)))), vs));
#elif AVX_LEVEL == 2
const __m256 vs = _mm256_set1_ps(s);
for (; i + 8 <= n; i += 8)
_mm256_storeu_ps(dst + i, _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(
_mm_loadl_epi64((const __m128i*)(q + i)))), vs));
#endif
for (; i < n; ++i) dst[i] = (float)q[i] * s;
return;
}
#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);
const __m512 cnan = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fc00000));
const __m512 vs = _mm512_set1_ps(s);
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);
__m512 f = _mm512_castsi512_ps(_mm512_add_epi32(_mm512_slli_epi32(mag, 20), cbias));
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);
f = _mm512_castsi512_ps(_mm512_or_si512(_mm512_castps_si512(f), sign));
_mm512_storeu_ps(dst + i, _mm512_mul_ps(f, vs));
}
#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));
const __m256 vs = _mm256_set1_ps(s);
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);
__m256 f = _mm256_castsi256_ps(_mm256_add_epi32(_mm256_slli_epi32(mag, 20), cbias));
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);
f = _mm256_castsi256_ps(_mm256_or_si256(_mm256_castps_si256(f), sign));
_mm256_storeu_ps(dst + i, _mm256_mul_ps(f, vs));
}
#endif
for (; i < n; ++i) dst[i] = avx_fp8e4m3_tab[src[i]] * s;
}
#if AVX_LEVEL >= 2
/* Sixteen codes, one per byte of `b` in natural order, each (code - z) * s, into dst. */
static inline void zp_emit16(__m128i b, int32_t z, float s, float* dst) {
#if AVX_LEVEL == 3
const __m512i v = _mm512_sub_epi32(_mm512_cvtepu8_epi32(b), _mm512_set1_epi32(z));
_mm512_storeu_ps(dst, _mm512_mul_ps(_mm512_cvtepi32_ps(v), _mm512_set1_ps(s)));
#else
const __m256i v0 = _mm256_sub_epi32(_mm256_cvtepu8_epi32(b), _mm256_set1_epi32(z));
const __m256i v1 = _mm256_sub_epi32(_mm256_cvtepu8_epi32(_mm_srli_si128(b, 8)),
_mm256_set1_epi32(z));
_mm256_storeu_ps(dst, _mm256_mul_ps(_mm256_cvtepi32_ps(v0), _mm256_set1_ps(s)));
_mm256_storeu_ps(dst + 8, _mm256_mul_ps(_mm256_cvtepi32_ps(v1), _mm256_set1_ps(s)));
#endif
}
/* u5 codes by pdep: eight codes are 40 bits, and one pdep deposits them into the low five bits of
* eight bytes. BMI2 is not in the level's flags (it is a CPUID bit of its own) and is checked at
* run time; Zen 1 and 2 microcode pdep, slowly but correctly. Each 40 bits are read as one
* 8-byte load, masked, except in the last 16 codes, where 3 of those bytes would lie past the
* ones asked for. Returns the codes decoded, a multiple of 16. */
__attribute__((target("bmi2"))) static int64_t zp_u5_pdep(const uint8_t* src, int64_t n,
int32_t z, float s, float* dst) {
const unsigned long long kLow5 = 0x1f1f1f1f1f1f1f1full, k40 = 0xffffffffffull;
int64_t i = 0;
for (; i + 16 <= n; i += 16) {
const uint8_t* p = src + i / 8 * 5;
uint64_t v0 = 0, v1 = 0;
if (i + 16 < n) {
std::memcpy(&v0, p, 8);
std::memcpy(&v1, p + 5, 8);
v0 &= k40;
v1 &= k40;
} else {
std::memcpy(&v0, p, 5);
std::memcpy(&v1, p + 5, 5);
}
const __m128i b = _mm_set_epi64x((long long)_pdep_u64(v1, kLow5),
(long long)_pdep_u64(v0, kLow5));
zp_emit16(b, z, s, dst + i);
}
return i;
}
#endif
/* `n` unsigned codes of `bits` from element k0 of a packed row, each (code - z) * s. Grid groups
* start on a byte for every width here (k0 a multiple of 128); other starts take the bit reader. */
void decode_zp(const uint8_t* row, int bits, int64_t k0, int64_t n, int32_t z, float s,
float* dst) {
int64_t i = 0;
#if AVX_LEVEL >= 2
const bool aligned = (k0 * bits) % 8 == 0;
const uint8_t* src = row + (k0 * bits) / 8;
if (aligned && bits == 4) {
const __m128i m4 = _mm_set1_epi8(0x0f);
for (; i + 16 <= n; i += 16) {
const __m128i x = _mm_loadl_epi64((const __m128i*)(src + i / 2));
const __m128i lo = _mm_and_si128(x, m4);
const __m128i hi = _mm_and_si128(_mm_srli_epi16(x, 4), m4);
zp_emit16(_mm_unpacklo_epi8(lo, hi), z, s, dst + i);
}
} else if (aligned && bits == 2) {
const __m128i m2 = _mm_set1_epi8(0x03);
for (; i + 16 <= n; i += 16) {
int32_t w;
std::memcpy(&w, src + i / 4, 4);
const __m128i x = _mm_cvtsi32_si128(w);
const __m128i p0 = _mm_and_si128(x, m2);
const __m128i p1 = _mm_and_si128(_mm_srli_epi16(x, 2), m2);
const __m128i p2 = _mm_and_si128(_mm_srli_epi16(x, 4), m2);
const __m128i p3 = _mm_and_si128(_mm_srli_epi16(x, 6), m2);
zp_emit16(_mm_unpacklo_epi16(_mm_unpacklo_epi8(p0, p1), _mm_unpacklo_epi8(p2, p3)),
z, s, dst + i);
}
} else if (aligned && bits == 5) {
static const bool bmi2 = __builtin_cpu_supports("bmi2");
if (bmi2) {
i = zp_u5_pdep(src, n, z, s, dst);
} else {
for (; i + 16 <= n; i += 16) {
alignas(16) uint8_t q[16];
for (int h = 0; h < 2; ++h) {
uint64_t v = 0;
std::memcpy(&v, src + (i + 8 * h) / 8 * 5, 5);
for (int t = 0; t < 8; ++t) q[8 * h + t] = (uint8_t)((v >> (5 * t)) & 31u);
}
zp_emit16(_mm_load_si128((const __m128i*)q), z, s, dst + i);
}
}
}
#endif
for (; i < n; ++i) dst[i] = (float)((int32_t)rad_load_bits(row, bits, k0 + i) - z) * s;
}
void scaled_row(const avxp::ScaledRows& sr, int64_t r, int64_t K, float* dst) {
const uint8_t* c = sr.codes.p + r * sr.codes.row_bytes;
const int64_t span = sr.span(K);
for (int64_t c0 = 0; c0 < K; c0 += span) {
const int64_t c1 = c0 + span < K ? c0 + span : K;
decode_scaled(sr.codes.dt, c + c0, sr.scale_at(r, c0), dst + c0, c1 - c0);
}
}
} /* inline namespace AVX_SUFFIX */
} /* namespace avx */
+226
View File
@@ -0,0 +1,226 @@
/* avx_planes.h -- libavx's reading of a weight operand joined over several planes
* (abi/rad_planes.h), and the layout hooks that ask for that form.
*
* The rules are libref's (libref/ref_planes.h), stated again because a plugin links only abi/:
* the same selections are joined and the same ones refused, so the selector can resolve either
* library for a band of an op that reads such a weight, and both read one stored form. A single
* plane is stored as it is, so these rows still read the plain forms a tool describes.
*
* Plain functions with internal linkage, no vector code: avx_registry.cpp (baseline) installs the
* hooks and every ISA level's kernels read the planes through the same helpers.
*/
#ifndef RAD_AVX_PLANES_H
#define RAD_AVX_PLANES_H
#include "rad_abi.h"
#include "rad_plugin.h"
#include "rad_planes.h"
#include <cstdint>
#include <cstring>
namespace avxp {
/* ================================================================== reading at launch */
/* One plane of a joined operand, as its entry describes it. */
struct JPlane {
const uint8_t* p = nullptr;
uint32_t dt = 0;
int64_t rows = 0, cols = 0, row_bytes = 0;
int64_t br = 0, bc = 0; /* logical rows x columns one element covers; 0 is all */
explicit operator bool() const { return p != nullptr; }
float at(int64_t i, int64_t j) const { return rad_load_f32(p + i * row_bytes, dt, j); }
};
static inline bool is_joined(const RadTensor* t) {
return t && t->data && rad_planes_header(t->data) != nullptr;
}
static inline JPlane jplane(const RadTensor* t, const char* role) {
JPlane v;
const RadPlanesEntry* e = nullptr;
const void* d = t && t->data ? rad_planes_find(t->data, role, &e) : nullptr;
if (!d) return v;
v.p = (const uint8_t*)d;
v.dt = e->dtype;
v.rows = e->rows;
v.cols = e->cols;
v.row_bytes = e->row_bytes;
v.br = e->block[0];
v.bc = e->block[1];
return v;
}
static inline int64_t cdiv_or_1(int64_t n, int64_t b) { return b > 0 ? (n + b - 1) / b : 1; }
static inline bool float_scale_dt(uint32_t dt) {
return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32;
}
/* Codes with one scale over [rows, cols]; element (r, c) is code(r, c) * scale covering it, one
* f32 rounding, as the core's affine decoder gives it (libref/ref_planes.h: ScaledRows). */
struct ScaledRows {
JPlane codes, scale;
/* Columns one scale covers, the whole row for a block extent of 0. */
int64_t span(int64_t cols) const { return scale.bc > 0 ? scale.bc : cols; }
float scale_at(int64_t r, int64_t c) const {
return scale.at(scale.br > 0 ? r / scale.br : 0, scale.bc > 0 ? c / scale.bc : 0);
}
};
static inline int scaled_rows(const RadTensor* t, int64_t rows, int64_t cols, ScaledRows* v) {
const RadPlanesHeader* h = t && t->data ? rad_planes_header(t->data) : nullptr;
if (!h) return RAD_E_INVAL;
v->codes = jplane(t, "codes");
v->scale = jplane(t, "scale");
if (h->n_planes != 2 || !v->codes || !v->scale) return RAD_E_DTYPE;
if ((v->codes.dt != RAD_F8E4M3 && v->codes.dt != RAD_I8) || !float_scale_dt(v->scale.dt) ||
v->codes.br != 1 || v->codes.bc != 1)
return RAD_E_DTYPE;
if (v->codes.rows != rows || v->codes.cols != cols ||
v->scale.rows != cdiv_or_1(rows, v->scale.br) ||
v->scale.cols != cdiv_or_1(cols, v->scale.bc))
return RAD_E_SHAPE;
return RAD_OK;
}
/* ================================================================== the zero-point grids
* As libref/ref_planes.h: unsigned codes read as (code - zero) * scale, one f16 scale and one
* integer zero per (row, `group` of K) joined in `b_scale`, against one of three activations. */
enum ZpAct { ZP_I8_ROW = 0, ZP_I8_GROUP = 1, ZP_F16 = 2 };
struct ZpGrid {
const char* name;
uint32_t codes;
ZpAct act;
};
static inline const ZpGrid* zp_grid(const char* dtype) {
static const ZpGrid kGrids[] = {
{ "w2a8", RAD_U2, ZP_I8_ROW }, { "w4a8_asym", RAD_U4, ZP_I8_ROW },
{ "w4a16_asym", RAD_U4, ZP_F16 }, { "w5a16", RAD_U5, ZP_F16 },
{ "w4a8i8_asym", RAD_U4, ZP_I8_GROUP }, { "w5a8i8", RAD_U5, ZP_I8_GROUP },
};
if (!dtype) return nullptr;
for (const ZpGrid& g : kGrids)
if (std::strcmp(g.name, dtype) == 0) return &g;
return nullptr;
}
static inline bool zero_dt(uint32_t dt) {
return dt == RAD_U8 || dt == RAD_U2 || dt == RAD_U4 || dt == RAD_U5;
}
/* ================================================================== the layout hooks */
static inline bool sel_roles(const RadEncoding* enc, const int* sel, int n, const char* r0,
const char* r1) {
if (!enc || !sel || n != 2) return false;
for (int i = 0; i < 2; ++i)
if (sel[i] < 0 || sel[i] >= enc->n_planes) return false;
return std::strncmp(enc->plane[sel[0]].role, r0, RAD_ENC_STR) == 0 &&
std::strncmp(enc->plane[sel[1]].role, r1, RAD_ENC_STR) == 0;
}
static inline bool enc_scaled_rows(const RadEncoding* enc, const int* sel, int n) {
if (!rad_enc_is(enc, "affine") || enc->transform[0] || enc->n_planes != 2) return false;
if (!sel_roles(enc, sel, n, "codes", "scale")) return false;
const RadEncPlane& c = enc->plane[sel[0]];
const RadEncPlane& s = enc->plane[sel[1]];
return c.kind == RAD_PLANE_TILED && c.block[0] == 1 && c.block[1] == 1 &&
(c.dtype == RAD_F8E4M3 || c.dtype == RAD_I8) && s.kind == RAD_PLANE_TILED &&
float_scale_dt(s.dtype);
}
static inline int layout_scaled(int operand, int rows_opd, int rows_opd2, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, RadLayout* out) {
if (n < 2 || (operand != rows_opd && operand != rows_opd2)) return RAD_E_UNSUPPORTED;
if (!enc_scaled_rows(enc, sel, n)) return RAD_E_DTYPE;
return rad_planes_layout(enc, sel, planes, n, out);
}
/* logits_gemm and logit_rerank: the head is operand 1 of both. */
static inline int avx_layout_head(const RadParam*, int, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, RadLayout* out) {
return layout_scaled(operand, 1, -1, enc, sel, planes, n, out);
}
/* hc_read: mix_down and mix_up (operands 2 and 3). */
static inline int avx_layout_hc(const RadParam*, int, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, RadLayout* out) {
return layout_scaled(operand, 2, 3, enc, sel, planes, n, out);
}
/* mtp_enter: fc_h and fc_e (operands 4 and 5). */
static inline int avx_layout_mtp(const RadParam*, int, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, RadLayout* out) {
return layout_scaled(operand, 4, 5, enc, sel, planes, n, out);
}
/* gemm_nt_q: `b_scale` (operand 3) as the scale and zero of the grid `dtype` names. */
static inline int avx_layout_gemm_q(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out) {
if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED;
const ZpGrid* zg = zp_grid(rad_param_gets(p, n_p, "dtype", nullptr));
const long long group = rad_param_geti(p, n_p, "group", 0);
if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE;
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0)
return RAD_E_DTYPE;
if (!sel_roles(enc, sel, n, "scale", "zero") || enc->n_planes < 3) return RAD_E_DTYPE;
const RadEncPlane& c = enc->plane[0];
const RadEncPlane& s = enc->plane[sel[0]];
const RadEncPlane& z = enc->plane[sel[1]];
if (std::strncmp(c.role, "codes", RAD_ENC_STR) != 0 || c.dtype != zg->codes ||
c.block[0] != 1 || c.block[1] != 1)
return RAD_E_DTYPE;
if (s.kind != RAD_PLANE_TILED || s.dtype != RAD_F16 || s.block[0] != 1 || s.block[1] != group ||
z.kind != RAD_PLANE_TILED || !zero_dt(z.dtype) || z.block[0] != 1 || z.block[1] != group)
return RAD_E_DTYPE;
return rad_planes_layout(enc, sel, planes, n, out);
}
template <RadLayoutFn L>
static int avx_relayout_planes(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, void* dst,
int64_t dst_bytes) {
RadLayout lay{};
const int st = L(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
return rad_planes_relayout(enc, sel, planes, n, dst, dst_bytes);
}
template <RadLayoutFn L>
static int avx_unrelayout_planes(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const void* src, int64_t src_bytes,
const RadTensor* planes, int n) {
RadLayout lay{};
const int st = L(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
return rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n);
}
} /* namespace avxp */
#ifdef AVX_LEVEL
/* The per-level decoders (avx_planes.cpp). */
namespace avx {
inline namespace AVX_SUFFIX {
/* n E4M3 or int8 codes, each times `s`: the code's exact value, then one rounding. */
void decode_scaled(uint32_t dt, const uint8_t* src, float s, float* dst, int64_t n);
/* `n` unsigned codes of `bits` from element k0 of a packed row, each (code - z) * s. */
void decode_zp(const uint8_t* row, int bits, int64_t k0, int64_t n, int32_t z, float s,
float* dst);
/* Row `r` of a ScaledRows weight, `K` wide, as f32. */
void scaled_row(const avxp::ScaledRows& sr, int64_t r, int64_t K, float* dst);
} /* inline namespace AVX_SUFFIX */
} /* namespace avx */
#endif
#endif /* RAD_AVX_PLANES_H */
+873
View File
@@ -0,0 +1,873 @@
/* avx_qsa.cpp -- the QSA indexer's score, selection, tail store and work list, and DFlash2's
* grouped convolution (docs/OPS.md, "Sparse attention (QSA)" and "Draft heads").
*
* libref/ref_qsa.cpp is the contract: the same refusals in the same order, the same elements left
* unwritten and the same order of every output. `cu` holds absolute row indices; a row belongs to
* the first sequence whose span holds it, and cu[0] need not be 0.
*
* qsa_score A tile of up to kQT query rows of one sequence is scored against VF_N block keys
* at a time. Each (row, head, block) dot is a vector accumulator over the head's
* lanes, and a fixed transpose-and-add tree turns VF_N of them into one vector with
* one block per lane, so the relu, the sum over heads and the store are vector work.
* The keys are read once per tile, which at decode is once per sequence. The dots
* sum in vector order (libref's order at the scalar level); the heads in order.
* qsa_select Linear time per row: an order key per block (the bits of max(score, 0) plus one,
* 0 for a dead block), a histogram of the keys' top bits, an exact select among the
* keys in the bin that holds the topk-th largest, and one emitting pass in block
* order. The ids match libref's byte for byte.
* qsa_tail_store, qsa_work Row copies through f32, as libref copies, so every value lands
* with the bits libref's would.
* dflash_conv Channels across lanes, in blocks of columns that walk their rows, so a block's base
* kernel and its slice of the row above stay in L1; one pass in registers a row.
*/
#include "avx_vec.h"
#include "avx_common.h"
#include <algorithm>
#include <functional>
#include <type_traits>
using namespace avx;
namespace {
int64_t cu_at(const RadTensor* cu, int64_t i) { return ldi(cu, offlin(cu, i)); }
/* Offset of entry `i` of a rank-1 operand, or of column 0 of row `i` of a rank-2 one (a state
* index row's committed slot). */
int64_t col0(const RadTensor* t, int64_t i) {
return t->rank >= 2 ? i * t->stride[0] : offlin(t, i);
}
/* Whether the dimensions after the first are dense, so a row of a paged store is
* `numel / shape[0]` contiguous values from `row * stride[0]`. */
bool rows_dense(const RadTensor* t) {
int64_t acc = 1;
for (int i = (int)t->rank - 1; i >= 1; --i) {
if (t->shape[i] != 1 && t->stride[i] != acc) return false;
acc *= t->shape[i];
}
return true;
}
/* seq[m] for every m < M: the first sequence whose cu span holds row m, or `none` (libref's
* seq_holding), filled from the spans instead of scanning every span for every row. */
void seq_rows(const RadTensor* cu, int64_t n_seq, int64_t M, int64_t none, int64_t* seq) {
const int64_t unset = INT64_MIN;
std::fill(seq, seq + M, unset);
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t lo = std::max<int64_t>(cu_at(cu, s), 0);
const int64_t hi = std::min<int64_t>(cu_at(cu, s + 1), M);
for (int64_t m = lo; m < hi; ++m)
if (seq[m] == unset) seq[m] = s;
}
for (int64_t m = 0; m < M; ++m)
if (seq[m] == unset) seq[m] = none;
}
/* `n` elements of `t` from `base`, `st` apart, as f32, and back. Whole-byte dtypes convert a row
* at a time; the conversions are libref's bit for bit either way. */
void widen(const RadTensor* t, int64_t base, int64_t st, int64_t n, float* dst) {
if (st == 1 && rad_dtype_bits(t->dtype) >= 8) {
row_to_f32(t->dtype, byte_at(t->data, t->dtype, base), dst, n);
return;
}
for (int64_t i = 0; i < n; ++i) dst[i] = ldt(t, base + i * st);
}
void narrow(const RadTensor* t, int64_t base, int64_t st, int64_t n, const float* src) {
if (st == 1 && rad_dtype_bits(t->dtype) >= 8) {
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]);
}
/* ================================================================== qsa_score */
/* Query rows a tile: the key history is read once per tile, and kQT * heads rows of f32 queries
* stay in L1 beside VF_N widened keys (16 KiB and 8 KiB at Flash-Next's 4 heads of 128). */
enum { kQT = 8 };
/* Blocks a work unit. Units are ordered chunk-major and handed out in order, so the threads work
* through one chunk's keys across the tiles of a prefill chunk while they are in L3. */
enum { kChunk = 256 };
/* Blocks the software prefetch runs ahead of the keys being widened. */
enum { kAhead = 32 };
/* lane_sums leaves the total of accumulator slot i in lane kSlot[i]; slot i is loaded with block
* kSlot[i] of the group, so lane j holds block j. */
#if AVX_LEVEL == 3
const int kSlot[16] = { 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15 };
#elif AVX_LEVEL >= 1
const int kSlot[8] = { 0, 4, 1, 5, 2, 6, 3, 7 };
#else
const int kSlot[1] = { 0 };
#endif
/* The VF_N horizontal sums of a[0 .. VF_N), one a lane, by a fixed tree: each level halves every
* vector and adds pairs of them, so a level costs one vector of adds per output vector. */
static inline vf lane_sums(const vf* a) {
#if AVX_LEVEL == 3
__m512 s[8], t[4];
for (int i = 0; i < 8; ++i)
s[i] = _mm512_add_ps(_mm512_shuffle_f32x4(a[2 * i], a[2 * i + 1], 0x44),
_mm512_shuffle_f32x4(a[2 * i], a[2 * i + 1], 0xEE));
for (int i = 0; i < 4; ++i)
t[i] = _mm512_add_ps(_mm512_shuffle_f32x4(s[2 * i], s[2 * i + 1], 0x88),
_mm512_shuffle_f32x4(s[2 * i], s[2 * i + 1], 0xDD));
const __m512 u0 = _mm512_add_ps(_mm512_shuffle_ps(t[0], t[1], 0x44),
_mm512_shuffle_ps(t[0], t[1], 0xEE));
const __m512 u1 = _mm512_add_ps(_mm512_shuffle_ps(t[2], t[3], 0x44),
_mm512_shuffle_ps(t[2], t[3], 0xEE));
return _mm512_add_ps(_mm512_shuffle_ps(u0, u1, 0x88), _mm512_shuffle_ps(u0, u1, 0xDD));
#elif AVX_LEVEL >= 1
__m256 s[4];
for (int i = 0; i < 4; ++i)
s[i] = _mm256_add_ps(_mm256_permute2f128_ps(a[2 * i], a[2 * i + 1], 0x20),
_mm256_permute2f128_ps(a[2 * i], a[2 * i + 1], 0x31));
const __m256 t0 = _mm256_add_ps(_mm256_shuffle_ps(s[0], s[1], 0x44),
_mm256_shuffle_ps(s[0], s[1], 0xEE));
const __m256 t1 = _mm256_add_ps(_mm256_shuffle_ps(s[2], s[3], 0x44),
_mm256_shuffle_ps(s[2], s[3], 0xEE));
return _mm256_add_ps(_mm256_shuffle_ps(t0, t1, 0x88), _mm256_shuffle_ps(t0, t1, 0xDD));
#else
return a[0];
#endif
}
/* Lane j: the dot of the query row `q` with block key j of the group in `kf` (slot order, rows
* `np` apart). `np` is a multiple of 16 and the tails of both rows are zero. */
static inline vf dot_group(const float* q, const float* kf, int64_t np) {
vf acc[VF_N];
for (int i = 0; i < VF_N; ++i) acc[i] = vf_zero();
for (int64_t c = 0; c < np; c += VF_N) {
const vf vq = vf_load(q + c);
#pragma GCC unroll 16
for (int i = 0; i < VF_N; ++i) acc[i] = vf_fma(vq, vf_load(kf + i * np + c), acc[i]);
}
return lane_sums(acc);
}
struct ScoreTile { int64_t m0, rows, s, nbs; };
struct ScoreJob {
const RadTensor *q, *bk, *bt, *o;
int64_t n, np, heads;
int64_t q_rs, q_cs, pg_rs, bt_rs, bt_cs, o_rs, o_cs;
int64_t esz; /* bytes an element of bk, 0 for a packed dtype */
float rn;
};
/* Scores blocks [b0, b1) of one tile. */
static void score_unit(const ScoreJob& j, const ScoreTile& t, int64_t b0, int64_t b1) {
const int64_t n = j.n, np = j.np, R = t.rows * j.heads;
float* qf = scratch_f32((size_t)(R * np));
float* kf = scratch_f32_b((size_t)(VF_N * np));
for (int64_t r = 0; r < R; ++r) {
const int64_t m = t.m0 + r / j.heads, h = r % j.heads;
float* d = qf + r * np;
widen(j.q, m * j.q_rs + h * n * j.q_cs, j.q_cs, n, d);
std::fill(d + n, d + np, 0.0f);
}
for (int i = 0; i < VF_N; ++i) std::fill(kf + i * np + n, kf + (i + 1) * np, 0.0f);
const bool f32_out = j.o->dtype == RAD_F32;
const uint8_t* bkb = (const uint8_t*)j.bk->data;
const int64_t bt_row = t.s * j.bt_rs;
alignas(64) float lanes[VF_N];
/* Software prefetch kAhead blocks ahead of the group being widened, from the unit's first
* block: a block table need not be in page order, so the hardware prefetcher cannot follow
* it, and a unit's head would otherwise wait on DRAM. */
int64_t pf = b0;
auto prefetch_to = [&](int64_t lim) {
for (lim = std::min(lim, b1); pf < lim; ++pf) {
const int64_t p = ldi(j.bt, bt_row + pf * j.bt_cs);
if (p < 0 || j.esz == 0) continue;
const uint8_t* at = bkb + p * j.pg_rs * j.esz;
for (int64_t off = 0; off < n * j.esz; off += 64) __builtin_prefetch(at + off);
}
};
prefetch_to(b0 + kAhead);
for (int64_t g = b0; g < b1; g += VF_N) {
const int nv = (int)std::min<int64_t>(VF_N, b1 - g);
prefetch_to(g + VF_N + kAhead);
int64_t pg[VF_N];
for (int L = 0; L < VF_N; ++L)
pg[L] = L < nv ? ldi(j.bt, bt_row + (g + L) * j.bt_cs) : -1;
for (int i = 0; i < VF_N; ++i) {
const int64_t p = pg[kSlot[i]];
float* d = kf + i * np;
if (p >= 0) widen(j.bk, p * j.pg_rs, 1, n, d);
else std::fill(d, d + n, 0.0f);
}
for (int64_t qi = 0; qi < t.rows; ++qi) {
vf s = vf_zero();
for (int64_t h = 0; h < j.heads; ++h)
s = vf_add(s, vf_max(dot_group(qf + (qi * j.heads + h) * np, kf, np), vf_zero()));
vf_store(lanes, vf_div(s, vf_set1(j.rn)));
const int64_t ob = (t.m0 + qi) * j.o_rs + g * j.o_cs;
if (f32_out) {
float* o = (float*)j.o->data;
for (int L = 0; L < nv; ++L) o[ob + L * j.o_cs] = pg[L] < 0 ? -INFINITY : lanes[L];
} else {
for (int L = 0; L < nv; ++L)
stt(j.o, ob + L * j.o_cs, pg[L] < 0 ? -INFINITY : lanes[L]);
}
}
}
}
} /* namespace */
/* ------------------------------------------------------------------ qsa_score */
/* score[m][b] = (sum over heads h of relu(q[m][h] . bk[bt[seq(m)][b]])) / sqrt(n) for b below
* min(nc[seq], the table's width, the score plane's width); a negative page id scores -inf.
* Columns past the bound, and rows no sequence holds, are not written. */
AVX_KERNEL(qsa_score) {
if (!rad_args_have(a, 6)) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *bk = &a->t[1], *bt = &a->t[2], *cu = &a->t[3];
const RadTensor *nc = &a->t[4], *o = &a->t[5];
const int64_t n = p_int(a, "n", 0), heads = p_int(a, "heads", 0);
if (n <= 0 || heads <= 0) return RAD_E_SHAPE;
if (bt->rank != 2 || o->rank != 2 || bk->rank < 2) return RAD_E_SHAPE;
const int64_t M = o->shape[0], nb = std::min(bt->shape[1], o->shape[1]);
const int64_t n_seq = numel(cu) - 1, pages = bk->shape[0];
if (M <= 0 || nb <= 0 || n_seq <= 0 || pages <= 0) return RAD_E_SHAPE;
if (bt->shape[0] < n_seq || numel(nc) < n_seq || rows_of(q, heads * n) < M) return RAD_E_SHAPE;
if (numel(bk) / pages != n) return RAD_E_SHAPE;
if (!rows_dense(bk)) return RAD_E_STRIDE;
const int64_t bt_rs = bt->stride[0], bt_cs = bt->stride[1];
/* Every page id the launch will read must name a page of `bk`. */
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t nbs = std::min(ldi(nc, offlin(nc, s)), nb);
for (int64_t b = 0; b < nbs; ++b)
if (ldi(bt, s * bt_rs + b * bt_cs) >= pages) return RAD_E_INVAL;
}
ScoreJob j{};
j.q = q; j.bk = bk; j.bt = bt; j.o = o;
j.n = n; j.np = (n + 15) & ~(int64_t)15; j.heads = heads;
j.q_rs = row_stride(q, heads * n); j.q_cs = laststride(q);
j.pg_rs = bk->stride[0]; j.bt_rs = bt_rs; j.bt_cs = bt_cs;
j.o_rs = o->stride[0]; j.o_cs = o->stride[1];
j.esz = rad_dtype_bits(bk->dtype) / 8;
j.rn = std::sqrt((float)n);
/* Tiles: runs of up to kQT consecutive rows of one sequence. One allocation, as a second
* scratch_raw call could move the first. */
int64_t* seq = (int64_t*)scratch_raw((size_t)M * (sizeof(int64_t) + sizeof(ScoreTile)) + 64);
ScoreTile* tiles = (ScoreTile*)(seq + M);
seq_rows(cu, n_seq, M, -1, seq);
int64_t nt = 0, widest = 0, work = 0;
for (int64_t m = 0; m < M;) {
const int64_t s = seq[m];
int64_t e = m + 1;
while (e < M && e - m < kQT && seq[e] == s) ++e;
if (s >= 0) {
const int64_t nbs = std::min(ldi(nc, offlin(nc, s)), nb);
if (nbs > 0) {
tiles[nt++] = ScoreTile{ m, e - m, s, nbs };
widest = std::max(widest, nbs);
work += (e - m) * heads * n * nbs;
}
}
m = e;
}
const int64_t nch = (widest + kChunk - 1) / kChunk, units = nt * nch;
/* Dynamic: a unit's arithmetic does not depend on the thread that runs it, so the output is
* the same bytes for any schedule, and a preempted thread does not hold up the rest. */
#ifdef _OPENMP
AVX_PRAGMA(omp parallel for schedule(dynamic, 1) if(work >= ((int64_t)1 << 19) ||
avx_par_forced()) num_threads(avx_team_size()))
#endif
for (int64_t u = 0; u < units; ++u) {
const ScoreTile& t = tiles[u % nt];
const int64_t b0 = (u / nt) * kChunk, b1 = std::min(b0 + kChunk, t.nbs);
if (b0 < b1) score_unit(j, t, b0, b1);
}
return RAD_OK;
}
/* ================================================================== qsa_select */
namespace {
/* Bins of the first selection pass: the top 10 bits of a key, which is below 2^31. */
enum { kBins = 1024, kBinShift = 21 };
struct SelJob {
const RadTensor *sc, *bt, *nc, *po, *se, *ns, *su;
const int64_t* seq;
int64_t nb, topk, ratio;
int64_t s_rs, s_cs, bt_rs, bt_cs, o_rs, o_cs;
};
/* The order key of each of the row's first `n` blocks: bits(max(score, 0)) + 1 for a live block
* (page id >= 0 and score > -1e30), 0 for a dead one. Non-negative floats order as their bits, so
* keys order as libref's values; max(score, 0) maps -0 to +0 as libref's `v > 0 ? v : 0` does.
* Returns the live count. */
static int64_t order_keys(const SelJob& j, int64_t m, int64_t s, int64_t n, uint32_t* key) {
const int64_t sb = m * j.s_rs, bb = s * j.bt_rs;
int64_t live = 0, b = 0;
#if AVX_LEVEL >= 2
if (j.sc->dtype == RAD_F32 && j.s_cs == 1 && j.bt->dtype == RAD_I32 && j.bt_cs == 1) {
const float* v = (const float*)j.sc->data + sb;
const int32_t* p = (const int32_t*)j.bt->data + bb;
#if AVX_LEVEL == 3
const __m512 lo = _mm512_set1_ps(-1e30f);
const __m512i one = _mm512_set1_epi32(1);
for (; b + 16 <= n; b += 16) {
const __m512 x = _mm512_loadu_ps(v + b);
const __m512i pg = _mm512_loadu_si512((const void*)(p + b));
const __mmask16 lv = _mm512_cmp_ps_mask(x, lo, _CMP_GT_OQ) &
_mm512_cmpge_epi32_mask(pg, _mm512_setzero_si512());
const __m512i k = _mm512_add_epi32(
_mm512_castps_si512(_mm512_max_ps(x, _mm512_setzero_ps())), one);
_mm512_storeu_si512((void*)(key + b), _mm512_maskz_mov_epi32(lv, k));
live += __builtin_popcount((unsigned)lv);
}
#else
const __m256 lo = _mm256_set1_ps(-1e30f);
const __m256i one = _mm256_set1_epi32(1), neg = _mm256_set1_epi32(-1);
for (; b + 8 <= n; b += 8) {
const __m256 x = _mm256_loadu_ps(v + b);
const __m256i pg = _mm256_loadu_si256((const __m256i*)(p + b));
const __m256 lv = _mm256_and_ps(_mm256_cmp_ps(x, lo, _CMP_GT_OQ),
_mm256_castsi256_ps(_mm256_cmpgt_epi32(pg, neg)));
const __m256i k = _mm256_add_epi32(
_mm256_castps_si256(_mm256_max_ps(x, _mm256_setzero_ps())), one);
_mm256_storeu_si256((__m256i*)(key + b),
_mm256_and_si256(k, _mm256_castps_si256(lv)));
live += __builtin_popcount((unsigned)_mm256_movemask_ps(lv));
}
#endif
}
#endif
for (; b < n; ++b) {
const float v = ldt(j.sc, sb + b * j.s_cs);
if (ldi(j.bt, bb + b * j.bt_cs) < 0 || !(v > -1e30f)) { key[b] = 0; continue; }
const float x = v > 0.0f ? v : 0.0f;
uint32_t u;
std::memcpy(&u, &x, 4);
key[b] = u + 1u;
++live;
}
return live;
}
/* The topk-th largest key of a row with more than `topk` live keys, and how many keys are above
* it. A histogram of the top bits finds the bin holding it; the keys in that bin are gathered and
* the exact value taken among them. `cand` holds up to n keys. */
static uint32_t threshold(const uint32_t* key, int64_t n, int64_t topk, uint32_t* hist,
uint32_t* cand, int64_t* above_out) {
/* Four interleaved histograms, so runs of keys in one bin do not serialise on one counter. */
std::memset(hist, 0, 4 * kBins * sizeof(uint32_t));
int64_t b = 0;
for (; b + 4 <= n; b += 4) {
++hist[0 * kBins + (key[b] >> kBinShift)];
++hist[1 * kBins + (key[b + 1] >> kBinShift)];
++hist[2 * kBins + (key[b + 2] >> kBinShift)];
++hist[3 * kBins + (key[b + 3] >> kBinShift)];
}
for (; b < n; ++b) ++hist[key[b] >> kBinShift];
for (int i = 0; i < kBins; ++i)
hist[i] += hist[kBins + i] + hist[2 * kBins + i] + hist[3 * kBins + i];
/* Bin 0 is never counted: it is the last one left, and holds the dead keys (0) beside the
* smallest live ones, which the gather below tells apart. */
int64_t above = 0;
int bin = kBins - 1;
for (; bin > 0; --bin) {
if (above + (int64_t)hist[bin] >= topk) break;
above += hist[bin];
}
/* The keys of the bin, i.e. in [lo, hi], with key 0 (dead) left out of bin 0. Few keys fall in
* one bin, so the vector forms test a vector and walk only its hits. */
const uint32_t lo = std::max<uint32_t>((uint32_t)bin << kBinShift, 1u);
const uint32_t hi = (((uint32_t)bin + 1u) << kBinShift) - 1u;
int64_t nc = 0;
b = 0;
#if AVX_LEVEL == 3
const __m512i vlo = _mm512_set1_epi32((int)lo), vhi = _mm512_set1_epi32((int)hi);
for (; b + 16 <= n; b += 16) {
const __m512i k = _mm512_loadu_si512((const void*)(key + b));
const __mmask16 in = _mm512_cmpge_epu32_mask(k, vlo) & _mm512_cmple_epu32_mask(k, vhi);
_mm512_mask_compressstoreu_epi32((void*)(cand + nc), in, k);
nc += __builtin_popcount((unsigned)in);
}
#elif AVX_LEVEL == 2
/* Keys are below 2^31, so the signed compares order them. */
const __m256i vlo = _mm256_set1_epi32((int)lo - 1), vhi = _mm256_set1_epi32((int)hi + 1);
for (; b + 8 <= n; b += 8) {
const __m256i k = _mm256_loadu_si256((const __m256i*)(key + b));
const __m256i in = _mm256_and_si256(_mm256_cmpgt_epi32(k, vlo), _mm256_cmpgt_epi32(vhi, k));
unsigned hit = (unsigned)_mm256_movemask_ps(_mm256_castsi256_ps(in));
while (hit) {
cand[nc++] = key[b + __builtin_ctz(hit)];
hit &= hit - 1;
}
}
#endif
for (; b < n; ++b) {
const uint32_t k = key[b];
if (k >= lo && k <= hi) cand[nc++] = k;
}
const int64_t want = topk - above; /* 1 .. nc */
std::nth_element(cand, cand + (want - 1), cand + nc, std::greater<uint32_t>());
const uint32_t thr = cand[want - 1];
for (int64_t i = 0; i < nc; ++i) above += cand[i] > thr;
*above_out = above;
return thr;
}
/* Writes the page ids of the keys above `thr` in block order at row[0 .. gt), then the first
* `ties` keys equal to it in block order at row[gt ..). */
static void emit(const SelJob& j, const uint32_t* key, int64_t n, int64_t s, uint32_t thr,
int64_t gt, int64_t ties, int32_t* row) {
const int64_t bb = s * j.bt_rs;
int64_t og = 0, ot = 0, b = 0;
auto one = [&](int64_t i) {
const uint32_t k = key[i];
if (k > thr) row[og++] = (int32_t)ldi(j.bt, bb + i * j.bt_cs);
else if (k == thr && ot < ties) row[gt + ot++] = (int32_t)ldi(j.bt, bb + i * j.bt_cs);
};
#if AVX_LEVEL == 3
const __m512i vt = _mm512_set1_epi32((int)thr);
for (; b + 16 <= n && (og < gt || ot < ties); b += 16) {
const __m512i k = _mm512_loadu_si512((const void*)(key + b));
unsigned hit = (unsigned)(_mm512_cmpge_epu32_mask(k, vt));
while (hit) {
one(b + __builtin_ctz(hit));
hit &= hit - 1;
}
}
#elif AVX_LEVEL == 2
/* Keys are below 2^31, so the signed compare orders them. */
const __m256i vt = _mm256_set1_epi32((int)thr - 1);
for (; b + 8 <= n && (og < gt || ot < ties); b += 8) {
const __m256i k = _mm256_loadu_si256((const __m256i*)(key + b));
unsigned hit = (unsigned)_mm256_movemask_ps(_mm256_castsi256_ps(_mm256_cmpgt_epi32(k, vt)));
while (hit) {
one(b + __builtin_ctz(hit));
hit &= hit - 1;
}
}
#endif
for (; b < n && (og < gt || ot < ties); ++b) one(b);
}
static void select_row(const SelJob& j, int64_t m) {
const int64_t s = j.seq[m];
const int64_t p = ldi(j.po, offlin(j.po, m));
const int64_t n = std::min(std::min(ldi(j.nc, offlin(j.nc, s)), j.nb), (p + 1) / j.ratio);
const int64_t topk = j.topk;
uint32_t* key = (uint32_t*)scratch_f32((size_t)std::max<int64_t>(n, 1));
int32_t* row = (int32_t*)scratch_f32_b((size_t)(4 * kBins + topk + 1));
uint32_t* hist = (uint32_t*)(row + topk + 1);
const int64_t live = n > 0 ? order_keys(j, m, s, n, key) : 0;
int64_t out = 0;
if (live <= topk) {
const int64_t bb = s * j.bt_rs;
for (int64_t b = 0; b < n && out < live; ++b)
if (key[b]) row[out++] = (int32_t)ldi(j.bt, bb + b * j.bt_cs);
} else {
uint32_t* cand = (uint32_t*)scratch_f32_c((size_t)n);
int64_t gt = 0;
const uint32_t thr = threshold(key, n, topk, hist, cand, &gt);
emit(j, key, n, s, thr, gt, topk - gt, row);
out = topk;
}
if (n < j.nb && (p + 1) % j.ratio != 0) {
const int64_t part = ldi(j.bt, s * j.bt_rs + n * j.bt_cs);
if (part >= 0) row[out++] = (int32_t)part;
}
for (int64_t i = out; i <= topk; ++i) row[i] = -1;
const int64_t ob = m * j.o_rs;
if (j.se->dtype == RAD_I32 && j.o_cs == 1) {
std::memcpy((int32_t*)j.se->data + ob, row, (size_t)(topk + 1) * sizeof(int32_t));
} else {
for (int64_t i = 0; i <= topk; ++i)
st_int_dt(j.se->dtype, j.se->data, ob + i * j.o_cs, row[i]);
}
st_int_dt(j.ns->dtype, j.ns->data, offlin(j.ns, m), out);
st_int_dt(j.su->dtype, j.su->data, offlin(j.su, m),
out == 0 ? 0 : (out - 1) * j.ratio + p % j.ratio + 1);
}
} /* namespace */
/* ------------------------------------------------------------------ qsa_select */
/* The page-id table the sparse attention reads (docs/OPS.md): over the query's complete blocks
* n = min(nc[seq], (pos + 1) / ratio, width), the live ones (page id >= 0, score > -1e30) ranked
* by max(score, 0). All of them when `topk` or fewer are live, else every block above the topk-th
* largest value in block order, then the blocks equal to it in block order until topk are taken.
* The partial page bt[n] follows when (pos + 1) % ratio != 0 and n < width, and -1 pads the row
* to topk + 1. A row no sequence holds reads sequence 0, as libref's and libr4d's do. */
AVX_KERNEL(qsa_select) {
if (!rad_args_have(a, 8)) return RAD_E_INVAL;
const RadTensor *sc = &a->t[0], *bt = &a->t[1], *nc = &a->t[2], *po = &a->t[3];
const RadTensor *cu = &a->t[4], *se = &a->t[5], *ns = &a->t[6], *su = &a->t[7];
const int64_t topk = p_int(a, "topk", 0), ratio = p_int(a, "ratio", 0);
if (topk <= 0 || ratio <= 0) return RAD_E_SHAPE;
if (sc->rank != 2 || bt->rank != 2 || se->rank != 2) return RAD_E_SHAPE;
const int64_t M = sc->shape[0], nb = std::min(bt->shape[1], sc->shape[1]);
const int64_t n_seq = numel(cu) - 1;
if (M <= 0 || nb <= 0 || n_seq <= 0) return RAD_E_SHAPE;
if (bt->shape[0] < n_seq || numel(nc) < n_seq) return RAD_E_SHAPE;
if (se->shape[0] < M || se->shape[1] < topk + 1) return RAD_E_SHAPE;
if (numel(ns) < M || numel(po) < M || numel(su) < M) return RAD_E_SHAPE;
for (int64_t s = 0; s < n_seq; ++s)
if (ldi(nc, offlin(nc, s)) < 0) return RAD_E_INVAL;
for (int64_t m = 0; m < M; ++m)
if (ldi(po, offlin(po, m)) < 0) return RAD_E_INVAL;
int64_t* seq = (int64_t*)scratch_raw((size_t)M * sizeof(int64_t) + 64);
seq_rows(cu, n_seq, M, 0, seq);
SelJob j{};
j.sc = sc; j.bt = bt; j.nc = nc; j.po = po; j.se = se; j.ns = ns; j.su = su;
j.seq = seq; j.nb = nb; j.topk = topk; j.ratio = ratio;
j.s_rs = sc->stride[0]; j.s_cs = sc->stride[1];
j.bt_rs = bt->stride[0]; j.bt_cs = bt->stride[1];
j.o_rs = se->stride[0]; j.o_cs = se->stride[1];
AVX_PARALLEL_FOR_IF(M * nb >= AVX_PAR_MIN && M > 1)
for (int64_t m = 0; m < M; ++m) select_row(j, m);
return RAD_OK;
}
/* ------------------------------------------------------------------ qsa_tail_store */
/* state[sidx[s][0]][0][pos[t] % ring] = k[t] for the last `ring` rows of each sequence, rows in
* ascending order, so a later row wins a shared target as in libref's serial loop (a row whose
* slot is -1, or that no sequence holds, writes nothing). At most `ring` rows a sequence write, so
* the copy is serial. */
AVX_KERNEL(qsa_tail_store) {
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
const RadTensor *k = &a->t[0], *po = &a->t[1], *cu = &a->t[2], *st = &a->t[3];
const RadTensor *sx = &a->t[4];
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0), ring = p_int(a, "ring", 0);
if (n <= 0 || ratio <= 0 || ring < ratio) return RAD_E_INVAL;
if (k->rank != 2 || st->rank != 4 || st->shape[1] != 1) return RAD_E_SHAPE;
const int64_t T = k->shape[0], slots = st->shape[0], n_seq = numel(cu) - 1;
if (T <= 0 || k->shape[1] != n || st->shape[2] < ring || st->shape[3] != n) return RAD_E_SHAPE;
if (n_seq <= 0 || numel(po) < T) return RAD_E_SHAPE;
if ((sx->rank >= 2 ? sx->shape[0] : numel(sx)) < n_seq) return RAD_E_SHAPE;
/* The rows that write, as (row, slot), validated before any write. */
int64_t* seq = (int64_t*)scratch_raw((size_t)T * 3 * sizeof(int64_t) + 64);
int64_t* w = seq + T;
seq_rows(cu, n_seq, T, -1, seq);
int64_t nw = 0;
for (int64_t t = 0; t < T; ++t) {
const int64_t s = seq[t];
if (s < 0 || t < cu_at(cu, s + 1) - ring) continue;
const int64_t si = ldi(sx, col0(sx, s));
if (si < 0) continue;
if (si >= slots || ldi(po, offlin(po, t)) < 0) return RAD_E_INVAL;
w[2 * nw] = t;
w[2 * nw + 1] = si;
++nw;
}
float* buf = scratch_f32((size_t)n);
for (int64_t i = 0; i < nw; ++i) {
const int64_t t = w[2 * i], si = w[2 * i + 1];
const int64_t row = ldi(po, offlin(po, t)) % ring;
widen(k, t * k->stride[0], k->stride[1], n, buf);
narrow(st, si * st->stride[0] + row * st->stride[2], st->stride[3], n, buf);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ qsa_work */
/* The blocks that complete in this batch, in sequence order and ascending within one (libref's
* ref_qsa_work has the full statement): page bt[s][b] (-1 without a tail slot), the first token's
* position in bpos (three components with `rope`), and, with a slot, the block's `ratio` raw keys
* in stage rows w * ratio + i, each from this step's rows or the tail's. Items past the count get
* page -1 and position 0 and leave `stage` alone. nc[s] = (last position + 1) / ratio. Items are
* independent, so they are split across threads. */
AVX_KERNEL(qsa_work) {
if (a->n_t < 11) return RAD_E_INVAL;
const RadTensor *k = rad_arg_in(a, 0), *po = rad_arg_in(a, 1), *cu = rad_arg_in(a, 2);
const RadTensor *tl = rad_arg_in(a, 3), *sx = rad_arg_in(a, 4), *bt = rad_arg_in(a, 5);
const RadTensor *rp = rad_arg_in(a, 6), *stg = rad_arg_in(a, 7), *pg = rad_arg_in(a, 8);
const RadTensor *bp = rad_arg_in(a, 9), *nc = rad_arg_in(a, 10);
if (!k || !po || !cu || !tl || !sx || !bt || !stg || !pg || !bp || !nc) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0), ring = p_int(a, "ring", 0);
if (n <= 0 || ratio <= 0 || ring < ratio) return RAD_E_INVAL;
if (k->rank != 2 || bt->rank != 2 || stg->rank != 2) return RAD_E_SHAPE;
if (tl->rank != 4 || tl->shape[1] != 1 || tl->shape[2] < ring || tl->shape[3] != n)
return RAD_E_SHAPE;
const int64_t T = k->shape[0], n_seq = numel(cu) - 1, slots = tl->shape[0];
if (T <= 0 || n_seq <= 0 || numel(po) < T || k->shape[1] != n || stg->shape[1] != n)
return RAD_E_SHAPE;
if (bt->shape[0] < n_seq || (sx->rank >= 2 ? sx->shape[0] : numel(sx)) < n_seq)
return RAD_E_SHAPE;
const int64_t mw = numel(pg);
if (mw < n_seq || stg->shape[0] < mw * ratio || numel(nc) < n_seq) return RAD_E_SHAPE;
int64_t bstep = 1;
if (bp->rank == 2) {
if (bp->shape[0] < mw || bp->stride[1] != 1 || bp->stride[0] < bp->shape[1] ||
(rp && bp->shape[1] < 3))
return RAD_E_SHAPE;
bstep = bp->stride[0];
} else if (rp || numel(bp) < mw) {
return RAD_E_SHAPE;
}
if (rp && (rp->rank != 2 || rp->shape[0] < 3 || rp->shape[1] < T)) return RAD_E_SHAPE;
for (int64_t t = 0; t < T; ++t)
if (ldi(po, offlin(po, t)) < 0) return RAD_E_INVAL;
/* The work list as (sequence, block), validated before any write. */
int64_t* items = (int64_t*)scratch_raw((size_t)mw * 2 * sizeof(int64_t) + 64);
int64_t ni = 0;
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t t0 = cu_at(cu, s), t1 = cu_at(cu, s + 1);
if (t1 <= t0) continue;
if (t0 < 0 || t1 > T) return RAD_E_SHAPE;
const int64_t p0 = ldi(po, offlin(po, t0)), p1 = ldi(po, offlin(po, t1 - 1));
for (int64_t b = p0 / ratio; b <= (p1 + 1) / ratio - 1; ++b) {
if (ni >= mw) break;
if (b >= bt->shape[1]) return RAD_E_SHAPE;
const int64_t si = ldi(sx, col0(sx, s));
if (si >= slots) return RAD_E_INVAL;
for (int64_t i = 0; si >= 0 && i < ratio; ++i) {
const int64_t q = b * ratio + i;
if (q >= p0 && t0 + (q - p0) >= T) return RAD_E_SHAPE;
}
items[2 * ni] = s;
items[2 * ni + 1] = b;
++ni;
}
}
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t t0 = cu_at(cu, s), t1 = cu_at(cu, s + 1);
st_int_dt(nc->dtype, nc->data, offlin(nc, s),
t1 > t0 ? (ldi(po, offlin(po, t1 - 1)) + 1) / ratio : 0);
}
const int ncomp = rp ? 3 : 1;
AVX_PARALLEL_FOR_IF(mw * ratio * n >= AVX_PAR_MIN)
for (int64_t w = 0; w < mw; ++w) {
auto bpos_at = [&](int c) { return bp->rank == 2 ? w * bstep + c : offlin(bp, w); };
if (w >= ni) {
st_int_dt(pg->dtype, pg->data, offlin(pg, w), -1);
for (int c = 0; c < ncomp; ++c) st_int_dt(bp->dtype, bp->data, bpos_at(c), 0);
continue;
}
const int64_t s = items[2 * w], b = items[2 * w + 1];
const int64_t t0 = cu_at(cu, s), p0 = ldi(po, offlin(po, t0));
const int64_t si = ldi(sx, col0(sx, s));
st_int_dt(pg->dtype, pg->data, offlin(pg, w),
si < 0 ? -1 : ldi(bt, s * bt->stride[0] + b * bt->stride[1]));
const int64_t f = b * ratio;
if (!rp) {
st_int_dt(bp->dtype, bp->data, bpos_at(0), f);
} else {
const int64_t rs = rp->stride[0], rc = rp->stride[1];
for (int c = 0; c < 3; ++c)
st_int_dt(bp->dtype, bp->data, bpos_at(c),
f >= p0 ? ldi(rp, c * rs + (t0 + f - p0) * rc)
: f + (ldi(rp, t0 * rc) - p0));
}
if (si < 0) continue;
float* buf = scratch_f32((size_t)n);
for (int64_t i = 0; i < ratio; ++i) {
const int64_t q = f + i;
if (q >= p0) widen(k, (t0 + q - p0) * k->stride[0], k->stride[1], n, buf);
else widen(tl, si * tl->stride[0] + (q % ring) * tl->stride[2], tl->stride[3], n, buf);
narrow(stg, (w * ratio + i) * stg->stride[0], stg->stride[1], n, buf);
}
}
return RAD_OK;
}
namespace {
/* VF_N bf16 values widened, and VF_N floats narrowed RTNE with the ABI's NaN rule: avx_vec.h's
* row conversions at one vector, for a kernel that keeps the vector in a register. */
static inline vf load_bf16(const uint16_t* p) {
#if AVX_LEVEL == 3
return _mm512_castsi512_ps(
_mm512_slli_epi32(_mm512_cvtepu16_epi32(_mm256_loadu_si256((const __m256i*)p)), 16));
#elif AVX_LEVEL == 2
return _mm256_castsi256_ps(
_mm256_slli_epi32(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*)p)), 16));
#elif AVX_LEVEL == 1
const __m128i h = _mm_loadu_si128((const __m128i*)p);
const __m128i lo = _mm_slli_epi32(_mm_cvtepu16_epi32(h), 16);
const __m128i hi = _mm_slli_epi32(_mm_cvtepu16_epi32(_mm_srli_si128(h, 8)), 16);
return _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_castsi128_ps(lo)),
_mm_castsi128_ps(hi), 1);
#else
return rad_bf16_to_f32(*p);
#endif
}
static inline void store_bf16(uint16_t* p, vf v) {
#if AVX_LEVEL == 3
_mm256_storeu_si256((__m256i*)p, _mm512_cvtepi32_epi16(bf16_round_bits(v)));
#elif AVX_LEVEL == 2
const __m256i w = bf16_round_bits(v);
_mm_storeu_si128((__m128i*)p, _mm_packus_epi32(_mm256_castsi256_si128(w),
_mm256_extracti128_si256(w, 1)));
#elif AVX_LEVEL == 1
const __m128i lo = bf16_round_bits128(_mm256_castps256_ps128(v));
const __m128i hi = bf16_round_bits128(_mm256_extractf128_ps(v, 1));
_mm_storeu_si128((__m128i*)p, _mm_packus_epi32(lo, hi));
#else
*p = rad_f32_to_bf16(v);
#endif
}
} /* namespace */
/* ------------------------------------------------------------------ dflash_conv */
namespace {
struct ConvJob {
const RadTensor *x, *dl, *bs, *o;
int64_t T, H, taps, group, NG, bsz;
int64_t x_rs, o_rs, d_rs, d_ts, d_gs;
};
/* Channels and rows a block: a block's widened base kernel (8 KiB a tap) and its slice of the row
* above stay in L1 while the block walks its rows. */
enum { kConvCols = 2048, kConvRows = 16 };
/* Rows [t0, t1) of groups [g0, g1), for dense rows of bf16 (XB, OB) or f32 and groups that span
* whole vectors. The rows a tap reads above are inputs, so any split of the rows is exact. */
template <bool XB, bool OB>
static void conv_block(const ConvJob& j, int64_t t0, int64_t t1, int64_t g0, int64_t g1) {
const int64_t G = j.group, ng = g1 - g0, cb = ng * G, h0 = g0 * G, taps = j.taps;
float* bf = scratch_f32((size_t)(taps * cb));
float* dg = scratch_f32_b((size_t)(taps * ng));
for (int64_t jt = 0; jt < taps; ++jt)
widen(j.bs, rowoff(j.bs, jt, j.H) + h0 * laststride(j.bs), laststride(j.bs), cb,
bf + jt * cb);
/* Element pointers as locals: through `j` the compiler reloads them after every store. */
using XT = typename std::conditional<XB, uint16_t, float>::type;
using OT = typename std::conditional<OB, uint16_t, float>::type;
const XT* const xd = (const XT*)j.x->data;
OT* const od = (OT*)j.o->data;
const int64_t x_rs = j.x_rs;
auto load = [](const XT* p) {
if constexpr (XB) return load_bf16(p);
else return vf_loadu(p);
};
auto store = [](OT* p, vf v) {
if constexpr (OB) store_bf16(p, v);
else vf_storeu(p, v);
};
for (int64_t t = t0; t < t1; ++t) {
/* Tap jt applies when jt == 0 or t % block_size >= jt, i.e. taps 0 .. nt - 1. */
const int64_t nt = std::min<int64_t>(taps, t % j.bsz + 1);
for (int64_t jt = 0; jt < nt; ++jt)
widen(j.dl, t * j.d_rs + jt * j.d_ts + g0 * j.d_gs, j.d_gs, ng, dg + jt * ng);
const XT* const x0 = xd + t * x_rs + h0;
OT* const out = od + t * j.o_rs + h0;
/* One and two taps (DFlash2's) straight-line; more in a loop. */
for (int64_t k = 0; k < ng; ++k) {
const vf d0 = vf_set1(dg[k]);
const int64_t i1 = (k + 1) * G;
if (nt == 1) {
for (int64_t i = k * G; i < i1; i += VF_N)
store(out + i, vf_mul(vf_add(vf_loadu(bf + i), d0), load(x0 + i)));
} else if (nt == 2) {
const vf d1 = vf_set1(dg[ng + k]);
const XT* const x1 = x0 - x_rs;
const float* const b1 = bf + cb;
for (int64_t i = k * G; i < i1; i += VF_N) {
const vf acc = vf_mul(vf_add(vf_loadu(bf + i), d0), load(x0 + i));
store(out + i, vf_fma(vf_add(vf_loadu(b1 + i), d1), load(x1 + i), acc));
}
} else {
for (int64_t i = k * G; i < i1; i += VF_N) {
vf acc = vf_mul(vf_add(vf_loadu(bf + i), d0), load(x0 + i));
for (int64_t jt = 1; jt < nt; ++jt)
acc = vf_fma(vf_add(vf_loadu(bf + jt * cb + i), vf_set1(dg[jt * ng + k])),
load(x0 - jt * x_rs + i), acc);
store(out + i, acc);
}
}
}
}
}
/* Any other rows: row t through f32 copies of x. */
static void conv_row(const ConvJob& j, const float* bf, int64_t t) {
const int64_t H = j.H, NG = j.NG, G = j.group;
const int64_t nt = std::min<int64_t>(j.taps, t % j.bsz + 1);
float* acc = scratch_f32((size_t)H);
float* xr = scratch_f32_b((size_t)H);
float* dg = scratch_f32_c((size_t)NG);
for (int64_t jt = 0; jt < nt; ++jt) {
const float* xv = in_row(j.x, (t - jt) * j.x_rs, H, xr);
const float* bj = bf + jt * H;
widen(j.dl, t * j.d_rs + jt * j.d_ts, j.d_gs, NG, dg);
for (int64_t g = 0; g < NG; ++g)
for (int64_t h = g * G; h < (g + 1) * G; ++h) {
const float term = (bj[h] + dg[g]) * xv[h];
acc[h] = jt == 0 ? term : acc[h] + term;
}
}
out_row(j.o, t * j.o_rs, H, acc);
}
} /* namespace */
/* DFlash2's grouped dynamic depthwise convolution over the [T, H] rows of x, blocks of
* `block_size` rows starting at row 0:
*
* out[t][h] = sum over taps j with j == 0 or t % block_size >= j of
* (base[j][h] + delta[t][j][h / group_size]) * x[t - j][h]
*
* in tap order, the coefficient add rounded as libref's, the product and sum fused. `delta` is
* [T, taps, NG], or [T, >= taps * NG] at its own row pitch. `out` must not alias `x`. */
AVX_KERNEL(dflash_conv) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *dl = &a->t[1], *bs = &a->t[2], *o = &a->t[3];
const int64_t taps = p_int(a, "taps", 0), group = p_int(a, "group_size", 0);
const int64_t NG = p_int(a, "NG", 0), bsz = p_int(a, "block_size", 0);
if (taps <= 0 || group <= 0 || NG <= 0 || bsz <= 0) return RAD_E_INVAL;
if (x->data == o->data) return RAD_E_INVAL;
if (x->rank != 2 || o->rank != 2) return RAD_E_SHAPE;
const int64_t T = x->shape[0], H = x->shape[1];
if (T <= 0 || o->shape[0] != T || o->shape[1] != H || H != NG * group) return RAD_E_SHAPE;
if (numel(bs) < taps * H) return RAD_E_SHAPE;
ConvJob j{};
j.x = x; j.dl = dl; j.bs = bs; j.o = o;
j.T = T; j.H = H; j.taps = taps; j.group = group; j.NG = NG; j.bsz = bsz;
j.x_rs = x->stride[0]; j.o_rs = o->stride[0];
if (dl->rank == 3) {
if (dl->shape[0] < T || dl->shape[1] < taps || dl->shape[2] < NG) return RAD_E_SHAPE;
j.d_rs = dl->stride[0]; j.d_ts = dl->stride[1]; j.d_gs = dl->stride[2];
} else if (dl->rank == 2) {
if (dl->shape[0] < T || dl->shape[1] < taps * NG) return RAD_E_SHAPE;
j.d_rs = dl->stride[0]; j.d_gs = dl->stride[1]; j.d_ts = NG * j.d_gs;
} else {
return RAD_E_SHAPE;
}
/* Dense bf16 and f32 rows, with groups of whole vectors so a group's delta is one broadcast:
* blocks of columns and rows, converted in the loads and the store. */
const bool fused = group % VF_N == 0 && laststride(x) == 1 && laststride(o) == 1 &&
(x->dtype == RAD_BF16 || x->dtype == RAD_F32) &&
(o->dtype == RAD_BF16 || o->dtype == RAD_F32);
if (fused) {
const int64_t gpb = std::max<int64_t>(1, kConvCols / group);
const int64_t ncb = (NG + gpb - 1) / gpb, nrb = (T + kConvRows - 1) / kConvRows;
const bool xb = x->dtype == RAD_BF16, ob = o->dtype == RAD_BF16;
AVX_PARALLEL_FOR_IF(T * H * taps >= ((int64_t)1 << 18))
for (int64_t u = 0; u < ncb * nrb; ++u) {
const int64_t g0 = (u % ncb) * gpb, g1 = std::min(g0 + gpb, NG);
const int64_t t0 = (u / ncb) * kConvRows, t1 = std::min(t0 + kConvRows, T);
if (xb && ob) conv_block<true, true>(j, t0, t1, g0, g1);
else if (xb) conv_block<true, false>(j, t0, t1, g0, g1);
else if (ob) conv_block<false, true>(j, t0, t1, g0, g1);
else conv_block<false, false>(j, t0, t1, g0, g1);
}
return RAD_OK;
}
/* The base kernel widened once; read-only inside the parallel loop. */
float* bf = (float*)scratch_raw((size_t)(taps * H) * sizeof(float) + 64);
for (int64_t jt = 0; jt < taps; ++jt)
widen(bs, rowoff(bs, jt, H), laststride(bs), H, bf + jt * H);
AVX_PARALLEL_FOR_IF(T * H * taps >= ((int64_t)1 << 18))
for (int64_t t = 0; t < T; ++t) conv_row(j, bf, t);
return RAD_OK;
}
+170 -196
View File
@@ -1,55 +1,32 @@
/* avx_quant.cpp -- the quantisers, the rotation, and the Gram accumulator.
*
* ============================== THE WALSH-HADAMARD IS BIT-IDENTICAL, ON PURPOSE ==============================
* Walsh-Hadamard, bit-identical to libref. The rotation is butterflies at strides 1, 2, 4, ... g/2,
* pairing i with i + h where (i & h) == 0. The stride matrices commute in exact arithmetic but not
* in f32, so libref's ascending order is kept: each butterfly is the same add and subtract on the
* same two floats, the rotated block is bit-identical, and the rotated-int8 family holds at the
* quantiser tolerance (1e-6). Only the lane mapping is vectorised (avx_had.h):
*
* 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.
* h >= VF_N the pair (i, i+h) is two whole vectors: one add, one sub, two stores.
* h < VF_N the partner is a swizzle within one vector (adjacent lanes, lane pairs, 128-bit
* lanes, 256-bit halves), results selected by a lane mask. Four such strides at
* AVX-512, three at AVX2; left scalar they would dominate at g = 128.
*
* 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:
* The rotation runs once per row. libref rotates each block twice (once for amax, once for the
* codes) because it has no row-sized scratch; here the row is rotated into scratch once.
*
* 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.
* `group` has three meanings (docs/OPS.md); reading the wrong one gives plausible numbers:
*
* 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.
* quant_act_i8 one scale per row; `group` is the width of the code
* sums `asum` holds.
* quant_act_i8g, quant_act_fp8, dequant contiguous elements sharing one scale; `scale` is
* and the fp8 fusions [M, ceil(n/group)].
* had_* int8 forms the rotation width; one scale per row, carrying
* 1/sqrt(group).
* had_* fp8 forms both, with no normalisation: <Hw, Ha> = g <w, a>, and
* the whole g is folded into the stored weight scale at
* convert, where dividing a bf16 by a power of two is
* exact. Splitting it as int8 does would round
* amax/7/sqrt(g) into bf16 (~0.2% error per group).
*/
#include "avx_vec.h"
#include "avx_common.h"
@@ -58,14 +35,8 @@ 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);
}
/* Codes are stored with out_row; for RAD_I8 that is the vectorised clamp + cvtps/packs path
* (avx_vec.h), bit-exact with libref's nearbyintf-and-clamp. */
/* Scale a row by a scalar, in place. */
static inline void scale_row(float* v, int64_t n, float s) {
@@ -76,10 +47,52 @@ static inline void scale_row(float* v, int64_t n, float 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. */
/* libref's arithmetic (ref_quant.cpp): one scale per row, max(amax, 1e-8) / 127, codes rounded to
* nearest even and stored in the step order, the middle two dwords of every 16-byte step
* exchanged. `asum` gets the per-`group` code sums, group-major [n/group][ceil(M/16)*16], taken
* from the row-major codes before the exchange. */
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 RadTensor* as = rad_arg_in(a, 3);
const int64_t n = p_int(a, "n", 0);
if (n <= 0 || n % 16) return RAD_E_SHAPE;
if (q->dtype != RAD_I8) return RAD_E_DTYPE;
if (!dense_row(q)) return RAD_E_STRIDE;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows) return RAD_E_SHAPE;
const int64_t g = as ? p_int(a, "group", 0) : 0;
const int64_t mpad = (rows + 15) / 16 * 16;
if (as && (g <= 0 || n % g || numel(as) < n / g * mpad)) 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);
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));
const float scale = std::max(row_amax(v, n), 1e-8f) / 127.0f;
cvt_scaled_f32_to_i8(v, 1.0f / scale, qb, n);
stt(s, rowoff(s, r, 1), scale);
for (int64_t gi = 0; as && gi < n / g; ++gi) {
int64_t sum = 0;
for (int64_t i = gi * g; i < (gi + 1) * g; ++i) sum += qb[i];
stt(as, gi * mpad + r, (float)sum);
}
for (int64_t k = 0; k < n; k += 16) {
uint32_t d1, d2;
std::memcpy(&d1, qb + k + 4, 4);
std::memcpy(&d2, qb + k + 8, 4);
std::memcpy(qb + k + 4, &d2, 4);
std::memcpy(qb + k + 8, &d1, 4);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ quant_act_i8g */
/* libr4d's quant_act_i8g: per `group` contiguous elements a scale amax * (1/127) (1 for an
* all-zero group), codes x * (1/scale) rounded to nearest even, row-major. */
AVX_KERNEL(quant_act_i8g) {
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);
@@ -92,48 +105,36 @@ AVX_KERNEL(quant_act_i8) {
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;
}
const bool dense_i8 = 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);
float* w = scratch_f32_b((size_t)n);
int8_t* qb = dense_i8 ? (int8_t*)byte_at(q->data, q->dtype, rowoff(q, r, n)) : nullptr;
float* w = dense_i8 ? nullptr : 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);
const float sc = amax > 0.0f ? amax * (1.0f / 127.0f) : 1.0f;
const float inv = 1.0f / sc;
if (dense_i8) {
cvt_scaled_f32_to_i8(v + k0, inv, qb + k0, k1 - k0);
} else {
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), sc);
}
store_codes(q, rowoff(q, r, n), n, w);
if (!dense_i8) out_row(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. */
/* Rotation at width `group`, then symmetric int8 with one scale per row carrying the
* 1/sqrt(group); amax is over the whole rotated 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];
@@ -145,9 +146,7 @@ AVX_KERNEL(had_quant_act_i8) {
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. */
/* Dense i8: one fused scale+encode call per row. */
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) {
@@ -166,34 +165,27 @@ AVX_KERNEL(had_quant_act_i8) {
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. */
/* in_row may return the operand itself for dense f32; copy before the in-place rotation
* so the input is not modified. */
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);
out_row(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.
/* Fused rmsnorm + Hadamard + quant_act_i8, the w4a8 counterpart of 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.
* With `residual` (the fused_add_rms_norm form) the sum is written back into `residual` (INOUT;
* the next layer's shortcut reads it). As in libref, the variance comes from the f32 sum and the
* rotation reads the sum narrowed to the residual's dtype.
*
* `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. */
* `out_bf16` receives the post-norm, pre-rotation row for a layer that also has a bf16 consumer. */
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];
@@ -212,8 +204,7 @@ AVX_KERNEL(rmsnorm_had_quant_i8) {
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. */
/* Gain with `wadd` folded in, widened once per launch (as in avx_norm.cpp). */
float* gain = (float*)scratch_raw((size_t)n * sizeof(float));
{
const int64_t ws = laststride(w);
@@ -228,14 +219,15 @@ AVX_KERNEL(rmsnorm_had_quant_i8) {
float* buf = scratch_f32_b((size_t)n);
float* tmp = scratch_f32_c((size_t)n);
float ss;
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. */
/* x + residual, stored, its variance taken, then narrowed through the residual's
* dtype in scratch. */
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);
ss = row_sumsq(buf, n);
if (res->dtype != RAD_F32) {
row_from_f32(res->dtype, buf, tmp, n);
row_to_f32(res->dtype, tmp, buf, n);
@@ -244,34 +236,33 @@ AVX_KERNEL(rmsnorm_had_quant_i8) {
} 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));
ss = row_sumsq(src, n);
}
const float sc = 1.0f / std::sqrt(row_sumsq(src, n) / (float)n + eps);
const float sc = 1.0f / std::sqrt(ss / (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 */
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);
out_row(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.
/* Gated product, then the rotation and the quantiser. `act` selects the w4a8 site: 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. */
* With `b` absent, `a` is a packed [M, 2n] gate_up plane, gate first. */
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];
@@ -307,24 +298,22 @@ AVX_KERNEL(gated_had_quant_i8) {
}
for (; i < n; ++i) {
const float gt = gv[i];
const float sg = 1.0f / (1.0f + std::exp(-gt));
const float sg = 1.0f / (1.0f + sc_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);
out_row(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. */
/* q * scale, with the scale tensor's extent giving the group count. The inverse of quant_act_i8
* only; it does not undo a rotation. */
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];
@@ -343,9 +332,8 @@ AVX_KERNEL(dequant) {
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. */
/* Per group, with the scale hoisted (libref divides per element to find it). Same
* product. */
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g;
if (k0 >= n) break;
@@ -356,8 +344,8 @@ AVX_KERNEL(dequant) {
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. */
/* Elements past the described groups use the last group's scale, as libref clamps
* (`gi < ngrp ? gi : ngrp - 1`). */
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;
@@ -368,18 +356,14 @@ AVX_KERNEL(dequant) {
}
/* ------------------------------------------------------------------ quant_act_fp8 */
/* The three choices this shares with libr4d's kernel, none of them derivable:
/* Conventions shared with libr4d's kernel:
*
* 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. */
* 448 E4M3's largest finite value. scale = amax / 448 is a dequant multiplier, the same
* sense as a checkpoint's `weight_scale_inv`, so the GEMM multiplies the two scales.
* scale 1 for an all-zero group (amax/448 = 0 has no reciprocal), because the GEMM
* multiplies the block scales and 0 would erase the weight's.
* the clamp amax * (1/scale) can land an ulp above 448 after rounding the reciprocal, which
* would encode as NaN. */
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];
@@ -410,13 +394,12 @@ AVX_KERNEL(quant_act_fp8) {
}
/* ------------------------------------------------------------- rmsnorm_quant_fp8 */
/* RMS norm, an optional residual add, and quant_act_fp8, in one pass.
/* RMS norm, 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). */
* With `residual`, the sum is written back narrowed to that tensor's dtype and the whole norm,
* variance included, is taken over the narrowed sum: the `add` + `rmsnorm` pair, unlike
* rmsnorm_add, which takes its variance from the unrounded sum. The normalised row is narrowed to
* bf16 before the codes are taken (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];
@@ -436,8 +419,7 @@ AVX_KERNEL(rmsnorm_quant_fp8) {
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. */
/* Gain with `wadd` folded in, widened once on the calling thread (as in avx_norm.cpp). */
float* gain = (float*)scratch_raw((size_t)n * sizeof(float));
{
const int64_t ws = laststride(w);
@@ -480,9 +462,9 @@ AVX_KERNEL(rmsnorm_quant_fp8) {
}
/* ------------------------------------------------------------- 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. */
/* act(gate) * up over a packed [M, 2n] gate_up plane (gate first), then quant_act_fp8 over the
* bf16-narrowed product. `act` is silu or sigmoid (`mode` is libr4d's integer form); default
* silu. */
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];
@@ -512,21 +494,18 @@ AVX_KERNEL(gated_quant_fp8) {
}
/* ------------------------------------------------------------- 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.
/* quant_act_fp8 with a `group`-wide Hadamard before the absmax, which shrinks the maximum the grid
* is scaled by.
*
* 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. */
* Unlike had_quant_act_i8, 1/sqrt(g) is not applied here. <Hw, Ha> = g <w, a>, and the whole g is
* divided out of the weight scale instead, where dividing a bf16 by a power of two is 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. */
/* n % g != 0 is refused: a block straddling the row end would mix in padding, unlike any
* rotated weight block. */
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;
@@ -552,12 +531,11 @@ AVX_KERNEL(had_quant_act_fp8) {
}
/* ------------------------------------------------------------- givens_rotate */
/* ParoQuant's activation side for a 16-bit GEMM: each row divided by its channel scales and rotated
* by `stages` rounds of disjoint Givens pairs, once a part, the parts side by side in y. libref's
* arithmetic (ref_quant.cpp) in its order: the divide, then a' = a cos t + b sin t,
* b' = b cos t - a sin t in f32, stage by stage. A pair walk is a gather and a scatter with nothing
* to vectorise; what is hoisted is the cos and sin of every angle, a property of the weight and the
* same for every row, so they are taken once a call rather than once a row. */
/* ParoQuant's activation side for a 16-bit GEMM: each row is divided by its channel scales and
* rotated by `stages` rounds of disjoint Givens pairs, once per part, parts side by side in y.
* libref's arithmetic and order (ref_quant.cpp): the divide, then a' = a cos t + b sin t,
* b' = b cos t - a sin t in f32, stage by stage. The pair walk is a gather/scatter and stays
* scalar; the cos and sin of each angle are computed once per call. */
AVX_KERNEL(givens_rotate) {
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *pr = &a->t[1], *an = &a->t[2], *sc = &a->t[3], *y = &a->t[4];
@@ -582,8 +560,8 @@ AVX_KERNEL(givens_rotate) {
}
for (int64_t j = 0; j < NP; ++j) {
const float th = ldt(an, j);
cs[j] = std::cos(th);
sn[j] = std::sin(th);
cs[j] = sc_cos(th);
sn[j] = sc_sin(th);
}
for (int64_t k = 0; k < P * n; ++k) rs[k] = ldt(sc, k);
@@ -612,12 +590,12 @@ AVX_KERNEL(givens_rotate) {
}
/* --------------------------------------------------------- givens_dense_quant */
/* The quantising form: the rotation as one dense 128 x 128 f16 matrix a (part, group) -- `tdense`,
* which rad-convert composes from the pairs and angles and stores as the weight's "t.dense" table --
* then the block-scaled quantiser `out` names: "fp8" E4M3 with scale amax / 448, "i8" scale
* amax / 127 rounded to nearest; scale 1 for an all-zero group, as libref. The matrices are widened
* to f32 once a call; a row is then a matrix-vector product a group, in f32 where libref sums in
* f64, so a code can differ from libref's where the value sits on a rounding edge. */
/* Quantising form: the rotation as one dense 128 x 128 f16 matrix per (part, group) (`tdense`,
* which rad-convert composes from the pairs and angles as the weight's "t.dense" table), then the
* block-scaled quantiser named by `out`: "fp8" E4M3 with scale amax / 448, or "i8" with scale
* amax / 127, rounded to nearest; scale 1 for an all-zero group, as libref. The matrices are widened
* to f32 once per call. Each group is a matrix-vector product summed in f32 (libref uses f64), so a
* code on a rounding edge can differ from libref's. */
AVX_KERNEL(givens_dense_quant) {
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *tm = &a->t[1], *sc = &a->t[2], *q = &a->t[3], *s = &a->t[4];
@@ -673,26 +651,17 @@ AVX_KERNEL(givens_dense_quant) {
/* ---------------------------------------------------------------- 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[k1][k2] += sum over rows of x[m][k1] * x[m][k2], where x is the dequantised E4M3 input, or a
* bf16 input as is when no scale is passed: the second moment GPTQ's error feedback needs, over 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.
* `h` accumulates across launches: the caller zeroes it once and runs a calibration corpus through.
*
* 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. */
* Accumulation is f64 here (f32 on the device), as in libref: the result is consumed offline by
* the packer, and the kbench tolerance covers the gap. The f64 inner reduction stays scalar; only
* the dequantisation is vectorised, once per row into a scratch plane rather than in the k2 loop. */
AVX_KERNEL(gram_accum) {
/* `a_scale` is optional: absent, `a` is read as it stands, which is the bf16 form. */
/* `a_scale` is optional; without it `a` is read as 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;
@@ -721,16 +690,21 @@ AVX_KERNEL(gram_accum) {
}
}
/* The upper triangle, each sum added to both (k1, k2) and (k2, k1): the products commute, so
* the two sums are the same bits. Rows of the triangle shrink, hence the dynamic schedule. */
const int64_t hst = laststride(h);
AVX_PARALLEL_FOR_IF(n * n >= 1024)
#ifdef _OPENMP
AVX_PRAGMA(omp parallel for schedule(dynamic, 8) if(n * n >= 1024 || avx_par_forced())
num_threads(avx_team_size()))
#endif
for (int64_t k1 = 0; k1 < n; ++k1) {
const int64_t hb = rowoff(h, k1, n);
for (int64_t k2 = 0; k2 < n; ++k2) {
for (int64_t k2 = k1; 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));
const int64_t o12 = rowoff(h, k1, n) + k2 * hst, o21 = rowoff(h, k2, n) + k1 * hst;
stt(h, o12, (float)((double)ldt(h, o12) + acc));
if (k2 != k1) stt(h, o21, (float)((double)ldt(h, o21) + acc));
}
}
return RAD_OK;
+394 -151
View File
@@ -1,64 +1,40 @@
/* avx_registry.cpp -- what libavx contains, in the two forms the core reads it in.
/* avx_registry.cpp -- the op schemas and kernel rows libavx exports.
*
* ============================== THE SCHEMAS ARE libref's, DELIBERATELY IDENTICAL ==============================
* Schemas match libref's exactly. The first plugin in hierarchy order to declare an op fixes its
* schema; a later plugin declaring it differently is refused at load (rad_abi.h,
* core/plugin/loader.cpp: schema_same). That compares parameters position by position (key, type,
* requiredness) and operands (role, optionality), not operand names. The table is copied rather
* than shared because a plugin links only abi/; rad-avx-check runs the loader's comparison against
* libref over every schema before checking any number, so the copy cannot drift silently.
*
* 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.
* No opd_shape. That hook sizes an op's operands for a tool calling it cold; libref implements it
* for the whole conventional vocabulary (docs/OPS.md), and libavx computes the same ops at the same
* shapes. A second set of answers could disagree with libref's. A tool with libavx but not libref
* could not size buffers; both host plugins ship together.
*
* 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.
* No tunables. The vector width is fixed by the ISA level, and the GEMM's M block is derived from K
* against a fixed L2 byte target (avx_gemm.cpp), with no occupancy interaction to search over.
*/
#include "avx_isa.h"
#include "avx_planes.h"
#include "avx_rows.h"
#include "rad_abi.h"
#include "rad_planes.h"
#include "rad_plugin.h"
#include <cstring>
/* ================================================================== 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. */
* Same macro names as libref, so the schema sections of libref/ref_registry.cpp and this file can
* be diffed directly. */
#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_CAP(k) { k, RAD_P_INT, RAD_REQUIRED, RAD_PROLE_CAPACITY }
#define P_F64(k) { k, RAD_P_F64, RAD_REQUIRED }
#define P_F64O(k) { k, RAD_P_F64, RAD_OPTIONAL }
@@ -75,12 +51,12 @@
#define ARR(a) (a), (int)(sizeof(a) / sizeof((a)[0]))
/* ---- elementwise and norms ---------------------------------------------------------------- */
/* rmsnorm_add has no `mult`: it is the fused pair, and nothing fuses a scaled branch. */
/* rmsnorm_add has no `mult`: no fused residual-norm site uses a scaled branch. */
static const RadParamSpec pRmsnormAdd[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"),
P_F64O("wadd") };
static const RadParamSpec pRmsnorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"),
P_F64O("wadd"), P_F64O("mult") };
/* `w` optional: absent, the gain is one. */
/* `w` is optional; absent means a gain of 1. */
static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT_O("w"), OUT("y") };
static const RadParamSpec pHcRead[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("lowrank"),
@@ -136,7 +112,7 @@ static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coor
static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") };
/* `cap` required, for the reason libref's pMnCap states: a softcap without a cap is a different op. */
/* `cap` is required (as in libref's pMnCap). */
static const RadParamSpec pMnCap[] = { P_INT("M"), P_INT("n"), P_F64("cap"), P_STR("dtype") };
static const RadOperandSpec oBinary[] = { OPD("a"), OPD("b"), OUT("y") };
static const RadOperandSpec oMulWeight[] = { OPD("x"), WGT("w"), OUT("y") };
@@ -147,26 +123,36 @@ static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_
P_STR("dtype") };
static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") };
static const RadOperandSpec oUnary[] = { OPD("x"), OUT("y") };
/* The audio (USM conformer) tower's operators; libref's lists, field for field. */
/* The audio (USM conformer) tower's operators, as in libref. */
static const RadOperandSpec oClamp[] = { OPD("x"), WGT("lo"), WGT("hi"), OUT("y") };
static const RadParamSpec pConv2d[] = { P_INT("M"), P_INT("width"), P_INT("cin"), P_INT("cout"),
P_INT("kh"), P_INT("kw"), P_INT("stride"), P_INT("pad"),
P_INTO("cu_div"), P_INTO("valid_stride"),
P_STR("dtype") };
P_STR("dtype"), P_INTO("t_last"), P_STRO("act") };
static const RadOperandSpec oConv2d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("valid"),
OUT("y") };
OUT("y"), WGT_O("b") };
static const RadParamSpec pConv2dUnfold[] = { P_INT("M"), P_INT("width"), P_INT("cin"),
P_INT("kh"), P_INT("kw"), P_INT("stride"),
P_INT("pad"), P_INTO("cu_div"),
P_INTO("valid_stride"), P_INTO("t_last"),
P_STR("dtype") };
static const RadOperandSpec oConv2dUnfold[] = { OPD("x"), OPD("cu_seqlens"), OPD_O("valid"),
OUT("y") };
static const RadParamSpec pConv1dDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_INTO("cu_div"),
P_STR("dtype") };
static const RadOperandSpec oConv1dDw[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OUT("y") };
static const RadParamSpec pRelSin[] = { P_INT("M"), P_INT("n"), P_F64O("max_timescale"),
P_STR("dtype") };
static const RadOperandSpec oRelSin[] = { OUT("y") };
static const RadParamSpec pSegSin[] = { P_INT("M"), P_INT("n"), P_INT("period"),
P_F64O("max_timescale"), P_INTO("cu_div"), P_STR("dtype") };
static const RadOperandSpec oSegSin[] = { OPD("cu_seqlens"), OUT("y") };
static const RadParamSpec pAttnLocalRel[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("left"), P_INT("right"), P_F64("softcap"),
P_INTO("cu_div"), P_STR("dtype") };
static const RadOperandSpec oAttnLocalRel[] = { OPD("q"), OPD("k"), OPD("v"), OPD("relk"),
WGT("pds"), OPD("cu_seqlens"), OUT("out") };
/* `fill` has no input: `value` is the whole of what it writes. */
/* `fill` has no input; it writes `value`. */
static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") };
static const RadOperandSpec oFill[] = { OUT("y") };
static const RadOperandSpec oScale[] = { OPD("x"), WGT("s"), OUT("y") };
@@ -181,8 +167,8 @@ static const RadParamSpec pQuant[] = { P_INT("M"), P_INT("n"), P_INT("group
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") };
/* ParoQuant's rotation, libref's declaration: the tables are the "givens" encoding's
* (abi/rad_encoding.h) and WEIGHT operands, resolved and placed with the weight they belong to. */
/* ParoQuant's rotation, as libref declares it: the tables come from the "givens" encoding
* (abi/rad_encoding.h) and are weight operands, placed with the weight they belong to. */
static const RadParamSpec pGivensRotate[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"),
P_INT("stages"), P_INT("parts") };
static const RadParamSpec pGivensDense[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"),
@@ -192,8 +178,8 @@ static const RadOperandSpec oGivensDense[] = { OPD("x"), WGT("tdense"), WGT("rsc
static const RadOperandSpec oGivensRotate[] = { OPD("x"), WGT("pairs"), WGT("angle"), WGT("rscale"),
OUT("y") };
/* The fp8 fusions: the unfused pair's operands minus the tensor between them, and `out_bf16` to
* put even that back. */
/* The fp8 fusions: the unfused pair's operands minus the intermediate tensor, which `out_bf16`
* can optionally still produce. */
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"),
@@ -212,7 +198,7 @@ static const RadParamSpec pGatedQuant[] = { P_INT("M"), P_INT("n"), P_INT("gro
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. */
/* `a_scale` is optional: a "bf16" activation has 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"),
@@ -235,7 +221,7 @@ static const RadOperandSpec oGemmQ[] = { OPD("a"), OPD_O("a_scale"), WGT("b
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
/* `act` is required here (optional in the quantiser); `N` is the weight's rows, twice the output
* width. */
static const RadParamSpec pGemmQGated[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
P_STR("dtype"), P_STR("act") };
@@ -256,7 +242,8 @@ 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"), P_INTO("window") };
P_INTO("max_seqlen"), P_INTO("window"),
P_INTO("cu_div"), P_INTO("block") };
static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
OUT("out") };
@@ -281,8 +268,8 @@ static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("th
P_INTO("head_dim"), P_STRO("ladder") };
static const RadOperandSpec oRopeTable[] = { OPD("positions"), OUT("cos_sin") };
/* QSA's compressed key, libr4d's schema exactly (libr4d/r4d_rows.cpp): `block_size` is `ratio`
* spelled for the KV group the block-key store is, `page` and `pos` are optional. */
/* QSA's compressed key, libr4d's schema (libr4d/r4d_rows.cpp): `block_size` is `ratio` under the
* name the block-key store's KV group uses; `page` and `pos` are optional. */
static const RadParamSpec pQsaBlockKey[] = { P_INT("M"), P_INT("n"), P_INT("ratio"),
P_INT("rotary_dim"), P_INTO("pos0"),
P_INTO("block_size"), P_F64("eps"), P_F64("theta"),
@@ -293,6 +280,27 @@ static const RadParamSpec pQsaBlockKey[] = { P_INT("M"), P_INT("n"), P_INT("rati
static const RadOperandSpec oQsaBlockKey[] = { OPD("k"), WGT("w"), OPD_O("page"), OPD_O("pos"),
OUT("out") };
/* The rest of the QSA indexer, as libref declares it. `M` counts query rows (score, select) or
* tokens (tail store, work list); `seqs` is the declared height of `cu`'s sequences, whose count is
* cu's length less one. `work` bounds the blocks that can complete. */
static const RadParamSpec pQsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"), P_INT("blocks"),
P_INT("seqs"), P_STR("dtype") };
static const RadOperandSpec oQsaScore[] = { OPD("q"), OPD("bk"), OPD("bt"), OPD("cu"), OPD("nc"),
OUT("score") };
static const RadParamSpec pQsaSelect[] = { P_INT("M"), P_INT("blocks"), P_INT("topk"),
P_INT("ratio"), P_INT("seqs") };
static const RadOperandSpec oQsaSelect[] = { OPD("score"), OPD("bt"), OPD("nc"), OPD("pos"),
OPD("cu"), OUT("sel"), OUT("nsel"), OUT("seqused") };
static const RadParamSpec pQsaTailStore[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("ring"),
P_INT("seqs"), P_STR("dtype") };
static const RadOperandSpec oQsaTailStore[] = { OPD("k"), OPD("pos"), OPD("cu"), INOUT("state"),
OPD("sidx") };
static const RadParamSpec pQsaWork[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("ring"),
P_INT("seqs"), P_CAP("work"), P_STR("dtype") };
static const RadOperandSpec oQsaWork[] = { OPD("k"), OPD("pos"), OPD("cu"), OPD("state"),
OPD("sidx"), OPD("bt"), OPD_O("rope"), OUT("stage"),
OUT("page"), OUT("bpos"), OUT("nc") };
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"),
@@ -305,10 +313,7 @@ static const RadOperandSpec oQkNormRope[] = { INOUT("qkv"), OPD("positions"), WG
/* ---- 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. */
/* `add` is optional and comes before `y`; operands are positional, so `y` is index 3. */
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"),
@@ -326,9 +331,9 @@ static const RadParamSpec pMoeGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P
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. */
/* Experts in two tables by parity: `w` the even ones at [N, K], `w_odd` the odd ones at
* [N_odd, K_odd], with `parts` parts stacked along the rows and the output (see libr4d's
* schema). */
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"),
@@ -336,8 +341,8 @@ static const RadParamSpec pMoeGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"),
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") };
/* The same over four classes by the expert's number mod 4, `w_q` class q at [N_q, K_q]. Mirrors
* libref's and libr4d's schema exactly. */
/* The same over four classes by expert number mod 4, `w_q` class q at [N_q, K_q], as in libref
* and libr4d. */
static const RadParamSpec pMoeGemmQMod4[] = { 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_1"),
@@ -349,10 +354,9 @@ static const RadOperandSpec oMoeGemmQMod4[] = { OPD("a"), OPD_O("a_scale"), WTAB
WTAB("w_1_scale"), WTAB("w_2"), WTAB("w_2_scale"),
WTAB("w_3"), WTAB("w_3_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. */
/* With `shared` and `shared_gate`, the shared expert is folded in: y = narrow(shared * act(gate))
* + narrow(gathered), the unfused pair's roundings. `act` is sigmoid or none, as in scale_rows,
* applied to the per-token gate scalar. */
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"),
@@ -368,9 +372,9 @@ static const RadOperandSpec oRowTopkMerge[] = { OPD("gathered"), OUT("idx"), OUT
static const RadParamSpec pPairArgmax[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
static const RadOperandSpec oPairArgmax[] = { OPD("pairs"), OUT("idx"), OUT_O("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. */
/* As libref: R candidates rescored against the full-precision head, ties to the lower id, pads
* last. libref's shape hook does not describe this op, so the checker skips its geometries, but
* the row is needed for the coverage gate. */
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") };
@@ -416,8 +420,7 @@ static const RadOperandSpec oRecurrent[] = {
};
/* 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. */
* recurrence's minus q, k and v; parameters are the union of both ops'. */
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"),
@@ -444,6 +447,46 @@ static const RadParamSpec pAllGather[] = { P_INT("world_size"), P_INT("numel")
P_INTO("row") };
static const RadOperandSpec oAllGather[] = { OPD("x"), OUT("y") };
/* ---- image generation --------------------------------------------------------------------- */
static const RadParamSpec pLnMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") };
static const RadOperandSpec oLnMod[] = { OPD("x"), OPD("s"), OPD("cu_seqlens"), OUT("y") };
static const RadOperandSpec oGateAdd[] = { OPD("y"), OPD("g"), OPD("cu_seqlens"), INOUT("x") };
static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
P_INT("gated"), P_STR("dtype") };
static const RadOperandSpec oLnModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), OPD("cu_seqlens"),
INOUT("x"), OUT("q"), OUT("scale"), OUT_O("z") };
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"), P_F64("max_period"),
P_INTO("round"), P_STR("dtype") };
static const RadOperandSpec oTimestep[] = { OPD("t"), OUT("y") };
static const RadOperandSpec oGather2[] = { OPD("a"), OPD("b"), OPD("idx"), OUT("y") };
static const RadParamSpec pLane[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("dtype") };
static const RadOperandSpec oLaneGather[] = { OPD("src"), OPD("lane"), OPD("cu_seqlens"), OUT("y") };
static const RadOperandSpec oLaneStore[] = { OPD("src"), OPD("lane"), INOUT("dst") };
static const RadOperandSpec oRandnLanes[] = { OPD("flags"), OPD("seed"), OPD("lane"),
OPD("cu_seqlens"), INOUT("dst") };
static const RadOperandSpec oFlowEuler[] = { OPD("v"), OPD("sigma"), OPD("sigma_next"), OPD("cfg"),
OPD("pair"), OPD("lane"), OPD("flags"), OPD("seed"),
OPD("cu_seqlens"), OPD_O("inp_lat"), OPD_O("inp_mask"),
INOUT("state"), INOUT_O("preview") };
static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"),
P_STR("mode"), P_STR("dtype") };
static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("stride"), P_STR("pad"), P_INT("up"), P_STR("dtype") };
static const RadOperandSpec oConvNhwc[] = { OPD("x"), WGT("w"), WGT("b"), OUT("y") };
static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") };
static const RadOperandSpec oL2Norm[] = { OPD("x"), WGT("gamma"), OUT("y") };
static const RadParamSpec pSpaceDepth[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("ft"),
P_STR("dtype") };
static const RadOperandSpec oSpaceDepth[] = { OPD("x"), INOUT("y") };
static const RadParamSpec pAttnPS[] = { P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"),
P_INTD("block_size"), P_INT("causal"), P_STR("q_dtype"),
P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"),
P_INTO("n_head"), P_INTO("max_seqs"), P_STRO("qk") };
static const RadOperandSpec oAttnPS[] = { OPD("q"), OPD("k"), OPD("v"), OPD("kv_cache"),
OPD("block_table"), OPD("seqused"), OPD("cu_seqlens"),
OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("k_i8"),
OPD_O("k_scale"), OUT("out") };
/* ---- vocabulary edges --------------------------------------------------------------------- */
static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"),
P_STR("dtype"), P_INTO("vocab_offset"),
@@ -462,8 +505,8 @@ 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. */
/* As libref: the history stages take the rank's first vocabulary row (`vocab_off`), 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") };
@@ -491,23 +534,25 @@ static const RadParamSpec pDflashSelect[] = { P_INT("M"), P_INT("steps"), P_I
static const RadOperandSpec oDflashSelect[] = { OPD("cand"), OPD("unary"), OPD_O("hp"),
OPD("anchor"), WGT("pred"), WGT("succ"),
OUT("tokens") };
/* DFlash2's grouped convolution, as libref declares it. */
static const RadParamSpec pDflashConv[] = { P_INT("T"), P_INT("hidden_size"), P_INT("taps"),
P_INT("group_size"), P_INT("NG"), P_INT("block_size"),
P_STR("dtype") };
static const RadOperandSpec oDflashConv[] = { OPD("x"), OPD("delta"), WGT("base"), OUT("out") };
/* ================================================================== 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.
* Doc strings are libavx's own (schema_same does not compare them); which plugin's string a reader
* sees depends on which fixed the schema first. libref's are 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." },
"y = x * rsqrt(mean(x^2) + eps) * (w + wadd); the sum of squares is a four-accumulator vector "
"reduction, in a different order from libref's." },
{ "rmsnorm_p", ARR(pLayernorm), ARR(oUnary),
"y = x * rsqrt(mean(x^2) + eps), the rmsnorm with no gain at all. Same four-accumulator sum of "
"squares as rmsnorm; the only difference is there is no weight to widen, so the op has no `w`." },
"y = x * rsqrt(mean(x^2) + eps): rmsnorm with no gain, summed as rmsnorm sums." },
{ "rmsnorm_add", ARR(pRmsnormAdd), 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." },
"residual_out = x + residual, then y = rmsnorm(residual_out) * w: the variance from the unrounded "
"f32 sum, the multiply from residual_out after narrowing, as libref." },
{ "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),
@@ -525,9 +570,9 @@ static const RadOpSchema kSchemas[] = {
"x += a side x side position table resampled bilinearly to the row's grid." },
{ "grid_embed_aa", ARR(pGridEmbed), ARR(oGridEmbed),
"x += the table resampled as torch's antialiased half-pixel bilinear, SigLIP2's." },
{ "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." },
{ "add", ARR(pMnD), ARR(oBinary),
"y = a + b; a `b` of exactly n elements against a taller output broadcasts along rows." },
{ "mul", ARR(pMnD), ARR(oBinary), "y = a * b, with the same broadcast rule as `add`." },
{ "mul_weight", ARR(pMulWeight), ARR(oMulWeight),
"y = x * w, `w` a weight of one element or one row, broadcast; f32 product rounded once." },
{ "act_mul", ARR(pActMul), ARR(oBinary),
@@ -541,6 +586,10 @@ static const RadOpSchema kSchemas[] = {
{ "conv1d_dw", ARR(pConv1dDw), ARR(oConv1dDw),
"segment-wise causal depthwise convolution over time." },
{ "rel_sinusoid", ARR(pRelSin), ARR(oRelSin), "the sinusoidal relative-position table." },
{ "conv2d_unfold", ARR(pConv2dUnfold), ARR(oConv2dUnfold),
"a convolution's receptive fields as rows, columns in the weight's order." },
{ "seg_sinusoid", ARR(pSegSin), ARR(oSegSin),
"sinusoidal absolute positions restarting every `period` rows of a segment." },
{ "attn_local_rel", ARR(pAttnLocalRel), ARR(oAttnLocalRel),
"local attention with a relative-position term and a softcap (Gemma 4's audio)." },
{ "pool_rows", ARR(pPoolRows), ARR(oUnary),
@@ -568,12 +617,13 @@ static const RadOpSchema kSchemas[] = {
"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." },
"dtype conversion; narrowing is the ABI's round-to-nearest-even, bit for bit." },
{ "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." },
"symmetric int8, one f32 scale a row, codes in the int8 WMMA's step order; `asum` gets the "
"per-`group` code sums (libref's description)." },
{ "quant_act_i8g", ARR(pQuant), ARR(oQuantFp8),
"symmetric int8, one f32 scale per `group` contiguous elements, row-major." },
{ "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: "
@@ -603,9 +653,8 @@ static const RadOpSchema kSchemas[] = {
"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." },
"C = A B^T, f32 accumulate, cache-blocked with a register-blocked microkernel; it sums in a "
"different order from libref's straight loop." },
{ "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),
@@ -625,6 +674,21 @@ static const RadOpSchema kSchemas[] = {
"QSA's compressed key: the mean of a block's `ratio` rows rounded to k's dtype, RMS-normed with "
"gain (wadd + w), rotated at the block's position with `rope`'s ladder and YaRN; libref's "
"arithmetic with the angles from one table a block." },
{ "qsa_score", ARR(pQsaScore), ARR(oQsaScore),
"score[m][b] = (sum over heads of relu(q[m][h] . bk[bt[seq(m)][b]])) / sqrt(n) for the sequence's "
"first min(nc, width) blocks, a negative page id scoring -inf; the dots in vector order, the "
"heads summed in order. Columns past the bound are not written." },
{ "qsa_select", ARR(pQsaSelect), ARR(oQsaSelect),
"the topk highest-scoring complete blocks as page ids, libref's order exactly: the blocks above "
"the threshold in block order, then its ties in block order, then the partial page, then -1 to "
"topk + 1; a radix select, linear in the blocks." },
{ "qsa_tail_store", ARR(pQsaTailStore), ARR(oQsaTailStore),
"state[sidx[s][0]][pos[t] % ring] = k[t] for the last `ring` tokens of each sequence; the other "
"rows of the tail keep what they held." },
{ "qsa_work", ARR(pQsaWork), ARR(oQsaWork),
"the blocks completing in this batch: each block's `ratio` raw keys staged contiguously, its "
"block-key page and first-token position; slots past the count get page -1. nc is each "
"sequence's complete-block count." },
{ "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),
@@ -652,9 +716,10 @@ static const RadOpSchema kSchemas[] = {
{ "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 decode recurrence against the paged state cache. `state_form` names the reading: "
"\"per_candidate\" (one state per candidate token) or libr4d's two-slot \"anchor\" (one "
"committed state and its tokens' replay factors), both as libref reads them; any other form is "
"declined by name." },
{ "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 "
@@ -663,6 +728,49 @@ static const RadOpSchema kSchemas[] = {
{ "all_reduce", ARR(pAllReduce), ARR(oAllReduce),
"sum across ranks, f32, ascending rank order." },
{ "all_gather", ARR(pAllGather), ARR(oAllGather), "gather every rank's shard." },
{ "ln_mod_quant_fp8", ARR(pLnModQ), ARR(oLnModQ),
"gate_add (with `gated` 1), ln_mod and quant_act_fp8 in one pass, each value rounded as its own "
"store would round it; z written when bound." },
{ "ln_mod", ARR(pLnMod), ARR(oLnMod),
"y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a gainless layer norm and the row's entry's "
"modulation row of `s` ([n_seq, >= n] at its own pitch)." },
{ "gate_add", ARR(pMnD), ARR(oGateAdd),
"x = bf16(x + bf16(bf16(tanh(g[seq])) * y)), bit for bit libref's." },
{ "timestep_embed", ARR(pTimestep), ARR(oTimestep),
"the sinusoidal timestep embedding [cos | sin], libref's libm calls; `round` 1 takes t through "
"bf16 at scale and back first." },
{ "gather_rows2", ARR(pMnD), ARR(oGather2),
"y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]], zeros past either source." },
{ "lane_gather", ARR(pLane), ARR(oLaneGather),
"y[cu[e] + k] = src[lane[e] * stride + k]; every entry checked before a row is written." },
{ "lane_store", ARR(pLane), ARR(oLaneStore),
"dst[l * stride + k] = src[k] for every lane l listed." },
{ "randn_lanes", ARR(pLane), ARR(oRandnLanes),
"an image's first step: its lane's rows become its seed's normal stream (abi/rad_philox.h), "
"bit for bit libref's." },
{ "flow_euler", ARR(pLane), ARR(oFlowEuler),
"one flow-matching Euler step per entry that moves a lane, with guidance, the preview and the "
"repaint's kept region; libref's roundings bit for bit." },
{ "chan_affine", ARR(pChanAffine), ARR(oUnary),
"a per-channel affine from two lists of n bf16 values, `fma` or `inv`." },
{ "conv2d_nhwc", ARR(pConvNhwc), ARR(oConvNhwc),
"an image convolution, channels innermost, as GEMMs over bands of patch rows; `up` 2 reads the "
"input upsampled nearest-neighbour, `pad` same or down." },
{ "l2norm_chan", ARR(pL2Norm), ARR(oL2Norm),
"each pixel's channels to unit L2, times sqrt(n), times gamma (three roundings), then `act`." },
{ "d2s_add", ARR(pSpaceDepth), ARR(oSpaceDepth),
"y [2H, 2W * cout] += x [H, W * cin] repeated and dealt into 2x2 blocks (DupUp3D, one frame)." },
{ "s2d_avg_add", ARR(pSpaceDepth), ARR(oSpaceDepth),
"y [H, W * cout] += the 2x2 blocks of x dealt into channels and averaged in groups (AvgDown3D, "
"one frame)." },
{ "to_rgba8", ARR(pMnD), ARR(oUnary),
"decoded pixels in [-1, 1] to bytes as diffusers' postprocess makes them, u8 out." },
{ "gelu_tanh", ARR(pMnD), ARR(oUnary), "the tanh approximation of gelu." },
{ "scatter_add_rows", ARR(pMnD), ARR(oScatterRows),
"x[idx[i]] += v[i], rounded to x's dtype; a negative index adds nothing." },
{ "attn_prefix_self", ARR(pAttnPS), ARR(oAttnPS),
"attention over `seqused[s]` prefix positions in the paged cache and the step's own rows, "
"flash-attention tiles; `qk` \"i8\" is the int8 score form (docs/OPS.md)." },
{ "embed_lookup", ARR(pEmbedM), ARR(oEmbed),
"embedding gather, vocab-parallel with an offset; `mult` multiplies every row (rounded once)." },
{ "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ),
@@ -681,13 +789,16 @@ static const RadOpSchema kSchemas[] = {
{ "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." },
"top 24 bits as a float in [0,1), so a host reference, a device kernel and a rerun draw the "
"same stream." },
{ "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." },
{ "sample_logprobs", ARR(pLogprobs), ARR(oLogprobs),
"the raw logits' max, sum of exp(l - max) and k largest (id, logit) pairs, for a row with "
"RAD_SP_LOGPROBS." },
{ "dflash_conv", ARR(pDflashConv), ARR(oDflashConv),
"DFlash2's grouped dynamic depthwise convolution: out[t][h] = sum over taps j, j == 0 or "
"t % block_size >= j, of (base[j][h] + delta[t][j][h / group_size]) * x[t - j][h]." },
{ "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. "
@@ -696,18 +807,13 @@ static const RadOpSchema kSchemas[] = {
/* ================================================================== 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.
* Every row is domain HOST at priority 0 and unconstrained, except `block_size` on attn_paged and
* kv_store (as in libref): the constraint admits any value but requires the key to be present,
* since the cache cannot be walked without the 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. */
* Every row's shape is "any", since every extent is read from the operands (avx_common.h). The
* ISA level is deliberately not a constraint: rows are identical on every CPU and only the code
* underneath changes. */
#define SHAPE_ANY "any: every extent is read off the operands, strides included"
#define ROW(nm, opname, fam, what, dts, cons, ncons, fn) \
@@ -717,11 +823,88 @@ static const RadOpSchema kSchemas[] = {
#define SIMPLE(nm, opname, fam, what, dts, fn) ROW(nm, opname, fam, what, dts, nullptr, 0, fn)
/* ---- the codebook experts' layout hooks, on moe_gemm_q and moe_gemm_q_mod4
*
* A codebook expert's codes view (`codes,table`) and two-level scale view (`scale,scale.1`) are
* stored joined (abi/rad_planes.h); a view of one plane is stored as it is. The selections
* accepted are libref's (libref/ref_moe.cpp: cb_check), so a weight libref refuses at declare is
* refused here too, and both libraries store the same bytes under one tag. */
struct CbForm { int bits; int64_t group; uint32_t sdt; bool level; };
static CbForm cb_form(const RadParam* p, int n_p) {
const RadParam* d = rad_param_find(p, n_p, "dtype");
const char* s = d && d->kind == RAD_P_STR ? d->sval : nullptr;
if (s && !std::strcmp(s, "w4nla8h")) return CbForm{ 4, 128, RAD_BF16, false };
if (s && !std::strcmp(s, "w4nl64a8h")) return CbForm{ 4, 64, RAD_F8E4M3, true };
if (s && !std::strcmp(s, "w4nl32a8h")) return CbForm{ 4, 32, RAD_F8E4M3, true };
if (s && !std::strcmp(s, "w5nl64a8h")) return CbForm{ 5, 64, RAD_F8E4M3, true };
return CbForm{ 0, 0, 0, false };
}
static int cb_check(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, int n_planes) {
const CbForm f = cb_form(p, n_p);
const bool codes = operand == 2 || operand == 6 || operand == 8 || operand == 10;
const bool scale = operand == 3 || operand == 7 || operand == 9 || operand == 11;
if (!f.bits || (!codes && !scale) || !enc || !sel || n_planes != 2 ||
std::strcmp(enc->transform, "fwht128") != 0)
return RAD_E_DTYPE;
for (int i = 0; i < 2; ++i)
if (sel[i] < 0 || sel[i] >= enc->n_planes) return RAD_E_SHAPE;
const RadEncPlane& a = enc->plane[sel[0]];
const RadEncPlane& b = enc->plane[sel[1]];
if (codes)
return !std::strcmp(a.role, "codes") && a.kind == RAD_PLANE_TILED &&
a.dtype == (f.bits == 5 ? (uint32_t)RAD_U5 : (uint32_t)RAD_U4) &&
a.block[0] == 1 && a.block[1] == 1 && !std::strcmp(b.role, "table") &&
b.kind == RAD_PLANE_TABLE && b.dtype == RAD_F32 && b.extent[0] == 1 &&
b.extent[1] == ((int64_t)1 << f.bits)
? RAD_OK : RAD_E_DTYPE;
return f.level && !std::strcmp(a.role, "scale") && a.kind == RAD_PLANE_TILED &&
a.dtype == f.sdt && a.block[0] == 1 && a.block[1] == f.group &&
!std::strcmp(b.role, "scale.1") && b.kind == RAD_PLANE_TILED && b.dtype == RAD_F32 &&
b.block[0] == 0 && b.block[1] == 0
? RAD_OK : RAD_E_DTYPE;
}
static int avx_moe_cb_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n_planes,
RadLayout* out) {
if (n_planes <= 1) return RAD_E_UNSUPPORTED;
const int rc = cb_check(p, n_p, operand, enc, sel, n_planes);
return rc < 0 ? rc : rad_planes_layout(enc, sel, planes, n_planes, out);
}
static int avx_moe_cb_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n_planes, void* dst,
int64_t dst_bytes) {
if (n_planes <= 1) return RAD_E_UNSUPPORTED;
const int rc = cb_check(p, n_p, operand, enc, sel, n_planes);
return rc < 0 ? rc : rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes);
}
static int avx_moe_cb_unrelayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const void* src, int64_t src_bytes,
const RadTensor* planes, int n_planes) {
if (n_planes <= 1) return RAD_E_UNSUPPORTED;
const int rc = cb_check(p, n_p, operand, enc, sel, n_planes);
return rc < 0 ? rc : rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n_planes);
}
#define ROW_CB(nm, opname, fam, what, dts, fn) \
{ nm, opname, fam, what, SHAPE_ANY, dts, RAD_DOMAIN_HOST, 0, \
nullptr, 0, nullptr, 0, nullptr, nullptr, nullptr, fn, nullptr, avx_moe_cb_layout, \
avx_moe_cb_relayout, nullptr, avx_moe_cb_unrelayout, nullptr }
/* A row whose weight operands may be joined over several planes (avx_planes.h): libref's hooks for
* the op, restated, so both libraries store and read one form. */
#define ROWL(nm, opname, fam, what, dts, fn, lay) \
{ nm, opname, fam, what, SHAPE_ANY, dts, RAD_DOMAIN_HOST, 0, \
nullptr, 0, nullptr, 0, nullptr, nullptr, nullptr, fn, nullptr, avxp::lay, \
avxp::avx_relayout_planes<avxp::lay>, nullptr, avxp::avx_unrelayout_planes<avxp::lay>, \
nullptr }
#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"
#define DT_FLOAT_CB DT_FLOAT "; or u4 / u5 codes into an f32 table, joined (w4nl* / w5nl*)"
/* 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. */
/* Rows launch through the baseline-compiled thunks, which are valid before rad_plugin_open
* (avx_dispatch.cpp). */
#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)
@@ -735,12 +918,16 @@ SIMPLE("avx_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", D
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)),
ROWL("avx_hc_read", "hc_read", "norm",
"gated residual read: grouped norm, low-rank gate, stream mix",
DT_FLOAT ", or mixing matrices of E4M3 / int8 codes with a scale plane, joined", L(hc_read),
avx_layout_hc),
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)),
ROWL("avx_mtp_enter", "mtp_enter", "norm",
"MTP head entry: two norms, a per-sub-stream fc and a broadcast fc",
DT_FLOAT ", or fc matrices of E4M3 / int8 codes with a scale plane, joined", L(mtp_enter),
avx_layout_mtp),
SIMPLE("avx_layernorm", "layernorm", "norm", "layer norm with gain and bias", DT_FLOAT,
L(layernorm)),
SIMPLE("avx_grid_embed", "grid_embed", "elem",
@@ -765,6 +952,12 @@ SIMPLE("avx_conv1d_dw", "conv1d_dw", "elem", "segment-wise causal depthwise conv
DT_FLOAT, L(conv1d_dw)),
SIMPLE("avx_rel_sinusoid", "rel_sinusoid", "elem", "sinusoidal relative-position table",
DT_FLOAT, L(rel_sinusoid)),
SIMPLE("avx_conv2d_unfold", "conv2d_unfold", "elem",
"a convolution's receptive fields as rows, for a GEMM against its weight",
DT_FLOAT, L(conv2d_unfold)),
SIMPLE("avx_seg_sinusoid", "seg_sinusoid", "elem",
"sinusoidal absolute positions, restarting every `period` rows of a segment",
DT_FLOAT, L(seg_sinusoid)),
SIMPLE("avx_attn_local_rel", "attn_local_rel", "attn",
"local attention with a relative-position term and a softcap", DT_FLOAT,
L(attn_local_rel)),
@@ -795,8 +988,12 @@ 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",
SIMPLE("avx_quant_act_i8", "quant_act_i8", "quant",
"symmetric int8 activation quantiser, one scale a row, codes in the WMMA step order",
"float in, i8 out, f32 scale", L(quant_act_i8)),
SIMPLE("avx_quant_act_i8g", "quant_act_i8g", "quant",
"symmetric int8 activation quantiser, one scale per group, row-major",
"float in, i8 out, f32 scale", L(quant_act_i8g)),
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)),
@@ -835,8 +1032,9 @@ SIMPLE("avx_gated_quant_fp8", "gated_quant_fp8", "quant",
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)),
ROWL("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; u2 / u4 / u5 codes with an f16 scale "
"and integer zero per group, joined; f32 accumulate", L(gemm_nt_q), avx_layout_gemm_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",
@@ -860,6 +1058,16 @@ SIMPLE("avx_qsa_block_key", "qsa_block_key", "attn",
L(qsa_block_key)),
SIMPLE("avx_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary embedding",
DT_FLOAT, L(qk_norm_rope)),
SIMPLE("avx_qsa_score", "qsa_score", "attn",
"QSA block scores: per-head relu dots summed over the heads", DT_FLOAT, L(qsa_score)),
SIMPLE("avx_qsa_select", "qsa_select", "attn",
"QSA selection: the top-k blocks as a page-id table, partial page last",
"f32 scores, i32 tables", L(qsa_select)),
SIMPLE("avx_qsa_tail_store", "qsa_tail_store", "attn",
"QSA tail: the raw keys of open blocks into a per-sequence ring", DT_FLOAT,
L(qsa_tail_store)),
SIMPLE("avx_qsa_work", "qsa_work", "attn",
"QSA work list: completing blocks' keys, pages and positions", DT_FLOAT, L(qsa_work)),
SIMPLE("avx_router_topk", "router_topk", "moe", "softmax then exact top-k routing", DT_FLOAT,
L(router_topk)),
@@ -867,11 +1075,12 @@ SIMPLE("avx_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing
"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_gemm_q_mod4", "moe_gemm_q_mod4", "moe",
ROW_CB("avx_moe_gemm_q", "moe_gemm_q", "moe",
"grouped GEMM over the expert-sorted rows, quantised operands", DT_FLOAT_CB,
L(moe_gemm_q)),
ROW_CB("avx_moe_gemm_q_mod4", "moe_gemm_q_mod4", "moe",
"grouped GEMM over the expert-sorted rows, quantised operands, four classes by number mod 4",
DT_FLOAT, L(moe_gemm_q_mod4)),
DT_FLOAT_CB, L(moe_gemm_q_mod4)),
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)),
@@ -880,9 +1089,10 @@ SIMPLE("avx_row_topk_merge", "row_topk_merge", "moe",
SIMPLE("avx_pair_argmax", "pair_argmax", "moe",
"the global top-1 of a row of gathered (id, value) pairs, one id a row", DT_FLOAT,
L(pair_argmax)),
SIMPLE("avx_logit_rerank", "logit_rerank", "moe",
"R candidates a row rescored exactly against the full-precision head", DT_FLOAT,
L(logit_rerank)),
ROWL("avx_logit_rerank", "logit_rerank", "moe",
"R candidates a row rescored exactly against the full-precision head",
DT_FLOAT ", or a head of E4M3 / int8 codes with a scale plane, joined", L(logit_rerank),
avx_layout_head),
SIMPLE("avx_gdn_conv_prep", "gdn_conv_prep", "gdn",
"gdn prefill preamble: conv, split, l2 norm, gate cumsum, beta", DT_FLOAT,
@@ -901,33 +1111,65 @@ SIMPLE("avx_gdn_conv_recurrent_update", "gdn_conv_recurrent_update", "gdn",
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. */
/* No init/fini on the collectives: unlike libref's (ref_collective_init sets up a cross-rank
* rendezvous), these serve world_size 1 only, where both are copies (see avx_misc.cpp). */
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_ln_mod", "ln_mod", "norm", "gainless layer norm times (1 + an entry's scale row)",
DT_FLOAT, L(ln_mod)),
SIMPLE("avx_gate_add", "gate_add", "elem", "x += tanh(gate row) * y", DT_FLOAT, L(gate_add)),
SIMPLE("avx_ln_mod_quant_fp8", "ln_mod_quant_fp8", "norm",
"gated residual, adaptive norm and the E4M3 quantiser in one pass",
"float in, fp8_e4m3 out, f32 scale, bf16 z", L(ln_mod_quant_fp8)),
SIMPLE("avx_timestep_embed", "timestep_embed", "elem", "sinusoidal timestep embedding", DT_FLOAT,
L(timestep_embed)),
SIMPLE("avx_gather_rows2", "gather_rows2", "elem", "rows from two sources by a signed index",
DT_ANY, L(gather_rows2)),
SIMPLE("avx_lane_gather", "lane_gather", "elem", "each entry's rows out of its lane", DT_ANY,
L(lane_gather)),
SIMPLE("avx_lane_store", "lane_store", "elem", "one source's rows into several lanes", DT_ANY,
L(lane_store)),
SIMPLE("avx_randn_lanes", "randn_lanes", "elem", "a lane's rows from its seed's normal stream",
DT_FLOAT, L(randn_lanes)),
SIMPLE("avx_flow_euler", "flow_euler", "elem", "a flow-matching Euler step with guidance",
DT_FLOAT, L(flow_euler)),
SIMPLE("avx_chan_affine", "chan_affine", "elem", "a per-channel affine from parameter lists",
DT_FLOAT, L(chan_affine)),
SIMPLE("avx_conv2d_nhwc", "conv2d_nhwc", "conv",
"an image convolution, channels innermost, as GEMMs over patch rows", DT_FLOAT,
L(conv2d_nhwc)),
SIMPLE("avx_l2norm_chan", "l2norm_chan", "norm", "unit-L2 channel norm, scaled, optional silu",
DT_FLOAT, L(l2norm_chan)),
SIMPLE("avx_d2s_add", "d2s_add", "elem", "an upsampling shortcut added in", DT_FLOAT, L(d2s_add)),
SIMPLE("avx_s2d_avg_add", "s2d_avg_add", "elem", "a downsampling shortcut added in", DT_FLOAT,
L(s2d_avg_add)),
SIMPLE("avx_to_rgba8", "to_rgba8", "elem", "decoded pixels to bytes", DT_FLOAT, L(to_rgba8)),
SIMPLE("avx_gelu_tanh", "gelu_tanh", "elem", "tanh gelu", DT_FLOAT, L(gelu_tanh)),
SIMPLE("avx_scatter_add_rows", "scatter_add_rows", "elem", "x[idx[i]] += v[i]", DT_FLOAT,
L(scatter_add_rows)),
SIMPLE("avx_attn_prefix_self", "attn_prefix_self", "attn",
"attention over a paged prefix and the step's own rows, flash-attention tiles",
"bf16 or f32 q, k, v and cache; int8 score form", L(attn_prefix_self)),
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. Its init refuses a process that
* may not make the io_uring ring the cache's misses are read through, at declare and not at the
* first request. */
/* Its layout hook only validates: the table is read as stored and other encodings are refused
* (avx_ngram.cpp). An E4M3 table into bf16 goes through the row cache; other dtype pairs take
* the general gather. The init hook refuses, at declare, a process that cannot create the
* io_uring ring the cache misses are read through. */
{ "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 */
/* init, fini, launch, scratch, layout, relayout, opd_shape, unrelayout, replaces */
avx_init_ngram, 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)),
nullptr },
ROWL("avx_logits_gemm", "logits_gemm", "vocab", "the lm_head projection",
DT_FLOAT ", or a head of E4M3 / int8 codes with a scale plane, joined", L(logits_gemm),
avx_layout_head),
SIMPLE("avx_sample_penalties", "sample_penalties", "sample",
"repetition, frequency and presence penalties", DT_FLOAT, L(sample_penalties)),
@@ -954,6 +1196,8 @@ SIMPLE("avx_sample_pick", "sample_pick", "sample", "seeded inverse-CDF draw", DT
SIMPLE("avx_sample_argmax", "sample_argmax", "sample", "greedy pick", DT_FLOAT, L(sample_argmax)),
SIMPLE("avx_sample_logprobs", "sample_logprobs", "sample", "the raw distribution's summary",
DT_FLOAT, L(sample_logprobs)),
SIMPLE("avx_dflash_conv", "dflash_conv", "draft",
"DFlash2 grouped dynamic depthwise convolution", DT_FLOAT, L(dflash_conv)),
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)),
@@ -965,10 +1209,9 @@ static const RadPluginInfo kInfo = {
"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. */
"scalar / AVX / AVX2+FMA / AVX-512. Same ops and schemas as libref, the same answers to a "
"tolerance",
/* Not a -march string: the binary runs on any x86-64 and picks its own path at load. */
"host"
};
+10 -13
View File
@@ -1,13 +1,11 @@
/* 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.
/* avx_rows.h -- the quantised embedding gather, split in two: 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. */
* embed_lookup_q over an E4M3 table into bf16 serves the n-gram table, tens of gigabytes in a
* mapped container that is never loaded, so fetching the rows is the whole cost. That half (a
* shared row cache, direct reads for misses, a reader thread one step ahead) is the same at every
* level and lives in avx_ngram.cpp, with one row cache per process. Decoding codes to bf16 differs
* per level, so each level's kernel passes its own decoder. */
#ifndef RAD_AVX_ROWS_H
#define RAD_AVX_ROWS_H
@@ -47,13 +45,12 @@ 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). */
/* The table must be an E4M3 plane with one scale, or plain bf16, stored as is (avx_ngram.cpp). */
extern "C" int avx_layout_ngram(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
/* Whether this process can read the table's rows: refused, with the reason on stderr, where it may
* not make an io_uring ring (avx_ngram.cpp). */
/* Refuses, with the reason on stderr, when this process may not create an io_uring ring and so
* cannot read the table's rows (avx_ngram.cpp). */
extern "C" int avx_init_ngram(const RadParam*, int, int, int, void**);
#endif /* RAD_AVX_ROWS_H */
+124 -197
View File
@@ -1,45 +1,27 @@
/* avx_sample.cpp -- the sampler ops.
*
* ============================== THESE ARE NOT WHERE THE TIME GOES, EXCEPT WHERE THEY ARE ==============================
* Most of these work over a candidate set of at most about a thousand entries, where the cost is
* control flow; they widen candidate values to f32 once and otherwise keep libref's structure. The
* three that touch the whole vocabulary (a megabyte per row at 248K) are vectorised:
*
* 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.
* sample_temp a row multiply.
* sample_argmax maximum, lowest index on a tie, through the same `topk_next_f32` the routers
* use, so greedy and top-1 agree on ties (a greedy request is staged at
* top_k = 1 when lm_head is vocab-sharded).
* sample_mask a vocabulary bitmask. At AVX-512 a grammar half-word is a `__mmask16`, so 16
* tokens take one masked store of -inf; lower levels shift and test per token.
*
* The exceptions are the three that touch the WHOLE VOCABULARY, and at a 248K vocabulary that is a
* megabyte a row:
* Per-request settings (`rep`, `freq`, `pres`, `k`, `p`, seed, position) are fields of a params row
* (abi/rad_sample.h), not op parameters: parameters are geometry fixed at declare, so they could
* not differ between requests in one batch.
*
* 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.
* Candidate set: `sample_topk` writes a fixed-width set and the narrowing stages edit it in place.
* A dropped candidate is index -1, value -infinity; kept candidates stay in place, in descending
* order. `cand_val` holds logits, and each stage takes its own softmax over the set (as llama.cpp
* does), so stages compose in any order.
*
* ============================== 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.
* A greedy row (RAD_SP_GREEDY) has no candidates: its token comes from sample_argmax, top-k and the
* merge write it an empty set, and the narrowing stages and the pick skip it (libref's contract).
*/
#include "avx_vec.h"
#include "avx_common.h"
@@ -50,15 +32,10 @@
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. */
/* Validates the params operand. A row array is a byte blob declared as
* [rows, sizeof(RadSampleParams)/4] u32 (the builder's only way to say "this many bytes a row"), so
* the dtype must be a 32-bit one; a 16-bit view would pass a byte-count check and 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) {
@@ -72,10 +49,10 @@ static inline int rows_of_params(const RadTensor* t, int64_t M, Rows* out) {
#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. */
/* History window for the penalty and DRY stages, as in libref (ref_sample.cpp): `hist_off` and
* `hist_len` address this row of the history plane, clamped to it, and `last_n` keeps the tail of
* that span. last_n 0 disables the stage for the row; negative keeps the whole span (llama.cpp's
* repeat_last_n / 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;
@@ -95,20 +72,17 @@ static inline bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_
/* ------------------------------------------------------------------ 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)
* 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 repetition penalty is sign-dependent: dividing a negative logit would raise it.
*
* 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.
* The history is copied into an int array once, so libref's O(hl^2) first-occurrence scan
* compares integers instead of switching on dtype; same scan, same result.
*
* 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. */
* History ids are global and the logits row is this rank's shard: a token's column is its id minus
* `vocab_off`, and tokens outside the shard belong to another rank. */
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];
@@ -142,8 +116,7 @@ AVX_KERNEL(sample_penalties) {
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. */
/* First occurrence only; `count` carries the multiplicity. */
bool first = true;
int64_t count = 0;
for (int64_t j = 0; j < hl; ++j) {
@@ -163,18 +136,15 @@ AVX_KERNEL(sample_penalties) {
}
/* ------------------------------------------------------------------ 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.
/* DRY ("don't repeat yourself"), as in libref (ref_sample.cpp) and llama.cpp: each token that
* would extend a previously seen suffix of the window is penalised once, by
* multiplier * base^(L - allowed_length) for the longest repeat L it extends, with repeats capped at
* the row's `dry_rep_limit`. Positions marked in the optional `breakers` plane hold sequence
* breakers and are never penalised. The penalty is built by repeated multiplication that stops
* short of overflow, as other implementations do, so results 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. */
* The window and the per-position repeat lengths are kept in two int arrays; the longest repeat
* per token is found by scanning them, with no map. */
static inline float dry_penalty(float multiplier, float base, int64_t e) {
float pen = multiplier;
if (base == 1.0f) return pen;
@@ -222,9 +192,8 @@ AVX_KERNEL(sample_dry) {
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. */
/* len[j]: length of the window suffix that also ends at j, capped; 0 when the token
* after j is a breaker or outside this rank's shard. */
for (int64_t j = 0; j + 1 < hl; ++j) {
const int64_t lim = j + 1 < cap ? j + 1 : cap;
int64_t n = 0;
@@ -238,9 +207,7 @@ AVX_KERNEL(sample_dry) {
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. */
/* Penalise each token once, at its longest repeat (earliest position on a tie). */
const int32_t next = h[j + 1];
bool rep = true;
for (int64_t j2 = 0; j2 + 1 < hl && rep; ++j2) {
@@ -256,8 +223,7 @@ AVX_KERNEL(sample_dry) {
}
/* ------------------------------------------------------------------ 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. */
/* temp <= 0 leaves the row untouched; greedy decoding is `sample_argmax`. */
AVX_KERNEL(sample_temp) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1];
@@ -300,24 +266,21 @@ AVX_KERNEL(sample_topk) {
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. */
/* The candidate width is the buffer's (the deployment bound), not the request's top_k. */
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. */
/* Optional vocab-parallel pair plane. cand_idx stays local (it indexes this rank's logits);
* `pairs` holds the same candidates as (u32 global id = local + vocab_off, f32 logit bits),
* which the all-gather moves and 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. */
/* The row's top_k, clamped to the buffer; <= 0 means the full width. A greedy row takes
* none and its logits are not 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;
@@ -335,8 +298,7 @@ AVX_KERNEL(sample_topk) {
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. */
/* 0xffffffff marks a hole; the merge reads it as a negative id (cand_idx's -1). */
uint32_t bits;
const float val = ok ? pv : -INFINITY;
std::memcpy(&bits, &val, 4);
@@ -350,17 +312,12 @@ AVX_KERNEL(sample_topk) {
/* ================================================================== 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.
* Unlike libref, which reads `cand_val` through `ldt` inside O(n_cand) and O(n_cand^2) loops, all
* four widen the candidate values to f32 once. Otherwise libref's structure is kept.
*
* 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. */
* The typical stage also precomputes each candidate's probability and surprisal distance (libref
* recomputes exp and log inside the threshold search). The search stays libref's O(n_cand^2) scan:
* a faster one would sort, which could change 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) {
@@ -400,39 +357,34 @@ static int narrow(const RadArgs* a, Narrow which) {
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. */
/* Keep candidates within a factor p of the most likely. exp(v - max) >= p is
* prob >= p * max_prob without the normaliser. */
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);
if (sc_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);
for (int64_t i = 0; i < n_cand; ++i) if (alive[i]) sum += sc_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;
prob[i] = alive[i] ? sc_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. */
/* Candidates arrive in descending order from sample_topk and are not re-sorted. Keep
* the shortest prefix whose cumulative probability reaches p, at least one. */
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;
if (cum >= p) done = true;
}
continue;
}
@@ -441,17 +393,16 @@ static int narrow(const RadArgs* a, Narrow which) {
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
* to the entropy H until their mass reaches p. This orders by |surprisal - H|, not by
* probability, so the selection is a distance threshold rather than a prefix. Ties at
* the threshold are all kept (may overshoot p), so the result does not depend on
* 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. */
if (alive[i] && prob[i] > 0.0f) H -= prob[i] * sc_log(prob[i]);
float* dist = val; /* `val` is dead here; 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;
dist[i] = (alive[i] && prob[i] > 0.0f) ? std::fabs(-sc_log(prob[i]) - H) : 0.0f;
float cut = 0.0f;
bool have_cut = false;
@@ -473,11 +424,9 @@ static int narrow(const RadArgs* a, Narrow which) {
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. */
/* XTC ("exclude top choices"): with probability `xtc_probability`, drop every candidate
* above `xtc_threshold` except the least likely of them. The draw comes from the row's
* own random stream, so it is reproducible. */
{
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)
@@ -487,8 +436,7 @@ static int narrow(const RadArgs* a, Narrow which) {
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. */
/* Needs at least two candidates above the threshold. */
if (n_above < 2) continue;
for (int64_t i = 0; i < n_cand; ++i) {
if (!alive[i] || i == last_above) continue;
@@ -505,18 +453,13 @@ 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.
/* Applies a GBNF grammar's token bitmask (the state machine runs on the host; the mask is 19 KiB
* per sequence at a 151K vocab). A set bit means allowed. Word w bit b covers token 32*w + b, LSB
* first.
*
* 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. */
* At AVX-512 sixteen bits of a mask word are a `__mmask16`, so sixteen tokens take one masked store
* of -inf with the mask inverted. Below AVX-512 the mask would have to be expanded to a 0/-1 vector
* and blended, which costs more than the scalar shift-and-test. */
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];
@@ -548,8 +491,7 @@ AVX_KERNEL(sample_mask) {
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. */
/* Store -inf where the grammar 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);
}
@@ -567,15 +509,12 @@ AVX_KERNEL(sample_mask) {
}
/* ------------------------------------------------------------------ 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.
/* Inverse CDF in candidate order, accumulated in f32. If rounding lets `u` (< 1) fall through,
* the fallback is the last candidate above -infinity, never a grammar-masked one top-k left at
* -infinity at the tail. Greedy rows are skipped (their 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. */
* The draw is specified (abi/rad_sample.h): splitmix64 over (seed * golden ratio + pos), 24 bits as
* a float in [0, 1), so host, device and reruns produce the same stream. */
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];
@@ -603,7 +542,7 @@ AVX_KERNEL(sample_pick) {
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);
sum += sc_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);
@@ -615,7 +554,7 @@ AVX_KERNEL(sample_pick) {
if (id < 0) continue;
const float v = ldt(cv, vb + i * vs);
if (v > -INFINITY) last = id;
cum += std::exp(v - mx) * inv;
cum += sc_exp(v - mx) * inv;
if (u < cum) { chosen = id; break; }
}
st_int_dt(tok->dtype, tok->data, offlin(tok, m), chosen >= 0 ? chosen : last);
@@ -624,12 +563,9 @@ AVX_KERNEL(sample_pick) {
}
/* ------------------------------------------------------------------ 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. */
/* Greedy, ties to the lower token id, through the same `topk_next_f32` as top-k. When lm_head is
* vocab-sharded this op is unusable (its answer is a local column) and greedy requests run at
* top_k = 1 instead, so both paths must pick the same token. */
AVX_KERNEL(sample_argmax) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *tok = &a->t[2];
@@ -651,20 +587,18 @@ AVX_KERNEL(sample_argmax) {
}
/* ------------------------------------------------------------------ sample_logprobs */
/* The raw distribution's summary for a row with RAD_SP_LOGPROBS -- max, sum of exp(l - max), and
* the k largest as (id, logit) pairs, descending, ties to the lower id -- libref's contract
* (ref_sample.cpp). A row without the flag is not written.
/* For rows with RAD_SP_LOGPROBS: max, sum of exp(l - max), and the k largest as (id, logit)
* pairs, descending, ties to the lower id (libref's contract, ref_sample.cpp). Other rows are not
* written.
*
* ONE PASS FOR THE k LARGEST, not k passes of topk_next_f32: `k` is the deployment's width (the
* largest top_logprobs any request may ask for), and k full sweeps of a 248K row would cost k times
* the argmax. The set is seeded with the row's first k columns, kept sorted, and the rest of the
* row is compared a vector at a time against its smallest value; a lane strictly above it is
* inserted. Strictly, because the scan runs in increasing id, and an equal value further along has
* the higher id and loses the tie. After the first few thousand columns almost no vector has such
* a lane, so the pass costs what the maximum does.
* One pass for the k largest instead of k passes of topk_next_f32 (`k` is the deployment's maximum
* top_logprobs). A sorted set is seeded with the first k columns; the rest of the row is compared
* a vector at a time against the set's smallest value, and lanes strictly above it are inserted.
* Strictly, because ids increase along the scan and an equal later value loses the tie. Few vectors
* pass the test after the first few thousand columns.
*
* The sum is f32 in four vector accumulators. Its terms are all in (0, 1] and the relative error
* of the sum is what a logprob carries (log of it), so f32 is ample next to libref's double. */
* The sum is f32 in four accumulators. Its terms are in (0, 1] and a logprob carries only its
* relative error, so f32 suffices (libref uses double). */
AVX_KERNEL(sample_logprobs) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *st = &a->t[2];
@@ -700,7 +634,7 @@ AVX_KERNEL(sample_logprobs) {
}
for (; i + VF_N <= n_vocab; i += VF_N) s0 = vf_add(s0, vf_exp(vf_sub(vf_loadu(v + i), vmx)));
sum = vf_hsum(vf_add(vf_add(s0, s1), vf_add(s2, s3)));
for (; i < n_vocab; ++i) sum += std::exp(v[i] - mx);
for (; i < n_vocab; ++i) sum += sc_exp(v[i] - mx);
}
/* Insert (x, id) into the sorted set of n entries, the set at most k long. */
@@ -745,22 +679,17 @@ AVX_KERNEL(sample_logprobs) {
}
/* ------------------------------------------------------------------ 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.
/* Vocab-parallel merge. With lm_head vocab-sharded, 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, world_size=4) instead of
* the full logits.
*
* `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.
* `gathered` is [M, world_size * n_cand] (token id, logit) pairs as raw u32 words. Ids are already
* global (each rank adds its vocab offset before the gather). The logit is read by bit pattern,
* since the buffer's dtype is u32.
*
* 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. */
* The row's top_k is re-applied (hence `params`): the merged set holds up to world_size * k
* candidates and no later stage narrows it. At k = 1 this matters: greedy rows are staged at
* top_k = 1, and with world_size candidates left sample_pick would draw among them. */
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];
@@ -790,10 +719,8 @@ AVX_KERNEL(sample_merge_topk) {
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. */
/* Unpack the pairs once (libref reads them inside the O(n_cand * n_in) selection). The
* selection sort is libref's, ties to the lower token id. */
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) {
@@ -834,18 +761,17 @@ AVX_KERNEL(sample_merge_topk) {
/* ================================================================== 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.
* Not a sampler, but it also picks tokens: DFlash2's greedy walk over a candidate lattice. A
* block-diffusion drafter proposes all positions of a block in one pass, so it cannot condition
* position l+1 on its pick at l; this walk restores that dependence.
*
* 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. */
* An absent `hp` is a plane of ones (a plain low-rank bigram). The walk is serial in l, so the
* parallel axis is the sequence and the vector work is each candidate's rank-R dot. A predecessor
* or candidate outside the vocabulary contributes nothing. Highest score wins, ties 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;
@@ -865,7 +791,8 @@ AVX_KERNEL(dflash_select) {
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). */
/* Rows come from `cand` ([M * steps, K]); the `M` parameter 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);
@@ -888,7 +815,7 @@ AVX_KERNEL(dflash_select) {
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. */
/* The candidate-independent factor, once per 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;
+108 -140
View File
@@ -1,18 +1,12 @@
/* avx_support.cpp -- the dtype-generic row and the row reductions, compiled once per ISA level.
/* avx_support.cpp -- dtype-generic row conversion and 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.
* Out of line rather than in the header: every kernel calls these with a runtime dtype, so inlining
* would paste the dtype switch into every call site. Out of line, the switch is taken once per row
* and lands in a straight vector loop.
*
* 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.
* Conversion rates per level come from `rad-avx-bench --cvt` (libavx/README.md). The two fp8
* decodes differ (avx_vec.h explains): e4m3 is a branchless bit reconstruction, e5m2 a table
* gather; the scalar level and tail elements use the table for both.
*/
#include "avx_vec.h"
#include "avx_common.h"
@@ -21,18 +15,14 @@ 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 canonical planes a container stores (abi/rad_encoding.h), read as stored: libavx rearranges
* no plane, its relayouts only join whole planes (avx_planes.h). Definition: libref/ref_common.h.
* W4: two nibbles a byte, element 2i in the low nibble, code (n ^ 8) - 8. W2: four codes a byte,
* code (c ^ 2) - 2. MXFP4: two e2m1 nibbles, as avx_common.h: ld_elem decodes them.
*
* 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 };
* W4 unpacks 32 elements from one 128-bit load: AND for the low nibbles, shift for the high, then
* interleave with punpcklbw; MXFP4 takes the same unpack and a register table. W2 stays scalar: no
* plain W2 weight is served. */
static void w4_to_f32(const uint8_t* src, float* dst, int64_t n) {
int64_t i = 0;
@@ -59,28 +49,46 @@ static void w4_to_f32(const uint8_t* src, float* dst, int64_t n) {
#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);
}
for (; i < n; ++i) dst[i] = ld_elem(src, RAD_I4, i);
}
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;
/* MXFP4: the same nibble unpack, then the e2m1 value of each code from a register table. AVX-512
* looks all sixteen up in one vpermps; AVX2's vpermps indexes eight, so it takes the magnitude by
* the low three bits and ors in the sign (bit 3). Code 8 is -0, as ld_elem gives it. */
static void fp4_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);
#if AVX_LEVEL >= 3
const __m512 tab = _mm512_setr_ps(0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f, -0.0f,
-0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f);
#else
const __m256 mag = _mm256_setr_ps(0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f);
auto emit8 = [&](__m128i codes8, float* d) {
const __m256i ix = _mm256_cvtepu8_epi32(codes8);
const __m256 m = _mm256_permutevar8x32_ps(mag, ix);
const __m256i sg = _mm256_slli_epi32(_mm256_and_si256(ix, _mm256_set1_epi32(8)), 28);
_mm256_storeu_ps(d, _mm256_or_ps(m, _mm256_castsi256_ps(sg)));
};
#endif
for (; i + 32 <= n; i += 32) {
const __m128i b = _mm_loadu_si128((const __m128i*)(src + (i >> 1)));
const __m128i lo = _mm_and_si128(b, lomask);
const __m128i hi = _mm_and_si128(_mm_srli_epi16(b, 4), lomask);
const __m128i e0 = _mm_unpacklo_epi8(lo, hi); /* codes 0..15 */
const __m128i e1 = _mm_unpackhi_epi8(lo, hi); /* codes 16..31 */
#if AVX_LEVEL >= 3
_mm512_storeu_ps(dst + i, _mm512_permutexvar_ps(_mm512_cvtepu8_epi32(e0), tab));
_mm512_storeu_ps(dst + i + 16, _mm512_permutexvar_ps(_mm512_cvtepu8_epi32(e1), tab));
#else
emit8(e0, dst + i);
emit8(_mm_srli_si128(e0, 8), dst + i + 8);
emit8(e1, dst + i + 16);
emit8(_mm_srli_si128(e1, 8), dst + i + 24);
#endif
}
#endif
for (; i < n; ++i) dst[i] = ld_elem(src, RAD_FP4E2M1, i);
}
/* ================================================================== the generic row */
@@ -93,11 +101,10 @@ void row_to_f32(uint32_t dt, const void* src, float* dst, int64_t n) {
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;
case RAD_I2: for (int64_t i = 0; i < n; ++i) dst[i] = ld_elem(src, RAD_I2, i); break;
case RAD_FP4E2M1: fp4_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. */
/* Remaining integer and bool dtypes are not hot; use the ABI accessor. */
for (int64_t i = 0; i < n; ++i) dst[i] = rad_load_f32(src, dt, i);
break;
}
@@ -120,19 +127,17 @@ void row_from_f32(uint32_t dt, const float* src, void* dst, int64_t n) {
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. */
/* Scalar gather. vpgatherdd issues one cache line per lane, while scalar loads coalesce in
* the load queue; and strided operands here are only column slices of a fused projection
* (docs/OPS.md on `z`), a few rows per launch. */
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`. */
* Fixed summation trees. The accumulators are written out rather than left to the unroller so the
* summation order is fixed by the source, not the optimiser, and results do not move by an ulp
* between builds. Four accumulators cover the FMA latency on current cores (`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;
@@ -193,75 +198,57 @@ float row_max(const float* x, int64_t n) {
}
/* ================================================================== an operand's row, as f32 */
/* Whether a dense row starting at element `base` can be addressed by a byte pointer. A sub-byte
* dtype starting mid-byte cannot (`byte_at` maps elements 2i and 2i+1 to the same byte), so it
* takes the element path rather than reading the row shifted by a nibble. Real W4 rows start on a
* group boundary. */
static inline bool byte_aligned(const RadTensor* t, int64_t base) {
const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1
: (t->dtype == RAD_I2) ? 3 : 0;
return (base & sub) == 0;
}
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);
}
}
if (st == 1 && byte_aligned(t, base))
return row_f32_in(t->dtype, byte_at(t->data, t->dtype, base), 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;
}
if (st == 1 && byte_aligned(t, base)) {
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.
* One step of an exact selection: the next element in descending value order, ties to the lower
* index (libref's `topk_next`).
*
* 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:
* Eligibility ("not above the last pick, and not the last pick or an equal element before it")
* splits at the previous pick into two value-only tests, which vectorise as compare + blend + max:
*
* 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.
* A second pass finds the index of the maximum and exits at the first match.
*
* `!(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). */
* `!(v > pv)` (the unordered NGT compare) rather than `v <= pv` matches libref, which treats a NaN
* as eligible. One known difference: libref keeps an eligible NaN that it meets first as the
* winner, while the vector max returns the largest non-NaN. No path produces NaN logits (a masked
* logit is -inf, which 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. */
/* Scalar level: libref's single pass. The two-pass form below only pays when the first pass
* is vector work; scalar, it is slower than one pass. */
float best = 0.0f;
int64_t bi = -1;
for (int64_t j = 0; j < n; ++j) {
@@ -276,7 +263,7 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) {
return true;
#else
const float NEG = -INFINITY;
/* The split point: indices at or below `pidx` must also differ from `prev`. */
/* Indices below `split` (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;
@@ -284,7 +271,7 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) {
{
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. */
/* At or below the previous pick: equality excluded. */
for (; i + VF_N <= split; i += VF_N) {
const vf x = vf_loadu(v + i);
#if AVX_LEVEL == 3
@@ -302,7 +289,7 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) {
if (x > prev || x == prev) continue;
if (x > best) best = x;
}
/* Range two: past the previous pick -- equality is allowed. */
/* Past the previous pick: equality allowed. */
for (; i + VF_N <= n; i += VF_N) {
const vf x = vf_loadu(v + i);
#if AVX_LEVEL == 3
@@ -323,25 +310,16 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) {
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.
/* Lowest index holding the maximum (ties to the lower column). Vectorised as well: a scalar
* scan reads n/2 elements on average and would dominate `sample_argmax`.
*
* 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 range below the previous pick must be scanned first, since the lowest index over the
* whole row wins. Scanning the vector range first returns the wrong index when the maximum
* occurs on both sides, which is common at bf16.
*
* 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. */
* That low range needs the extra `x != prev` test and is at most pidx+1 long (0 for an argmax,
* R-1 for the R-th pick), so it stays scalar. Past it, `x == best` implies eligibility, since
* best <= prev. */
for (int64_t j = 0; j < split; ++j) {
const float x = v[j];
if (x != best || x == prev) continue;
@@ -374,28 +352,18 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) {
/* ================================================================== 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.
* Measured here, with the kernels' per-level flags, because rad-avx-bench is baseline-compiled
* and could only measure a scalar chain far below what a GEMM at this level faces.
*
* 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.
* Independent FMA accumulators in registers, no memory traffic. The result is what the core
* retires at the clock it holds under sustained vector load (below advertised boost on parts with
* an AVX-512 frequency offset).
*
* 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.
* The accumulator count must fit the register file; a spill inside the loop understates the
* ceiling. 16 accumulators plus 2 constants fit AVX-512's 32 registers but spill on AVX/AVX2's 16.
* 10 covers a 4-5 cycle FMA latency on 2 FMA ports 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. */
* The `volatile` sink keeps the compiler from deleting the loop. */
extern "C" double AVX_FN(avx_peak_fma)(int64_t iters) {
using namespace avx;
#if AVX_LEVEL == 1 || AVX_LEVEL == 2
@@ -412,6 +380,6 @@ extern "C" double AVX_FN(avx_peak_fma)(int64_t iters) {
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. */
/* 2 flops per FMA, NACC FMAs per iteration, VF_N lanes each. */
return 2.0 * (double)iters * (double)NACC * (double)VF_N;
}
+3 -7
View File
@@ -1,12 +1,8 @@
/* 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.
* Members, initialisers and declarations all expand from AVX_OP_LIST (avx_isa.h), so their order
* cannot drift (a swapped entry would run the wrong op silently). An op added to the list without
* an implementation at some level is a link error naming the symbol and the level.
*/
#include "avx_vec.h"
#include "avx_isa.h"
+142 -261
View File
@@ -1,40 +1,24 @@
/* avx_vec.h -- the vector abstraction every kernel in this plugin is written against, and the
* dtype conversions that feed it.
/* avx_vec.h -- the vector abstraction every kernel 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.
* Compiled four times, once per ISA level, with AVX_LEVEL defined on the command line and matching
* -m flags. The level is a compile-time constant here, so `vf` is one concrete type and each
* operation is one instruction or a short fixed sequence. The runtime choice is made once, in
* avx_dispatch.cpp, between tables of compiled functions.
*
* ============================== WHY AN ABSTRACTION AND NOT FOUR COPIES ==============================
* One source per kernel instead of four copies: the AVX-512 path is the same algorithm as the
* scalar path, and the checker only has to prove the arithmetic agrees. The abstraction cannot
* express what differs in kind between levels (AVX-512 write masks, 32 registers,
* compress/expand), so where that matters a kernel has an `#if AVX_LEVEL >= 3` block with a
* comment (e.g. the GEMM microkernel's register blocking, top-k's compress).
*
* 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.
* Everything computes in f32, as libref does (f32 accumulation, IEEE RTNE narrowing;
* libref/ref_common.h). A whole row is converted to f32 scratch once, computed, and converted
* back, instead of libref's per-element dtype switch, which blocks vectorisation.
*
* 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).
* Unlike libref, this plugin reassociates reductions and uses FMA, so avx_check.cpp uses the kbench
* tolerances rather than zero. The narrowing conversions are bit-exact, since they define the
* stored result.
*/
#ifndef RAD_AVX_VEC_H
#define RAD_AVX_VEC_H
@@ -76,19 +60,15 @@
/* 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. */
/* Signature of every kernel. A host kernel ignores `stream`, but every entry point is
* (const RadArgs*, RadStream) in every domain (libr4d/r4d_plugin.h). */
#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. */
/* One inline namespace per level, so kernels write `avx::vf` without naming the level. Without it
* the four objects would define the same `avx::row_to_f32` symbol and the linker would silently
* pick one (e.g. the AVX-512 one) for all four tables. */
inline namespace AVX_SUFFIX {
/* ================================================================== the vector type */
@@ -131,9 +111,8 @@ 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. */
/* AVX has no FMA (it arrived with Haswell). Two roundings, which is closer to libref than AVX2's
* fused form. */
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); }
@@ -141,8 +120,8 @@ 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. */
/* Fixed order (cross-lane, then within 128 bits) so the result does not depend on the
* compiler's choice of tree. */
__m128 lo = _mm256_castps256_ps128(a);
__m128 hi = _mm256_extractf128_ps(a, 1);
__m128 s = _mm_add_ps(lo, hi);
@@ -181,47 +160,15 @@ 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.
* Bit-exact. rad_plugin.h defines f32->bf16 as RTNE with ties to the even surviving bit, NaN
* forced quiet, and overflow carrying into the bf16 infinity. The vector forms below are the same
* integer arithmetic lane for lane; avx_check.cpp checks `cast` over every dtype pair against
* libref at 1e-6, i.e. exactly.
*
* 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.
* Not `_mm512_cvtneps_pbh`: AVX512-BF16 (e.g. Zen 5) also rounds RTNE, but its NaN handling is the
* hardware's, not the ABI's.
*/
static inline void cvt_bf16_to_f32(const uint16_t* src, float* dst, int64_t n) {
int64_t i = 0;
@@ -238,9 +185,8 @@ static inline void cvt_bf16_to_f32(const uint16_t* src, float* dst, int64_t n) {
_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. */
/* AVX has no 256-bit integer ALU: shift in two 128-bit halves and join with vinsertf128, a
* float-domain instruction. Every integer helper at this level has this shape. */
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);
@@ -254,8 +200,8 @@ static inline void cvt_bf16_to_f32(const uint16_t* src, float* dst, int64_t n) {
}
#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. */
/* RTNE core on f32 bit patterns, leaving the 16-bit result in the low half of each lane. Same
* arithmetic at all three vector levels; only the pack differs. */
#if AVX_LEVEL == 3
static inline __m512i bf16_round_bits(__m512 f) {
__m512i u = _mm512_castps_si512(f);
@@ -303,7 +249,7 @@ static inline void cvt_f32_to_bf16(const float* src, uint16_t* dst, int64_t n) {
__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. */
/* Every lane is <= 0xffff, so packus does not saturate. */
_mm_storeu_si128((__m128i*)(dst + i), _mm_packus_epi32(lo, hi));
}
#elif AVX_LEVEL == 1
@@ -317,11 +263,9 @@ static inline void cvt_f32_to_bf16(const float* src, uint16_t* dst, int64_t n) {
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. */
/* f16 is hardware (F16C) from the AVX2 level up and the ABI's software convert below. F16C is a
* separate CPUID bit that arrived a generation after AVX, so the `avx` level cannot assume it.
* F16C rounds RTNE, as rad_f32_to_f16 does, so the two agree bit for bit (`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
@@ -348,67 +292,38 @@ static inline void cvt_f32_to_f16(const float* src, uint16_t* dst, int64_t n) {
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.
/* ---- fp8. Decode: a 256-entry table at the scalar level and for tails, built at load from the
* ABI's converters (avx_dispatch.cpp: fp8_tables_init); e4m3 is a bit reconstruction on the vector
* levels (see cvt_fp8e4m3_to_f32), e5m2 a table gather.
*
* 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. */
* Encode: the bit-exact algorithm has three branches (subnormal, normal, saturate). Only the normal
* case, |x| in [2^-6, 448), which covers a normalised activation, is vectorised; a mask of the
* other elements drives a scalar fixup through the ABI's converter. */
} /* The tables have C linkage at global scope: defined once in the baseline avx_dispatch.cpp and
read by all four levels, so they must stay outside the per-level inline namespace. */
}
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. */
/* Not const: rad_plugin_open fills them at load. A const declaration against the non-const
definition would still link (C linkage does not mangle the type), unreported. */
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.
/* e4m3 decode by bit reconstruction rather than a vpgatherdd table lookup. A gather issues one L1
* access per lane even for a 1 KiB table, and `rad-avx-bench --cvt` shows it no faster than the
* scalar lookup; the reconstruction is about 2.5x faster at AVX2 and 3.3x at AVX-512.
*
* 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
* u = (b & 0x7f) << 20 + 120 << 23 e into the f32 exponent field (bias 7 -> 127), m into
* the top three mantissa bits, in one add
* e == 0 fp8 subnormal: (f - 2^-7) * 2 removes the implicit 1
* and rescales, exactly
* mag == 0x7f 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. */
* The table remains for the scalar level and tails. The checker compares all 256 input bytes,
* NaN and subnormals included. */
static inline void cvt_fp8e4m3_to_f32(const uint8_t* src, float* dst, int64_t n) {
int64_t i = 0;
#if AVX_LEVEL == 3
@@ -470,15 +385,12 @@ static inline void cvt_fp8e5m2_to_f32(const uint8_t* src, float* dst, int64_t n)
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.
/* q = ((e+7) << 3) | rtne(mantissa >> 20), valid for finite 2^-6 <= |x| < 448; anything
* else takes the scalar fixup.
*
* 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. */
* The lower bound must be exactly 2^-6, e4m3's smallest normal. Below it the format is
* subnormal and needs a variable renormalising shift; a lower bound would send subnormals
* through this path with an exponent field <= 0, wrong by orders of magnitude. */
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) {
@@ -488,31 +400,23 @@ static inline void cvt_f32_to_fp8e4m3(const float* src, uint8_t* dst, int64_t n)
__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. */
/* RTNE on the 20 dropped bits: add half, plus one when the surviving bit is odd (bf16's
* tie rule). A mantissa carry propagates into the exponent in the same add. */
__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. */
/* A carry can push e past 15, and (e, m) = (15, 7) is the NaN encoding. Neither occurs
* for inputs below 448, but such lanes are sent to the saturating fixup rather than risk
* a silent NaN. */
__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. */
/* All lanes fast (the normal case for activations): one narrowing store. Without this
* exit, the per-lane fixup loop below would run on every vector and dominate the op. */
if (fast == (__mmask16)0xffff) {
_mm_storeu_si128((__m128i*)(dst + i), _mm512_cvtepi32_epi8(q));
continue;
@@ -523,21 +427,17 @@ static inline void cvt_f32_to_fp8e4m3(const float* src, uint8_t* dst, int64_t n)
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. */
/* The same arithmetic at 256 bits (the scalar converter is an order of magnitude slower).
* The mask is a movemask instead of a k-register; the all-fast exit narrows eight lanes 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. */
/* AVX2 has only signed cmpgt: `mag >= c_lo` is `!(c_lo > mag)`, `mag < c_hi` is
* `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);
@@ -572,15 +472,13 @@ 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.
/* ---- int8. `_mm*_cvtps_epi32` rounds under MXCSR (round-to-nearest-even by default), the same
* rule as libref's `std::nearbyintf`.
*
* 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. */
* The clamp is applied in float before conversion. The saturating packs are not enough: +inf and
* values beyond int32 convert to 0x80000000 ("integer indefinite"), which packs to -128.
* Clamp-then-round matches libref's round-then-clamp for every input, including .5 ties at the
* ends, so `quant_act` holds at 1e-6. NaN stores 0, as in the scalar tail. */
#if AVX_LEVEL == 3
static inline __m512 i8_range_ps(__m512 x) {
const __mmask16 ord = _mm512_cmp_ps_mask(x, x, _CMP_ORD_Q);
@@ -619,13 +517,9 @@ static inline void cvt_f32_to_i8(const float* src, int8_t* dst, int64_t n) {
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. */
/* Fused scale + int8 encode for the quant_act_i8 family: src * inv in a register feeds the same
* clamp/cvtps/packs sequence, so the bytes match scale-then-encode without an f32 round trip
* through memory. Not done for fp8: folding the scale into its longer integer chain is slower. */
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
@@ -666,27 +560,18 @@ static inline void cvt_i8_to_f32(const int8_t* src, float* dst, int64_t n) {
/* ================================================================== 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.
* One dtype switch per row instead of libref's per-element ld_dt(); for memory-bound ops this
* accounts for most of the speedup. The f32 case can be skipped entirely (row_f32_in).
*
* 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). */
* The packed weight codes W4 / W2 / MXFP4 decode here too (for `dequant` and the quantised GEMMs),
* as raw codes: the caller applies the group scale (the same split as libref/ref_common.h). */
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. */
/* Element i at src[i * stride]. Separate so the contiguous path carries no stride multiply. */
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. */
/* Returns `src` itself for RAD_F32, otherwise `scratch` filled with the converted row. */
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);
@@ -695,30 +580,23 @@ static inline const float* row_f32_in(uint32_t dt, const void* src, float* scrat
/* ================================================================== 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.
* exp and sigmoid. Softmax, gates and attention rows all go through these, and a per-element libm
* expf would dominate those ops.
*
* 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.
* Minimax degree 5 on [-ln2/2, ln2/2] after range reduction, ~0.6 ulp. That fits softmax's 1e-6
* because normalisation cancels the relative error common to all terms.
*
* 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. */
* Hand-written because SVML's _mm512_exp_ps needs Intel's runtime, and GCC's libmvec only
* vectorises expf where it can prove the call safe, which fails in kernels that mix integer work. */
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. */
/* Clamp first: outside this range the integer exponent construction overflows. The top
* saturates, which every consumer here prefers to an infinity. Below lo (under the smallest
* normal float) the result is set to zero, and NaN is passed through, after the polynomial;
* the clamp alone would turn e^-inf into e^lo and lose a NaN, so a fully masked softmax row
* would give 1/n instead of libref's NaN. */
const vf hi = vf_set1(88.3762626647949f), lo = vf_set1(-87.3365447504f);
const vf x0 = x;
x = vf_min(vf_max(x, lo), hi);
@@ -733,8 +611,7 @@ static inline vf vf_exp(vf x) {
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. */
/* exp(r) on [-ln2/2, ln2/2], Horner form. */
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));
@@ -768,22 +645,18 @@ static inline vf vf_exp(vf x) {
}
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. */
/* 1 / (1 + e^-x), as libref computes it. The tanh form differs in the last ulp, which
* `hc_read`'s chained sigmoid gates accumulate. */
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. */
/* Cheap silu, only for consumers whose output is bf16: a Taylor-4 exp (truncation ~6e-5) and a
* raw reciprocal seed (2^-14 avx512, 2^-12 avx2, no Newton step). Worst lane ~3e-4, well inside the
* bf16 tolerance of 6e-3 but not f32's 1e-5, so callers key on their output dtype. silu_mul uses
* it; in the frontend-bound conv kernels it makes no measurable difference. */
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);
@@ -796,9 +669,8 @@ static inline vf vf_exp_t4(vf x) {
#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. */
/* Taylor-4: 1 + r(1 + r(1/2 + r(1/6 + r/24))). Same range reduction and exponent build as
* vf_exp. */
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));
@@ -822,36 +694,45 @@ static inline vf vf_silu_fast(vf 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. */
/* No Newton step: d is 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. */
/* ================================================================== exact top-R
* One step of an exact top-R selection over an f32 row: descending by value, ties to the lower
* index (libr4d's rule; a router that broke ties differently would pick a different expert).
* `pv`/`pi` carry the previous pick; seed them with +infinity and -1. Returns false when nothing
* is left. Shared by row_topk, router_topk and sample_topk. */
bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi);
/* ================================================================== an operand's row, as f32
* `in_row` returns `n` floats holding elements (base + i * laststride) of the operand: `t->data`
* itself when it is dense f32, otherwise `scr` filled. `out_row` is the inverse. Every op must
* accept strided views (libref/ref_ops.h), and this is the one place the dense/strided split is
* made. */
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);
/* A dot product with four accumulators to cover FMA latency, combined (a0 + a1) + (a2 + a3) before
* the scalar tail: a fixed summation tree. Inline, since the attention and GEMM edges call it per
* element. */
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;
}
/* Row reductions with a fixed summation tree, independent of compiler unrolling. */
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);