Files
leleka/crates/cpu-sys/src/simd.rs
T
Pavlo RatushnyiandClaude Opus 5.5 87637c2b0b perf: multi-activation kernels make the CPU small-batch pass cheaper, bit-identical (STRA-220)
Profiling the speculative verification pass (batch_cost, position 900) showed its extra cost is compute in the
int8 weight products, not expert bytes: distinct experts per layer rise only from 4 to 9.5 at 9 tokens, while the
Q8_0 projections, whose weights every token shares, cost 3.6-4x a single step. Each (row, token) dot redid the
MXFP4 decode and scale work.

cpu-sys gains multi-activation kernels (portable, AVX2, AVX-VNNI) for MXFP4 and Q8_0 rows: the row is decoded once
per 64-block segment and up to 16 activations run over it with exactly the one-token kernel's accumulators and
final reduction, so every output is bit for bit the one-token kernel's (tests/multi.rs: every level, 1-16
activations, 13 row lengths). run_region uses them for jobs with two or more activations (speculative batches and
prefill chunks); one-token decode keeps its kernel. A new synthetic test checks a 20-token batch at every level
against feeding tokens one at a time. Model::set_multi_activation(false) restores the per-token path for paired
measurements; Profile counts the expert sets read.

batch_cost gains a per-size phase breakdown and an `ab` mode that runs every pass without and with the new kernels
back to back and checks the logits are identical. Paired, 9 rounds, real model: identical logits in all 90 paired
passes; time ratio with/without 1.01 (1 token), 0.98, 0.92, 0.90, 0.83, 0.81, 0.77, 0.79, 0.76 (2..9 tokens).
MEASURED_COST becomes 0.737 + 0.421 n (was 0.30 + 0.631 n). ab_speculation (3 pairs, outputs identical in all 24
runs) gave 1.34 / 1.04 / 0.97 / 0.94, within the pair-to-pair spread of the run before the change; replaying the
outputs through the drafter predicts 1.59 / 1.15 / 1.00 / 0.99, so the serving loop loses time the pass-cost model
does not see. Prefill also uses the kernels (bit-identical); its speed was not measured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:07:38 +02:00

1823 lines
70 KiB
Rust

//! Rust implementations of the CPU kernels, written with `std::arch` intrinsics.
//!
//! They mirror the C kernels in `csrc/` operation for operation (same accumulation structure, same
//! horizontal sums, same rounding), so results are bit-identical to them; a differential test checks
//! that. The portable functions are safe Rust. The x86-64 functions are `unsafe` only because the
//! caller must have verified the CPU features they are compiled for; the safe wrappers in the parent
//! module do that, and also check all slice lengths, so no function here re-checks them.
//!
//! Block formats follow ggml (MIT, llama.cpp commit 3cf03257f219afbe7334045ff7c6a06ac68c627d):
//! MXFP4 block = `e` scale byte + 16 bytes of nibbles (17 bytes), Q8_0 block = half scale + 32 int8
//! (34 bytes). The int8 and int4 dot products are adapted from Colibri `c/idot.h` (Apache-2.0).
// The portable reference loops walk blocks with `chunks_exact` on purpose: they mirror the C reference
// one for one, and the lengths are validated by the safe wrappers.
#![allow(clippy::chunks_exact_to_as_chunks)]
/// ggml's MXFP4 value table (twice the E2M1 value; the scale is halved to compensate).
pub const KVALUES_MXFP4: [i8; 16] = [0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12];
pub const MXFP4_BYTES: usize = 17;
pub const Q8_0_BYTES: usize = 34;
// ------------------------------------------------------------------ portable helpers ----------
/// `2^(e - 128)`: the E8M0 scale times one half, as ggml uses it with the doubled value table.
pub fn e8m0_half(e: u8) -> f32 {
let bits = if e < 2 {
0x0020_0000u32 << e
} else {
(u32::from(e) - 1) << 23
};
f32::from_bits(bits)
}
/// IEEE binary16 to binary32 for every bit pattern.
pub fn f16_to_f32(h: u16) -> f32 {
let sign = u32::from(h & 0x8000) << 16;
let mut exp = u32::from((h >> 10) & 0x1F);
let mut man = u32::from(h & 0x3FF);
let bits = if exp == 0 {
if man == 0 {
sign
} else {
exp = 113; // 127 - 14
while man & 0x400 == 0 {
man <<= 1;
exp -= 1;
}
man &= 0x3FF;
sign | (exp << 23) | (man << 13)
}
} else if exp == 31 {
sign | 0x7F80_0000 | (man << 13)
} else {
sign | ((exp + 112) << 23) | (man << 13)
};
f32::from_bits(bits)
}
/// IEEE binary32 to binary16, round to nearest even, overflow to infinity.
pub fn f32_to_f16(f: f32) -> u16 {
let magic = f32::from_bits(((127 - 15) + (23 - 10) + 1) << 23);
let mut u = f.to_bits();
let sign = u & 0x8000_0000;
u ^= sign;
let o: u16 = if u >= ((127 + 16) << 23) {
if u > (255 << 23) { 0x7E00 } else { 0x7C00 }
} else if u < (113 << 23) {
let r = f32::from_bits(u) + magic;
(r.to_bits() - magic.to_bits()) as u16
} else {
let odd = (u >> 13) & 1;
u = u.wrapping_add((15u32.wrapping_sub(127) << 23).wrapping_add(0xFFF));
u += odd;
(u >> 13) as u16
};
o | (sign >> 16) as u16
}
fn load_u16(b: &[u8]) -> u16 {
u16::from_le_bytes([b[0], b[1]])
}
// ------------------------------------------------------------------ portable kernels ----------
/// Exact `sum(w[i] * x[i])`.
pub fn dot_i8i8_scalar(w: &[i8], x: &[i8]) -> i32 {
w.iter()
.zip(x)
.map(|(a, b)| i32::from(*a) * i32::from(*b))
.sum()
}
/// Packed int4 weights (`value = nibble - 8`, element `2k` in the low nibble) times int8.
pub fn dot_i4i8_scalar(w4: &[u8], x: &[i8]) -> i32 {
dot_i4i8_tail(w4, x, 0)
}
fn mxfp4_block_isum(xb: &[u8], q8: &[u8]) -> i32 {
let mut sum = 0i32;
for j in 0..16 {
let b = xb[1 + j];
sum += i32::from(KVALUES_MXFP4[usize::from(b & 0xF)]) * i32::from(q8[j] as i8)
+ i32::from(KVALUES_MXFP4[usize::from(b >> 4)]) * i32::from(q8[j + 16] as i8);
}
sum
}
/// MXFP4 weights times Q8_0 activations (ggml layouts), blocks summed in order in float.
pub fn dot_mxfp4_q8_0_scalar(x: &[u8], y: &[u8]) -> f32 {
let mut sum = 0.0f32;
for (xb, yb) in x.chunks_exact(MXFP4_BYTES).zip(y.chunks_exact(Q8_0_BYTES)) {
let d = f16_to_f32(load_u16(yb)) * e8m0_half(xb[0]);
sum += d * mxfp4_block_isum(xb, &yb[2..]) as f32;
}
sum
}
/// The exact integer sum of each MXFP4 x Q8_0 block.
pub fn mxfp4_q8_0_isums_scalar(x: &[u8], y: &[u8], out: &mut [i32]) {
for ((xb, yb), o) in x
.chunks_exact(MXFP4_BYTES)
.zip(y.chunks_exact(Q8_0_BYTES))
.zip(out)
{
*o = mxfp4_block_isum(xb, &yb[2..]);
}
}
/// MXFP4 weights times an activation in the "q8r" layout (f32 scales, contiguous int8 quants).
pub fn dot_mxfp4_q8r_scalar(x: &[u8], ys: &[f32], yq: &[i8]) -> f32 {
let mut sum = 0.0f32;
for (ib, xb) in x.chunks_exact(MXFP4_BYTES).enumerate() {
let q8 = &yq[ib * 32..ib * 32 + 32];
let mut isum = 0i32;
for j in 0..16 {
let b = xb[1 + j];
isum += i32::from(KVALUES_MXFP4[usize::from(b & 0xF)]) * i32::from(q8[j])
+ i32::from(KVALUES_MXFP4[usize::from(b >> 4)]) * i32::from(q8[j + 16]);
}
sum += (ys[ib] * e8m0_half(xb[0])) * isum as f32;
}
sum
}
/// Q8_0 weights times an activation in the "q8r" layout.
pub fn dot_q8_q8r_scalar(x: &[u8], ys: &[f32], yq: &[i8]) -> f32 {
let mut sum = 0.0f32;
for (ib, xb) in x.chunks_exact(Q8_0_BYTES).enumerate() {
let isum: i32 = xb[2..]
.iter()
.zip(&yq[ib * 32..ib * 32 + 32])
.map(|(w, a)| i32::from(*w as i8) * i32::from(*a))
.sum();
sum += (f16_to_f32(load_u16(xb)) * ys[ib]) * isum as f32;
}
sum
}
// ------------------------------------------------------------------- attention kernels ----------
//
// Single-precision helpers for attention over a key/value cache laid out with a fixed stride between
// positions (`stride` floats from one position to the next, one head's `hd` floats used per position).
// They work on a group of `heads` query heads that share the same keys and values (grouped-query
// attention), so each key and value row is read once for the whole group.
/// Positions handled per block: the rows of a block stay in the L1 cache while every head uses them.
pub const ATTN_BLOCK: usize = 16;
/// `out[g * n + i] = scale * dot(q[g * hd ..][..hd], keys[i * stride ..][..hd])` for each head `g` and
/// position `i < n`, with `hd = q.len() / heads`.
pub fn attn_scores_scalar(
q: &[f32],
heads: usize,
keys: &[f32],
stride: usize,
n: usize,
scale: f32,
out: &mut [f32],
) {
let hd = q.len() / heads;
for g in 0..heads {
let query = &q[g * hd..(g + 1) * hd];
for i in 0..n {
let k = &keys[i * stride..i * stride + hd];
let mut dot = 0.0f32;
for (a, b) in query.iter().zip(k) {
dot += a * b;
}
out[g * n + i] = dot * scale;
}
}
}
/// `out[g * hd ..][..hd] = sum_i weights[g * n + i] * values[i * stride ..][..hd]`, with
/// `hd = out.len() / heads`.
pub fn attn_weighted_sum_scalar(
weights: &[f32],
heads: usize,
n: usize,
values: &[f32],
stride: usize,
out: &mut [f32],
) {
let hd = out.len() / heads;
out.fill(0.0);
for g in 0..heads {
for i in 0..n {
let w = weights[g * n + i];
for (o, v) in out[g * hd..(g + 1) * hd]
.iter_mut()
.zip(&values[i * stride..i * stride + hd])
{
*o += w * v;
}
}
}
}
/// As [`attn_scores_scalar`] with the keys stored as IEEE half floats (bit patterns).
pub fn attn_scores_f16_scalar(
q: &[f32],
heads: usize,
keys: &[u16],
stride: usize,
n: usize,
scale: f32,
out: &mut [f32],
) {
let hd = q.len() / heads;
for g in 0..heads {
let query = &q[g * hd..(g + 1) * hd];
for i in 0..n {
let k = &keys[i * stride..i * stride + hd];
let mut dot = 0.0f32;
for (a, b) in query.iter().zip(k) {
dot += a * f16_to_f32(*b);
}
out[g * n + i] = dot * scale;
}
}
}
/// As [`attn_weighted_sum_scalar`] with the values stored as IEEE half floats.
pub fn attn_weighted_sum_f16_scalar(
weights: &[f32],
heads: usize,
n: usize,
values: &[u16],
stride: usize,
out: &mut [f32],
) {
let hd = out.len() / heads;
out.fill(0.0);
for g in 0..heads {
for i in 0..n {
let w = weights[g * n + i];
for (o, v) in out[g * hd..(g + 1) * hd]
.iter_mut()
.zip(&values[i * stride..i * stride + hd])
{
*o += w * f16_to_f32(*v);
}
}
}
}
/// The gpt-oss expert activation ("swiglu-oai" in ggml): the gate is clamped from above, the linear
/// part to `[-limit, limit]`, and `out = gate * sigmoid(alpha * gate) * (linear + 1)`.
pub fn swiglu_oai_scalar(gate: &[f32], up: &[f32], alpha: f32, limit: f32, out: &mut [f32]) {
for ((o, g), u) in out.iter_mut().zip(gate).zip(up) {
let x = g.min(limit);
let y = u.clamp(-limit, limit);
let sigmoid = 1.0 / (1.0 + (alpha * -x).exp());
*o = x * sigmoid * (1.0 + y);
}
}
/// Converts IEEE half bit patterns to floats, `dst.len() == src.len()`.
pub fn f16_to_f32_slice_scalar(src: &[u16], dst: &mut [f32]) {
for (d, s) in dst.iter_mut().zip(src) {
*d = f16_to_f32(*s);
}
}
/// Converts floats to IEEE half bit patterns (round to nearest even), `dst.len() == src.len()`.
pub fn f32_to_f16_slice_scalar(src: &[f32], dst: &mut [u16]) {
for (d, s) in dst.iter_mut().zip(src) {
*d = f32_to_f16(*s);
}
}
/// Replaces every `x[i]` by `exp(x[i] - max)` and returns the sum of the results.
pub fn exp_shift_sum_scalar(x: &mut [f32], max: f32) -> f32 {
let mut sum = 0.0f32;
for v in x {
*v = (*v - max).exp();
sum += *v;
}
sum
}
/// Bias that turns signed weights into unsigned ones for the VNNI tile kernels (`w + 128`).
pub const WEIGHT_BIAS: i32 = 128;
/// One quantized activation row for the tile kernels, in the layouts they read. All views describe the
/// same `blocks` 32-element blocks; build them with [`prepare_act`].
#[derive(Clone, Copy, Debug)]
pub struct ActRef<'a> {
/// One f32 scale per block.
pub scales: &'a [f32],
/// Each scale repeated 8 times (`blocks * 8` values), so a kernel can load it as a vector.
pub scales_bcast: &'a [f32],
/// The int8 quants, `blocks * 32` values.
pub quants: &'a [i8],
/// `blocks * 8` values: lane 0 of each group of 8 holds `-WEIGHT_BIAS * sum(quants of the block)`,
/// the others zero. Added to the first accumulation it removes the bias of the unsigned weights.
pub corr: &'a [i32],
}
/// Fill `bcast` and `corr` for an activation with the given `scales` and `quants`.
pub fn prepare_act(scales: &[f32], quants: &[i8], bcast: &mut [f32], corr: &mut [i32]) {
for (ib, block) in quants.chunks_exact(32).enumerate() {
bcast[ib * 8..ib * 8 + 8].fill(scales[ib]);
let sum: i32 = block.iter().map(|q| i32::from(*q)).sum();
corr[ib * 8..ib * 8 + 8].fill(0);
corr[ib * 8] = -WEIGHT_BIAS * sum;
}
}
/// A tile of MXFP4 rows by activations, portable: `out[r * acts.len() + a]`.
pub fn mxfp4_q8r_tile_scalar(x: &[&[u8]], acts: &[ActRef], out: &mut [f32]) {
for (r, row) in x.iter().enumerate() {
for (a, act) in acts.iter().enumerate() {
out[r * acts.len() + a] = dot_mxfp4_q8r_scalar(row, act.scales, act.quants);
}
}
}
/// A tile of Q8_0 rows by activations, portable: `out[r * acts.len() + a]`.
pub fn q8_q8r_tile_scalar(x: &[&[u8]], acts: &[ActRef], out: &mut [f32]) {
for (r, row) in x.iter().enumerate() {
for (a, act) in acts.iter().enumerate() {
out[r * acts.len() + a] = dot_q8_q8r_scalar(row, act.scales, act.quants);
}
}
}
/// One activation in the "q8r" layout for the multi-activation kernels: one f32 scale per block and the
/// int8 quants, `scales.len() * 32` of them.
#[derive(Clone, Copy, Debug)]
pub struct Q8rRef<'a> {
pub scales: &'a [f32],
pub quants: &'a [i8],
}
/// Most activations one multi-activation kernel call takes.
pub const MULTI_MAX: usize = 16;
/// One MXFP4 row against several activations, portable: `out[a]` is [`dot_mxfp4_q8r_scalar`] of `acts[a]`.
pub fn dot_mxfp4_q8r_multi_scalar(x: &[u8], acts: &[Q8rRef], out: &mut [f32]) {
for (act, o) in acts.iter().zip(out) {
*o = dot_mxfp4_q8r_scalar(x, act.scales, act.quants);
}
}
/// One Q8_0 row against several activations, portable: `out[a]` is [`dot_q8_q8r_scalar`] of `acts[a]`,
/// which equals [`dot_q8_0_q8_0_scalar`] of the activation's Q8_0 blocks bit for bit.
pub fn dot_q8_0_q8r_multi_scalar(x: &[u8], acts: &[Q8rRef], out: &mut [f32]) {
for (act, o) in acts.iter().zip(out) {
*o = dot_q8_q8r_scalar(x, act.scales, act.quants);
}
}
/// Quantize floats (a multiple of 32) to Q8_0 blocks: scale = amax / 127 stored as a half, quants
/// rounded to nearest even and clamped to `[-127, 127]`.
pub fn quantize_q8_0_scalar(x: &[f32], out: &mut [u8]) {
for (xb, yb) in x.chunks_exact(32).zip(out.chunks_exact_mut(Q8_0_BYTES)) {
let mut amax = 0.0f32;
for v in xb {
let a = v.abs();
if a > amax {
amax = a;
}
}
let d = amax / 127.0;
let id = if d != 0.0 { 1.0 / d } else { 0.0 };
yb[..2].copy_from_slice(&f32_to_f16(d).to_le_bytes());
for (j, v) in xb.iter().enumerate() {
let q = (v * id).round_ties_even().clamp(-127.0, 127.0);
yb[2 + j] = (q as i8) as u8;
}
}
}
fn q8_block_isum(a: &[u8], b: &[u8]) -> i32 {
a[2..]
.iter()
.zip(&b[2..])
.map(|(p, q)| i32::from(*p as i8) * i32::from(*q as i8))
.sum()
}
/// Q8_0 weights times Q8_0 activations.
pub fn dot_q8_0_q8_0_scalar(x: &[u8], y: &[u8]) -> f32 {
let mut sum = 0.0f32;
for (xb, yb) in x.chunks_exact(Q8_0_BYTES).zip(y.chunks_exact(Q8_0_BYTES)) {
let d = f16_to_f32(load_u16(xb)) * f16_to_f32(load_u16(yb));
sum += d * q8_block_isum(xb, yb) as f32;
}
sum
}
/// The exact integer sum of each Q8_0 x Q8_0 block.
pub fn q8_0_q8_0_isums_scalar(x: &[u8], y: &[u8], out: &mut [i32]) {
for ((xb, yb), o) in x
.chunks_exact(Q8_0_BYTES)
.zip(y.chunks_exact(Q8_0_BYTES))
.zip(out)
{
*o = q8_block_isum(xb, yb);
}
}
// --------------------------------------------------------------------------- x86-64 ----------
#[cfg(target_arch = "x86_64")]
pub mod x86 {
//! AVX2 (+FMA +F16C) and AVX-VNNI kernels. Every function is `unsafe`: the caller must have
//! verified the CPU features named in its `target_feature` attribute and that all slices have the
//! lengths the safe wrappers checked.
//!
//! # Safety (applies to every function below)
//!
//! The CPU must support the features in the function's `target_feature` attribute, the operand
//! slices must have the lengths the safe wrappers in the crate root check (block counts derived
//! from the first slice, the others at least as long), and activations must be in `[-127, 127]`.
// The bodies are intrinsics from top to bottom; wrapping each in its own `unsafe` block would
// only add noise, so the function-level `unsafe` covers them (as the C kernels did). The safety
// contract is stated once in the module documentation above.
// `excessive_precision`: the exp polynomial keeps the published Cephes coefficients digit for digit
// so they can be checked against the source; the compiler rounds them to f32.
#![allow(
unsafe_op_in_unsafe_fn,
clippy::missing_safety_doc,
clippy::excessive_precision
)]
use super::{KVALUES_MXFP4, MXFP4_BYTES, Q8_0_BYTES, e8m0_half};
use std::arch::x86_64::*;
#[inline]
#[target_feature(enable = "avx2")]
unsafe fn hsum_epi32(v: __m256i) -> i32 {
let lo = _mm256_castsi256_si128(v);
let hi = _mm256_extracti128_si256::<1>(v);
let mut s = _mm_add_epi32(lo, hi);
s = _mm_hadd_epi32(s, s);
s = _mm_hadd_epi32(s, s);
_mm_cvtsi128_si32(s)
}
#[inline]
#[target_feature(enable = "avx")]
unsafe fn hsum_ps(v: __m256) -> f32 {
let lo = _mm256_castps256_ps128(v);
let hi = _mm256_extractf128_ps::<1>(v);
let mut s = _mm_add_ps(lo, hi);
let sh = _mm_movehl_ps(s, s);
s = _mm_add_ps(s, sh);
let sh = _mm_shuffle_ps::<1>(s, s);
s = _mm_add_ss(s, sh);
_mm_cvtss_f32(s)
}
#[inline]
#[target_feature(enable = "ssse3")]
unsafe fn hsum128_epi32(v: __m128i) -> i32 {
let mut s = _mm_hadd_epi32(v, v);
s = _mm_hadd_epi32(s, s);
_mm_cvtsi128_si32(s)
}
#[inline]
#[target_feature(enable = "f16c")]
unsafe fn half_to_f32(p: *const u8) -> f32 {
let h = u16::from_le_bytes([*p, *p.add(1)]);
_mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128(i32::from(h))))
}
#[inline]
#[target_feature(enable = "f16c")]
unsafe fn cvt_f32_f16(f: f32) -> u16 {
_mm_extract_epi16::<0>(_mm_cvtps_ph::<{ _MM_FROUND_TO_NEAREST_INT }>(_mm_set_ss(f))) as u16
}
// ---- int8 and int4 dot products (Colibri idot.h) ----
#[target_feature(enable = "avx2")]
pub unsafe fn dot_i8i8_avx2(w: &[i8], x: &[i8]) -> i32 {
let n = w.len();
let mut i = 0;
let mut acc = _mm256_setzero_si256();
let ones = _mm256_set1_epi16(1);
while i + 32 <= n {
let wv = _mm256_loadu_si256(w.as_ptr().add(i) as *const __m256i);
let xv = _mm256_loadu_si256(x.as_ptr().add(i) as *const __m256i);
let p = _mm256_maddubs_epi16(_mm256_sign_epi8(wv, wv), _mm256_sign_epi8(xv, wv));
acc = _mm256_add_epi32(acc, _mm256_madd_epi16(p, ones));
i += 32;
}
let mut sum = hsum_epi32(acc);
while i < n {
sum += i32::from(w[i]) * i32::from(x[i]);
i += 1;
}
sum
}
#[target_feature(enable = "avx2")]
pub unsafe fn dot_i4i8_avx2(w4: &[u8], x: &[i8]) -> i32 {
let n = x.len();
let mut i = 0;
let m4 = _mm_set1_epi8(0x0F);
let b8 = _mm256_set1_epi8(8);
let ones = _mm256_set1_epi16(1);
let mut acc = _mm256_setzero_si256();
while i + 32 <= n {
let by = _mm_loadu_si128(w4.as_ptr().add(i >> 1) as *const __m128i);
let lo = _mm_and_si128(by, m4);
let hi = _mm_and_si128(_mm_srli_epi16::<4>(by), m4);
let n0 = _mm_unpacklo_epi8(lo, hi);
let n1 = _mm_unpackhi_epi8(lo, hi);
let wv = _mm256_sub_epi8(_mm256_set_m128i(n1, n0), b8);
let xv = _mm256_loadu_si256(x.as_ptr().add(i) as *const __m256i);
let p = _mm256_maddubs_epi16(_mm256_sign_epi8(wv, wv), _mm256_sign_epi8(xv, wv));
acc = _mm256_add_epi32(acc, _mm256_madd_epi16(p, ones));
i += 32;
}
let mut sum = hsum_epi32(acc);
sum += super::dot_i4i8_tail(w4, x, i);
sum
}
#[target_feature(enable = "avx2,avxvnni")]
pub unsafe fn dot_i8i8_avxvnni(w: &[i8], x: &[i8]) -> i32 {
let n = w.len();
let mut i = 0;
let (mut a0, mut a1, mut a2, mut a3) = (
_mm_setzero_si128(),
_mm_setzero_si128(),
_mm_setzero_si128(),
_mm_setzero_si128(),
);
let ld = |p: &[i8], k: usize| _mm_loadu_si128(p.as_ptr().add(k) as *const __m128i);
while i + 64 <= n {
let (w0, x0) = (ld(w, i), ld(x, i));
let (w1, x1) = (ld(w, i + 16), ld(x, i + 16));
let (w2, x2) = (ld(w, i + 32), ld(x, i + 32));
let (w3, x3) = (ld(w, i + 48), ld(x, i + 48));
a0 = _mm_dpbusd_avx_epi32(a0, _mm_abs_epi8(w0), _mm_sign_epi8(x0, w0));
a1 = _mm_dpbusd_avx_epi32(a1, _mm_abs_epi8(w1), _mm_sign_epi8(x1, w1));
a2 = _mm_dpbusd_avx_epi32(a2, _mm_abs_epi8(w2), _mm_sign_epi8(x2, w2));
a3 = _mm_dpbusd_avx_epi32(a3, _mm_abs_epi8(w3), _mm_sign_epi8(x3, w3));
i += 64;
}
let mut acc = _mm_add_epi32(_mm_add_epi32(a0, a1), _mm_add_epi32(a2, a3));
while i + 16 <= n {
let (wv, xv) = (ld(w, i), ld(x, i));
acc = _mm_dpbusd_avx_epi32(acc, _mm_abs_epi8(wv), _mm_sign_epi8(xv, wv));
i += 16;
}
let mut sum = hsum128_epi32(acc);
while i < n {
sum += i32::from(w[i]) * i32::from(x[i]);
i += 1;
}
sum
}
#[target_feature(enable = "avx2,avxvnni")]
pub unsafe fn dot_i4i8_avxvnni(w4: &[u8], x: &[i8]) -> i32 {
let n = x.len();
let mut i = 0;
let m4 = _mm_set1_epi8(0x0F);
let b8 = _mm_set1_epi8(8);
let (mut a0, mut a1, mut a2, mut a3) = (
_mm_setzero_si128(),
_mm_setzero_si128(),
_mm_setzero_si128(),
_mm_setzero_si128(),
);
let ldb = |k: usize| _mm_loadu_si128(w4.as_ptr().add(k) as *const __m128i);
let ldx = |k: usize| _mm_loadu_si128(x.as_ptr().add(k) as *const __m128i);
while i + 64 <= n {
let by0 = ldb(i >> 1);
let by1 = ldb((i >> 1) + 16);
let lo0 = _mm_and_si128(by0, m4);
let hi0 = _mm_and_si128(_mm_srli_epi16::<4>(by0), m4);
let lo1 = _mm_and_si128(by1, m4);
let hi1 = _mm_and_si128(_mm_srli_epi16::<4>(by1), m4);
let w0 = _mm_sub_epi8(_mm_unpacklo_epi8(lo0, hi0), b8);
let w1 = _mm_sub_epi8(_mm_unpackhi_epi8(lo0, hi0), b8);
let w2 = _mm_sub_epi8(_mm_unpacklo_epi8(lo1, hi1), b8);
let w3 = _mm_sub_epi8(_mm_unpackhi_epi8(lo1, hi1), b8);
let (x0, x1, x2, x3) = (ldx(i), ldx(i + 16), ldx(i + 32), ldx(i + 48));
a0 = _mm_dpbusd_avx_epi32(a0, _mm_abs_epi8(w0), _mm_sign_epi8(x0, w0));
a1 = _mm_dpbusd_avx_epi32(a1, _mm_abs_epi8(w1), _mm_sign_epi8(x1, w1));
a2 = _mm_dpbusd_avx_epi32(a2, _mm_abs_epi8(w2), _mm_sign_epi8(x2, w2));
a3 = _mm_dpbusd_avx_epi32(a3, _mm_abs_epi8(w3), _mm_sign_epi8(x3, w3));
i += 64;
}
let mut acc = _mm_add_epi32(_mm_add_epi32(a0, a1), _mm_add_epi32(a2, a3));
while i + 32 <= n {
let by = ldb(i >> 1);
let lo = _mm_and_si128(by, m4);
let hi = _mm_and_si128(_mm_srli_epi16::<4>(by), m4);
let w0 = _mm_sub_epi8(_mm_unpacklo_epi8(lo, hi), b8);
let w1 = _mm_sub_epi8(_mm_unpackhi_epi8(lo, hi), b8);
let (x0, x1) = (ldx(i), ldx(i + 16));
acc = _mm_dpbusd_avx_epi32(acc, _mm_abs_epi8(w0), _mm_sign_epi8(x0, w0));
acc = _mm_dpbusd_avx_epi32(acc, _mm_abs_epi8(w1), _mm_sign_epi8(x1, w1));
i += 32;
}
let mut sum = hsum128_epi32(acc);
sum += super::dot_i4i8_tail(w4, x, i);
sum
}
// ---- MXFP4 x Q8_0, ggml layout ----
#[inline]
#[target_feature(enable = "avx2")]
unsafe fn mx_table() -> __m256i {
let t = _mm_loadu_si128(KVALUES_MXFP4.as_ptr() as *const __m128i);
_mm256_set_m128i(t, t)
}
#[inline]
#[target_feature(enable = "avx2")]
unsafe fn mx_values(x: *const u8, table: __m256i, low: __m128i) -> __m256i {
let bits = _mm_loadu_si128(x.add(1) as *const __m128i);
let lo = _mm_and_si128(bits, low);
let hi = _mm_and_si128(_mm_srli_epi16::<4>(bits), low);
_mm256_shuffle_epi8(table, _mm256_set_m128i(hi, lo))
}
#[inline]
#[target_feature(enable = "avx2")]
unsafe fn block_p32_avx2(q4: __m256i, q8: *const u8, ones: __m256i) -> __m256i {
let q8 = _mm256_loadu_si256(q8 as *const __m256i);
let p16 = _mm256_maddubs_epi16(_mm256_sign_epi8(q4, q4), _mm256_sign_epi8(q8, q4));
_mm256_madd_epi16(p16, ones)
}
#[inline]
#[target_feature(enable = "avx2,avxvnni")]
unsafe fn block_p32_vnni(q4: __m256i, q8: *const u8) -> __m256i {
let q8 = _mm256_loadu_si256(q8 as *const __m256i);
_mm256_dpbusd_avx_epi32(
_mm256_setzero_si256(),
_mm256_sign_epi8(q4, q4),
_mm256_sign_epi8(q8, q4),
)
}
#[target_feature(enable = "avx2,fma,f16c")]
pub unsafe fn dot_mxfp4_q8_0_avx2(x: &[u8], y: &[u8]) -> f32 {
let nb = x.len() / MXFP4_BYTES;
let (table, low, ones) = (mx_table(), _mm_set1_epi8(0x0F), _mm256_set1_epi16(1));
let (mut acc0, mut acc1) = (_mm256_setzero_ps(), _mm256_setzero_ps());
let mut ib = 0;
let (xp, yp) = (x.as_ptr(), y.as_ptr());
while ib + 2 <= nb {
let (x0, y0) = (xp.add(ib * MXFP4_BYTES), yp.add(ib * Q8_0_BYTES));
let (x1, y1) = (x0.add(MXFP4_BYTES), y0.add(Q8_0_BYTES));
let p0 = block_p32_avx2(mx_values(x0, table, low), y0.add(2), ones);
let p1 = block_p32_avx2(mx_values(x1, table, low), y1.add(2), ones);
let s0 = half_to_f32(y0) * e8m0_half(*x0);
let s1 = half_to_f32(y1) * e8m0_half(*x1);
acc0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p0), _mm256_set1_ps(s0), acc0);
acc1 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p1), _mm256_set1_ps(s1), acc1);
ib += 2;
}
while ib < nb {
let (xb, yb) = (xp.add(ib * MXFP4_BYTES), yp.add(ib * Q8_0_BYTES));
let p = block_p32_avx2(mx_values(xb, table, low), yb.add(2), ones);
let s = half_to_f32(yb) * e8m0_half(*xb);
acc0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p), _mm256_set1_ps(s), acc0);
ib += 1;
}
hsum_ps(_mm256_add_ps(acc0, acc1))
}
#[target_feature(enable = "avx2")]
pub unsafe fn mxfp4_q8_0_isums_avx2(x: &[u8], y: &[u8], out: &mut [i32]) {
let (table, low, ones) = (mx_table(), _mm_set1_epi8(0x0F), _mm256_set1_epi16(1));
for (ib, o) in out.iter_mut().enumerate() {
let (xb, yb) = (
x.as_ptr().add(ib * MXFP4_BYTES),
y.as_ptr().add(ib * Q8_0_BYTES),
);
*o = hsum_epi32(block_p32_avx2(mx_values(xb, table, low), yb.add(2), ones));
}
}
#[target_feature(enable = "avx2,fma,f16c,avxvnni")]
pub unsafe fn dot_mxfp4_q8_0_avxvnni(x: &[u8], y: &[u8]) -> f32 {
let nb = x.len() / MXFP4_BYTES;
let (table, low) = (mx_table(), _mm_set1_epi8(0x0F));
let (mut acc0, mut acc1) = (_mm256_setzero_ps(), _mm256_setzero_ps());
let mut ib = 0;
let (xp, yp) = (x.as_ptr(), y.as_ptr());
while ib + 2 <= nb {
let (x0, y0) = (xp.add(ib * MXFP4_BYTES), yp.add(ib * Q8_0_BYTES));
let (x1, y1) = (x0.add(MXFP4_BYTES), y0.add(Q8_0_BYTES));
let p0 = block_p32_vnni(mx_values(x0, table, low), y0.add(2));
let p1 = block_p32_vnni(mx_values(x1, table, low), y1.add(2));
let s0 = half_to_f32(y0) * e8m0_half(*x0);
let s1 = half_to_f32(y1) * e8m0_half(*x1);
acc0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p0), _mm256_set1_ps(s0), acc0);
acc1 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p1), _mm256_set1_ps(s1), acc1);
ib += 2;
}
while ib < nb {
let (xb, yb) = (xp.add(ib * MXFP4_BYTES), yp.add(ib * Q8_0_BYTES));
let p = block_p32_vnni(mx_values(xb, table, low), yb.add(2));
let s = half_to_f32(yb) * e8m0_half(*xb);
acc0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p), _mm256_set1_ps(s), acc0);
ib += 1;
}
hsum_ps(_mm256_add_ps(acc0, acc1))
}
#[target_feature(enable = "avx2,avxvnni")]
pub unsafe fn mxfp4_q8_0_isums_avxvnni(x: &[u8], y: &[u8], out: &mut [i32]) {
let (table, low) = (mx_table(), _mm_set1_epi8(0x0F));
for (ib, o) in out.iter_mut().enumerate() {
let (xb, yb) = (
x.as_ptr().add(ib * MXFP4_BYTES),
y.as_ptr().add(ib * Q8_0_BYTES),
);
*o = hsum_epi32(block_p32_vnni(mx_values(xb, table, low), yb.add(2)));
}
}
// ---- MXFP4 x "q8r" layout: four blocks and four accumulators per iteration ----
/// Two blocks and two accumulators per iteration (the first "q8r" kernel).
#[target_feature(enable = "avx2,fma")]
pub unsafe fn dot_mxfp4_q8r_avx2(x: &[u8], ys: &[f32], yq: &[i8]) -> f32 {
let nb = x.len() / MXFP4_BYTES;
let (table, low, ones) = (mx_table(), _mm_set1_epi8(0x0F), _mm256_set1_epi16(1));
let (mut acc0, mut acc1) = (_mm256_setzero_ps(), _mm256_setzero_ps());
let (xp, qp) = (x.as_ptr(), yq.as_ptr() as *const u8);
let mut ib = 0;
while ib + 2 <= nb {
let (x0, x1) = (xp.add(ib * MXFP4_BYTES), xp.add((ib + 1) * MXFP4_BYTES));
let p0 = block_p32_avx2(mx_values(x0, table, low), qp.add(ib * 32), ones);
let p1 = block_p32_avx2(mx_values(x1, table, low), qp.add(ib * 32 + 32), ones);
acc0 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p0),
_mm256_set1_ps(ys[ib] * e8m0_half(*x0)),
acc0,
);
acc1 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p1),
_mm256_set1_ps(ys[ib + 1] * e8m0_half(*x1)),
acc1,
);
ib += 2;
}
while ib < nb {
let xb = xp.add(ib * MXFP4_BYTES);
let p = block_p32_avx2(mx_values(xb, table, low), qp.add(ib * 32), ones);
acc0 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p),
_mm256_set1_ps(ys[ib] * e8m0_half(*xb)),
acc0,
);
ib += 1;
}
hsum_ps(_mm256_add_ps(acc0, acc1))
}
#[target_feature(enable = "avx2,fma")]
pub unsafe fn dot_mxfp4_q8r4_avx2(x: &[u8], ys: &[f32], yq: &[i8]) -> f32 {
let nb = x.len() / MXFP4_BYTES;
let (table, low, ones) = (mx_table(), _mm_set1_epi8(0x0F), _mm256_set1_epi16(1));
let z = _mm256_setzero_ps();
let (mut a0, mut a1, mut a2, mut a3) = (z, z, z, z);
let (xp, qp) = (x.as_ptr(), yq.as_ptr() as *const u8);
let mut ib = 0;
while ib + 4 <= nb {
let xb = xp.add(ib * MXFP4_BYTES);
let q = qp.add(ib * 32);
let p0 = block_p32_avx2(mx_values(xb, table, low), q, ones);
let p1 = block_p32_avx2(mx_values(xb.add(17), table, low), q.add(32), ones);
let p2 = block_p32_avx2(mx_values(xb.add(34), table, low), q.add(64), ones);
let p3 = block_p32_avx2(mx_values(xb.add(51), table, low), q.add(96), ones);
a0 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p0),
_mm256_set1_ps(ys[ib] * e8m0_half(*xb)),
a0,
);
a1 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p1),
_mm256_set1_ps(ys[ib + 1] * e8m0_half(*xb.add(17))),
a1,
);
a2 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p2),
_mm256_set1_ps(ys[ib + 2] * e8m0_half(*xb.add(34))),
a2,
);
a3 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p3),
_mm256_set1_ps(ys[ib + 3] * e8m0_half(*xb.add(51))),
a3,
);
ib += 4;
}
while ib < nb {
let xb = xp.add(ib * MXFP4_BYTES);
let p = block_p32_avx2(mx_values(xb, table, low), qp.add(ib * 32), ones);
a0 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p),
_mm256_set1_ps(ys[ib] * e8m0_half(*xb)),
a0,
);
ib += 1;
}
hsum_ps(_mm256_add_ps(_mm256_add_ps(a0, a1), _mm256_add_ps(a2, a3)))
}
#[target_feature(enable = "avx2,fma,avxvnni")]
pub unsafe fn dot_mxfp4_q8r4_avxvnni(x: &[u8], ys: &[f32], yq: &[i8]) -> f32 {
let nb = x.len() / MXFP4_BYTES;
let (table, low) = (mx_table(), _mm_set1_epi8(0x0F));
let z = _mm256_setzero_ps();
let (mut a0, mut a1, mut a2, mut a3) = (z, z, z, z);
let (xp, qp) = (x.as_ptr(), yq.as_ptr() as *const u8);
let mut ib = 0;
while ib + 4 <= nb {
let xb = xp.add(ib * MXFP4_BYTES);
let q = qp.add(ib * 32);
let p0 = block_p32_vnni(mx_values(xb, table, low), q);
let p1 = block_p32_vnni(mx_values(xb.add(17), table, low), q.add(32));
let p2 = block_p32_vnni(mx_values(xb.add(34), table, low), q.add(64));
let p3 = block_p32_vnni(mx_values(xb.add(51), table, low), q.add(96));
a0 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p0),
_mm256_set1_ps(ys[ib] * e8m0_half(*xb)),
a0,
);
a1 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p1),
_mm256_set1_ps(ys[ib + 1] * e8m0_half(*xb.add(17))),
a1,
);
a2 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p2),
_mm256_set1_ps(ys[ib + 2] * e8m0_half(*xb.add(34))),
a2,
);
a3 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p3),
_mm256_set1_ps(ys[ib + 3] * e8m0_half(*xb.add(51))),
a3,
);
ib += 4;
}
while ib < nb {
let xb = xp.add(ib * MXFP4_BYTES);
let p = block_p32_vnni(mx_values(xb, table, low), qp.add(ib * 32));
a0 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p),
_mm256_set1_ps(ys[ib] * e8m0_half(*xb)),
a0,
);
ib += 1;
}
hsum_ps(_mm256_add_ps(_mm256_add_ps(a0, a1), _mm256_add_ps(a2, a3)))
}
// ---- Q8_0 ----
#[inline]
#[target_feature(enable = "avx2")]
unsafe fn q8_p32_avx2(a: *const u8, b: *const u8, ones: __m256i) -> __m256i {
let a = _mm256_loadu_si256(a.add(2) as *const __m256i);
let b = _mm256_loadu_si256(b.add(2) as *const __m256i);
let p16 = _mm256_maddubs_epi16(_mm256_sign_epi8(a, a), _mm256_sign_epi8(b, a));
_mm256_madd_epi16(p16, ones)
}
#[inline]
#[target_feature(enable = "avx2,avxvnni")]
unsafe fn q8_p32_vnni(a: *const u8, b: *const u8) -> __m256i {
let a = _mm256_loadu_si256(a.add(2) as *const __m256i);
let b = _mm256_loadu_si256(b.add(2) as *const __m256i);
_mm256_dpbusd_avx_epi32(
_mm256_setzero_si256(),
_mm256_sign_epi8(a, a),
_mm256_sign_epi8(b, a),
)
}
#[target_feature(enable = "avx2,fma,f16c")]
pub unsafe fn dot_q8_0_q8_0_avx2(x: &[u8], y: &[u8]) -> f32 {
let nb = x.len() / Q8_0_BYTES;
let ones = _mm256_set1_epi16(1);
let (mut acc0, mut acc1) = (_mm256_setzero_ps(), _mm256_setzero_ps());
let (xp, yp) = (x.as_ptr(), y.as_ptr());
let mut ib = 0;
while ib + 2 <= nb {
let (x0, y0) = (xp.add(ib * Q8_0_BYTES), yp.add(ib * Q8_0_BYTES));
let (x1, y1) = (x0.add(Q8_0_BYTES), y0.add(Q8_0_BYTES));
let p0 = q8_p32_avx2(x0, y0, ones);
let p1 = q8_p32_avx2(x1, y1, ones);
let s0 = half_to_f32(x0) * half_to_f32(y0);
let s1 = half_to_f32(x1) * half_to_f32(y1);
acc0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p0), _mm256_set1_ps(s0), acc0);
acc1 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p1), _mm256_set1_ps(s1), acc1);
ib += 2;
}
while ib < nb {
let (xb, yb) = (xp.add(ib * Q8_0_BYTES), yp.add(ib * Q8_0_BYTES));
let s = half_to_f32(xb) * half_to_f32(yb);
acc0 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(q8_p32_avx2(xb, yb, ones)),
_mm256_set1_ps(s),
acc0,
);
ib += 1;
}
hsum_ps(_mm256_add_ps(acc0, acc1))
}
#[target_feature(enable = "avx2")]
pub unsafe fn q8_0_q8_0_isums_avx2(x: &[u8], y: &[u8], out: &mut [i32]) {
let ones = _mm256_set1_epi16(1);
for (ib, o) in out.iter_mut().enumerate() {
*o = hsum_epi32(q8_p32_avx2(
x.as_ptr().add(ib * Q8_0_BYTES),
y.as_ptr().add(ib * Q8_0_BYTES),
ones,
));
}
}
#[target_feature(enable = "avx2,fma,f16c,avxvnni")]
pub unsafe fn dot_q8_0_q8_0_avxvnni(x: &[u8], y: &[u8]) -> f32 {
let nb = x.len() / Q8_0_BYTES;
let (mut acc0, mut acc1) = (_mm256_setzero_ps(), _mm256_setzero_ps());
let (xp, yp) = (x.as_ptr(), y.as_ptr());
let mut ib = 0;
while ib + 2 <= nb {
let (x0, y0) = (xp.add(ib * Q8_0_BYTES), yp.add(ib * Q8_0_BYTES));
let (x1, y1) = (x0.add(Q8_0_BYTES), y0.add(Q8_0_BYTES));
let p0 = q8_p32_vnni(x0, y0);
let p1 = q8_p32_vnni(x1, y1);
let s0 = half_to_f32(x0) * half_to_f32(y0);
let s1 = half_to_f32(x1) * half_to_f32(y1);
acc0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p0), _mm256_set1_ps(s0), acc0);
acc1 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p1), _mm256_set1_ps(s1), acc1);
ib += 2;
}
while ib < nb {
let (xb, yb) = (xp.add(ib * Q8_0_BYTES), yp.add(ib * Q8_0_BYTES));
let s = half_to_f32(xb) * half_to_f32(yb);
acc0 = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(q8_p32_vnni(xb, yb)),
_mm256_set1_ps(s),
acc0,
);
ib += 1;
}
hsum_ps(_mm256_add_ps(acc0, acc1))
}
#[target_feature(enable = "avx2,avxvnni")]
pub unsafe fn q8_0_q8_0_isums_avxvnni(x: &[u8], y: &[u8], out: &mut [i32]) {
for (ib, o) in out.iter_mut().enumerate() {
*o = hsum_epi32(q8_p32_vnni(
x.as_ptr().add(ib * Q8_0_BYTES),
y.as_ptr().add(ib * Q8_0_BYTES),
));
}
}
// ---- register-tiled kernels: R weight rows against A activations in one pass ----
//
// Each weight block is decoded once and used against all A activations; each activation block is
// loaded once and used against all R rows. Every output has ONE accumulator that sums blocks in
// order (8 float lanes, reduced at the end), so a tile of any shape gives bit-for-bit the same
// value for a (row, activation) pair as the 1x1 tile at the same level.
//
// The AVX2 level multiplies `|w|` by `sign(x, w)` like the one-row kernels. The AVX-VNNI level uses
// unsigned weights instead (`w + 128`, no sign instruction) and removes the bias by starting each
// block's accumulation from `-128 * sum(x)` in lane 0 (the activation's `corr`), and reads the
// activation scale as a ready-made vector. Both give exact integer block sums.
use super::ActRef;
/// MXFP4 value table with every entry biased by 128 (as unsigned bytes).
#[inline]
#[target_feature(enable = "avx2")]
unsafe fn mx_table_biased() -> __m256i {
let t = _mm_xor_si128(
_mm_loadu_si128(KVALUES_MXFP4.as_ptr() as *const __m128i),
_mm_set1_epi8(-128),
);
_mm256_set_m128i(t, t)
}
/// MXFP4 rows against activations, AVX2. `x[r]` holds `nb` 17-byte blocks; `out[r * A + a]`.
#[inline]
#[target_feature(enable = "avx2,fma")]
unsafe fn mxfp4_tile_avx2<const R: usize, const A: usize>(
x: [&[u8]; R],
acts: [&ActRef; A],
out: &mut [f32],
) {
let nb = x[0].len() / MXFP4_BYTES;
let (table, low, ones) = (mx_table(), _mm_set1_epi8(0x0F), _mm256_set1_epi16(1));
let mut acc = [[_mm256_setzero_ps(); A]; R];
for ib in 0..nb {
for r in 0..R {
let xb = x[r].as_ptr().add(ib * MXFP4_BYTES);
let w = mx_values(xb, table, low);
let wabs = _mm256_sign_epi8(w, w);
let e = e8m0_half(*xb);
for a in 0..A {
let xv =
_mm256_loadu_si256(acts[a].quants.as_ptr().add(ib * 32) as *const __m256i);
let p16 = _mm256_maddubs_epi16(wabs, _mm256_sign_epi8(xv, w));
let p = _mm256_madd_epi16(p16, ones);
let s = *acts[a].scales.get_unchecked(ib) * e;
acc[r][a] =
_mm256_fmadd_ps(_mm256_cvtepi32_ps(p), _mm256_set1_ps(s), acc[r][a]);
}
}
}
for r in 0..R {
for a in 0..A {
out[r * A + a] = hsum_ps(acc[r][a]);
}
}
}
/// MXFP4 rows against activations, AVX-VNNI with unsigned weights.
#[inline]
#[target_feature(enable = "avx2,fma,avxvnni")]
unsafe fn mxfp4_tile_avxvnni<const R: usize, const A: usize>(
x: [&[u8]; R],
acts: [&ActRef; A],
out: &mut [f32],
) {
let nb = x[0].len() / MXFP4_BYTES;
let (table, low) = (mx_table_biased(), _mm_set1_epi8(0x0F));
let mut acc = [[_mm256_setzero_ps(); A]; R];
for ib in 0..nb {
for r in 0..R {
let xb = x[r].as_ptr().add(ib * MXFP4_BYTES);
let w = mx_values(xb, table, low);
let ev = _mm256_set1_ps(e8m0_half(*xb));
for a in 0..A {
let xv =
_mm256_loadu_si256(acts[a].quants.as_ptr().add(ib * 32) as *const __m256i);
let init =
_mm256_loadu_si256(acts[a].corr.as_ptr().add(ib * 8) as *const __m256i);
let p = _mm256_dpbusd_avx_epi32(init, w, xv);
let s = _mm256_mul_ps(
ev,
_mm256_loadu_ps(acts[a].scales_bcast.as_ptr().add(ib * 8)),
);
acc[r][a] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p), s, acc[r][a]);
}
}
}
for r in 0..R {
for a in 0..A {
out[r * A + a] = hsum_ps(acc[r][a]);
}
}
}
/// Q8_0 rows (34-byte blocks with a half scale) against activations, AVX2.
#[inline]
#[target_feature(enable = "avx2,fma,f16c")]
unsafe fn q8_tile_avx2<const R: usize, const A: usize>(
x: [&[u8]; R],
acts: [&ActRef; A],
out: &mut [f32],
) {
let nb = x[0].len() / Q8_0_BYTES;
let ones = _mm256_set1_epi16(1);
let mut acc = [[_mm256_setzero_ps(); A]; R];
for ib in 0..nb {
for r in 0..R {
let xb = x[r].as_ptr().add(ib * Q8_0_BYTES);
let w = _mm256_loadu_si256(xb.add(2) as *const __m256i);
let wabs = _mm256_sign_epi8(w, w);
let d = half_to_f32(xb);
for a in 0..A {
let xv =
_mm256_loadu_si256(acts[a].quants.as_ptr().add(ib * 32) as *const __m256i);
let p16 = _mm256_maddubs_epi16(wabs, _mm256_sign_epi8(xv, w));
let p = _mm256_madd_epi16(p16, ones);
let s = *acts[a].scales.get_unchecked(ib) * d;
acc[r][a] =
_mm256_fmadd_ps(_mm256_cvtepi32_ps(p), _mm256_set1_ps(s), acc[r][a]);
}
}
}
for r in 0..R {
for a in 0..A {
out[r * A + a] = hsum_ps(acc[r][a]);
}
}
}
/// Q8_0 rows against activations, AVX-VNNI with unsigned weights (`w ^ 0x80`).
#[inline]
#[target_feature(enable = "avx2,fma,f16c,avxvnni")]
unsafe fn q8_tile_avxvnni<const R: usize, const A: usize>(
x: [&[u8]; R],
acts: [&ActRef; A],
out: &mut [f32],
) {
let nb = x[0].len() / Q8_0_BYTES;
let flip = _mm256_set1_epi8(-128);
let mut acc = [[_mm256_setzero_ps(); A]; R];
for ib in 0..nb {
for r in 0..R {
let xb = x[r].as_ptr().add(ib * Q8_0_BYTES);
let w = _mm256_xor_si256(_mm256_loadu_si256(xb.add(2) as *const __m256i), flip);
let dv = _mm256_set1_ps(half_to_f32(xb));
for a in 0..A {
let xv =
_mm256_loadu_si256(acts[a].quants.as_ptr().add(ib * 32) as *const __m256i);
let init =
_mm256_loadu_si256(acts[a].corr.as_ptr().add(ib * 8) as *const __m256i);
let p = _mm256_dpbusd_avx_epi32(init, w, xv);
let s = _mm256_mul_ps(
dv,
_mm256_loadu_ps(acts[a].scales_bcast.as_ptr().add(ib * 8)),
);
acc[r][a] = _mm256_fmadd_ps(_mm256_cvtepi32_ps(p), s, acc[r][a]);
}
}
}
for r in 0..R {
for a in 0..A {
out[r * A + a] = hsum_ps(acc[r][a]);
}
}
}
/// Slice of exactly `N` references to an array (the shape was checked by the caller).
#[inline(always)]
fn conv<T, const N: usize>(s: &[T]) -> [&T; N] {
std::array::from_fn(|i| &s[i])
}
/// Slice of exactly `N` slices to an array (the shape was checked by the caller).
#[inline(always)]
fn conv_rows<'a, const N: usize>(s: &[&'a [u8]]) -> [&'a [u8]; N] {
std::array::from_fn(|i| s[i])
}
/// Expands to a `match` over the tile shapes `1..=4` rows by `1..=4` activations.
macro_rules! tile_shapes {
($generic:ident, $x:ident, $acts:ident, $out:ident) => {
match ($x.len(), $acts.len()) {
(1, 1) => $generic::<1, 1>(conv_rows($x), conv($acts), $out),
(1, 2) => $generic::<1, 2>(conv_rows($x), conv($acts), $out),
(1, 3) => $generic::<1, 3>(conv_rows($x), conv($acts), $out),
(1, 4) => $generic::<1, 4>(conv_rows($x), conv($acts), $out),
(2, 1) => $generic::<2, 1>(conv_rows($x), conv($acts), $out),
(2, 2) => $generic::<2, 2>(conv_rows($x), conv($acts), $out),
(2, 3) => $generic::<2, 3>(conv_rows($x), conv($acts), $out),
(2, 4) => $generic::<2, 4>(conv_rows($x), conv($acts), $out),
(3, 1) => $generic::<3, 1>(conv_rows($x), conv($acts), $out),
(3, 2) => $generic::<3, 2>(conv_rows($x), conv($acts), $out),
(3, 3) => $generic::<3, 3>(conv_rows($x), conv($acts), $out),
(3, 4) => $generic::<3, 4>(conv_rows($x), conv($acts), $out),
(4, 1) => $generic::<4, 1>(conv_rows($x), conv($acts), $out),
(4, 2) => $generic::<4, 2>(conv_rows($x), conv($acts), $out),
(4, 3) => $generic::<4, 3>(conv_rows($x), conv($acts), $out),
(4, 4) => $generic::<4, 4>(conv_rows($x), conv($acts), $out),
_ => unreachable!("tile shape is checked by the safe wrapper"),
}
};
}
/// Largest number of rows or activations in one tile.
pub const TILE_MAX: usize = 4;
/// MXFP4 tile of `x.len()` rows by `acts.len()` activations (each in `1..=TILE_MAX`).
#[target_feature(enable = "avx2,fma")]
pub unsafe fn mxfp4_q8r_tile_avx2(x: &[&[u8]], acts: &[ActRef], out: &mut [f32]) {
tile_shapes!(mxfp4_tile_avx2, x, acts, out)
}
/// As [`mxfp4_q8r_tile_avx2`] with AVX-VNNI.
#[target_feature(enable = "avx2,fma,avxvnni")]
pub unsafe fn mxfp4_q8r_tile_avxvnni(x: &[&[u8]], acts: &[ActRef], out: &mut [f32]) {
tile_shapes!(mxfp4_tile_avxvnni, x, acts, out)
}
/// Q8_0 tile of `x.len()` rows by `acts.len()` activations (each in `1..=TILE_MAX`).
#[target_feature(enable = "avx2,fma,f16c")]
pub unsafe fn q8_q8r_tile_avx2(x: &[&[u8]], acts: &[ActRef], out: &mut [f32]) {
tile_shapes!(q8_tile_avx2, x, acts, out)
}
/// As [`q8_q8r_tile_avx2`] with AVX-VNNI.
#[target_feature(enable = "avx2,fma,f16c,avxvnni")]
pub unsafe fn q8_q8r_tile_avxvnni(x: &[&[u8]], acts: &[ActRef], out: &mut [f32]) {
tile_shapes!(q8_tile_avxvnni, x, acts, out)
}
// ---- multi-activation kernels: one weight row against up to MULTI_MAX activations ----
//
// The row is decoded once per segment of blocks (int8 values, their absolute values and the block
// scales), then each activation runs over the decoded segment with exactly the arithmetic of the
// one-activation kernel at the same level: the same integer products per lane, the same scale
// product, the same accumulator for every block (four for MXFP4, two for Q8_0) and the same final
// reduction. So `out[a]` is bit-identical to the one-activation kernel for `acts[a]`, whatever the
// number of activations.
use super::{MULTI_MAX, Q8rRef};
/// Blocks decoded at a time (a multiple of four, so segments never split a four-block group).
const SEGMENT: usize = 64;
/// `|w| * sign(q, w)` summed in groups of four products per lane, as `block_p32_avx2` does.
#[inline]
#[target_feature(enable = "avx2")]
unsafe fn decoded_p32_avx2(wabs: __m256i, w: __m256i, q: *const u8) -> __m256i {
let q = _mm256_loadu_si256(q as *const __m256i);
let p16 = _mm256_maddubs_epi16(wabs, _mm256_sign_epi8(q, w));
_mm256_madd_epi16(p16, _mm256_set1_epi16(1))
}
/// As [`decoded_p32_avx2`] with one `vpdpbusd`, as `block_p32_vnni` does.
#[inline]
#[target_feature(enable = "avx2,avxvnni")]
unsafe fn decoded_p32_vnni(wabs: __m256i, w: __m256i, q: *const u8) -> __m256i {
let q = _mm256_loadu_si256(q as *const __m256i);
_mm256_dpbusd_avx_epi32(_mm256_setzero_si256(), wabs, _mm256_sign_epi8(q, w))
}
/// Generates a multi-activation kernel. `$decode` fills `w[i]` and `d[i]` (the weight scale) for
/// block `ib`; `$groups` is the number of accumulators of the one-activation kernel (4 or 2).
macro_rules! multi_kernel {
($name:ident, $features:literal, $block_bytes:expr, $p32:ident, $groups:literal, |$xb:ident, $ib:ident| $decode:expr) => {
#[target_feature(enable = $features)]
pub unsafe fn $name(x: &[u8], acts: &[Q8rRef], out: &mut [f32]) {
let nb = x.len() / $block_bytes;
let main = nb - nb % $groups;
let mut acc = [[_mm256_setzero_ps(); $groups]; MULTI_MAX];
let mut w = [_mm256_setzero_si256(); SEGMENT];
let mut wabs = [_mm256_setzero_si256(); SEGMENT];
let mut d = [0.0f32; SEGMENT];
let mut s = [0.0f32; SEGMENT];
let mut seg0 = 0;
while seg0 < nb {
let seg = SEGMENT.min(nb - seg0);
for i in 0..seg {
let $ib = seg0 + i;
let $xb = x.as_ptr().add($ib * $block_bytes);
let (wi, di): (__m256i, f32) = $decode;
w[i] = wi;
wabs[i] = _mm256_sign_epi8(wi, wi);
d[i] = di;
}
for (a, act) in acts.iter().enumerate() {
// the scale products, lane by lane the same multiplication as the scalar one
let mut i = 0;
while i + 8 <= seg {
let v = _mm256_mul_ps(
_mm256_loadu_ps(act.scales.as_ptr().add(seg0 + i)),
_mm256_loadu_ps(d.as_ptr().add(i)),
);
_mm256_storeu_ps(s.as_mut_ptr().add(i), v);
i += 8;
}
while i < seg {
s[i] = *act.scales.get_unchecked(seg0 + i) * d[i];
i += 1;
}
let q = act.quants.as_ptr() as *const u8;
let mut g = acc[a];
// block `ib < main` goes to accumulator `ib % groups` (segments start at a
// multiple of four), the remaining blocks to the first one
let mut i = 0;
while i + $groups <= seg && seg0 + i + $groups <= main {
for (k, gk) in g.iter_mut().enumerate() {
let p = $p32(wabs[i + k], w[i + k], q.add((seg0 + i + k) * 32));
*gk = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p),
_mm256_broadcast_ss(&s[i + k]),
*gk,
);
}
i += $groups;
}
while i < seg {
let p = $p32(wabs[i], w[i], q.add((seg0 + i) * 32));
g[0] = _mm256_fmadd_ps(
_mm256_cvtepi32_ps(p),
_mm256_broadcast_ss(&s[i]),
g[0],
);
i += 1;
}
acc[a] = g;
}
seg0 += seg;
}
for (a, o) in out.iter_mut().enumerate().take(acts.len()) {
*o = multi_reduce(&acc[a]);
}
}
};
}
/// The final reduction of the one-activation kernels: `(a0 + a1) + (a2 + a3)` for four
/// accumulators, `a0 + a1` for two, then the horizontal sum.
#[inline]
#[target_feature(enable = "avx")]
unsafe fn multi_reduce<const G: usize>(g: &[__m256; G]) -> f32 {
if G == 4 {
hsum_ps(_mm256_add_ps(
_mm256_add_ps(g[0], g[1]),
_mm256_add_ps(g[2], g[3]),
))
} else {
hsum_ps(_mm256_add_ps(g[0], g[1]))
}
}
multi_kernel!(
dot_mxfp4_q8r4_multi_avx2,
"avx2,fma",
MXFP4_BYTES,
decoded_p32_avx2,
4,
|xb, ib| (
mx_values(xb, mx_table(), _mm_set1_epi8(0x0F)),
e8m0_half(*xb)
)
);
multi_kernel!(
dot_mxfp4_q8r4_multi_avxvnni,
"avx2,fma,avxvnni",
MXFP4_BYTES,
decoded_p32_vnni,
4,
|xb, ib| (
mx_values(xb, mx_table(), _mm_set1_epi8(0x0F)),
e8m0_half(*xb)
)
);
multi_kernel!(
dot_q8_0_q8r_multi_avx2,
"avx2,fma,f16c",
Q8_0_BYTES,
decoded_p32_avx2,
2,
|xb, ib| (
_mm256_loadu_si256(xb.add(2) as *const __m256i),
half_to_f32(xb)
)
);
multi_kernel!(
dot_q8_0_q8r_multi_avxvnni,
"avx2,fma,f16c,avxvnni",
Q8_0_BYTES,
decoded_p32_vnni,
2,
|xb, ib| (
_mm256_loadu_si256(xb.add(2) as *const __m256i),
half_to_f32(xb)
)
);
// ---- attention ----
#[inline]
#[target_feature(enable = "avx2,fma")]
unsafe fn attn_dot(q: *const f32, k: *const f32, hd: usize) -> f32 {
let (mut a0, mut a1, mut a2, mut a3) = (
_mm256_setzero_ps(),
_mm256_setzero_ps(),
_mm256_setzero_ps(),
_mm256_setzero_ps(),
);
let mut j = 0;
while j + 32 <= hd {
a0 = _mm256_fmadd_ps(_mm256_loadu_ps(q.add(j)), _mm256_loadu_ps(k.add(j)), a0);
a1 = _mm256_fmadd_ps(
_mm256_loadu_ps(q.add(j + 8)),
_mm256_loadu_ps(k.add(j + 8)),
a1,
);
a2 = _mm256_fmadd_ps(
_mm256_loadu_ps(q.add(j + 16)),
_mm256_loadu_ps(k.add(j + 16)),
a2,
);
a3 = _mm256_fmadd_ps(
_mm256_loadu_ps(q.add(j + 24)),
_mm256_loadu_ps(k.add(j + 24)),
a3,
);
j += 32;
}
while j + 8 <= hd {
a0 = _mm256_fmadd_ps(_mm256_loadu_ps(q.add(j)), _mm256_loadu_ps(k.add(j)), a0);
j += 8;
}
let mut sum = hsum_ps(_mm256_add_ps(_mm256_add_ps(a0, a1), _mm256_add_ps(a2, a3)));
while j < hd {
sum += *q.add(j) * *k.add(j);
j += 1;
}
sum
}
#[target_feature(enable = "avx2,fma")]
pub unsafe fn attn_scores_avx2(
q: &[f32],
heads: usize,
keys: &[f32],
stride: usize,
n: usize,
scale: f32,
out: &mut [f32],
) {
let hd = q.len() / heads;
let mut first = 0;
while first < n {
let block = (n - first).min(super::ATTN_BLOCK);
for g in 0..heads {
let query = q.as_ptr().add(g * hd);
for i in first..first + block {
*out.get_unchecked_mut(g * n + i) =
attn_dot(query, keys.as_ptr().add(i * stride), hd) * scale;
}
}
first += block;
}
}
#[target_feature(enable = "avx2,fma")]
pub unsafe fn attn_weighted_sum_avx2(
weights: &[f32],
heads: usize,
n: usize,
values: &[f32],
stride: usize,
out: &mut [f32],
) {
let hd = out.len() / heads;
out.fill(0.0);
// columns in chunks of up to 64 floats (eight accumulators), positions in L1-sized blocks
let mut col = 0;
while col + 8 <= hd {
let width = (hd - col).min(64) / 8 * 8;
let vectors = width / 8;
let mut first = 0;
while first < n {
let block = (n - first).min(super::ATTN_BLOCK);
for g in 0..heads {
let dst = out.as_mut_ptr().add(g * hd + col);
let mut acc = [_mm256_setzero_ps(); 8];
for (v, a) in acc.iter_mut().enumerate().take(vectors) {
*a = _mm256_loadu_ps(dst.add(v * 8));
}
for i in first..first + block {
let wv = _mm256_set1_ps(*weights.get_unchecked(g * n + i));
let row = values.as_ptr().add(i * stride + col);
for (v, a) in acc.iter_mut().enumerate().take(vectors) {
*a = _mm256_fmadd_ps(wv, _mm256_loadu_ps(row.add(v * 8)), *a);
}
}
for (v, a) in acc.iter().enumerate().take(vectors) {
_mm256_storeu_ps(dst.add(v * 8), *a);
}
}
first += block;
}
col += width;
}
// columns left over when hd is not a multiple of 8
while col < hd {
for g in 0..heads {
let mut sum = 0.0f32;
for i in 0..n {
sum +=
*weights.get_unchecked(g * n + i) * *values.get_unchecked(i * stride + col);
}
out[g * hd + col] = sum;
}
col += 1;
}
}
/// `exp` of eight floats, relative error below 3e-7 for inputs above -87 (results below that are 0).
#[inline]
#[target_feature(enable = "avx2,fma")]
unsafe fn exp256(x: __m256) -> __m256 {
let underflow = _mm256_cmp_ps::<_CMP_LT_OQ>(x, _mm256_set1_ps(-87.0));
let x = _mm256_min_ps(x, _mm256_set1_ps(88.0));
let n = _mm256_round_ps::<{ _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC }>(
_mm256_mul_ps(x, _mm256_set1_ps(std::f32::consts::LOG2_E)),
);
// r = x - n ln 2, with ln 2 split into a short high part and a low correction
let r = _mm256_fnmadd_ps(n, _mm256_set1_ps(0.693_359_375), x);
let r = _mm256_fnmadd_ps(n, _mm256_set1_ps(-2.121_944_4e-4), r);
// Cephes polynomial for exp(r) - 1 - r on |r| <= ln 2 / 2
let mut p = _mm256_set1_ps(1.987_569_15e-4);
for c in [
1.398_199_950_7e-3f32,
8.333_451_907_3e-3,
4.166_579_589_4e-2,
1.666_666_545_9e-1,
5.000_000_120_1e-1,
] {
p = _mm256_fmadd_ps(p, r, _mm256_set1_ps(c));
}
let y = _mm256_fmadd_ps(
_mm256_mul_ps(p, r),
r,
_mm256_add_ps(r, _mm256_set1_ps(1.0)),
);
// multiply by 2^n through the exponent field
let pow2 = _mm256_castsi256_ps(_mm256_slli_epi32::<23>(_mm256_add_epi32(
_mm256_cvtps_epi32(n),
_mm256_set1_epi32(127),
)));
_mm256_andnot_ps(underflow, _mm256_mul_ps(y, pow2))
}
/// Eight half floats at `p` as f32 lanes.
#[inline]
#[target_feature(enable = "avx2,f16c")]
unsafe fn load_f16x8(p: *const u16) -> __m256 {
_mm256_cvtph_ps(_mm_loadu_si128(p as *const __m128i))
}
#[inline]
#[target_feature(enable = "avx2,fma,f16c")]
unsafe fn attn_dot_f16(q: *const f32, k: *const u16, hd: usize) -> f32 {
let (mut a0, mut a1, mut a2, mut a3) = (
_mm256_setzero_ps(),
_mm256_setzero_ps(),
_mm256_setzero_ps(),
_mm256_setzero_ps(),
);
let mut j = 0;
while j + 32 <= hd {
a0 = _mm256_fmadd_ps(_mm256_loadu_ps(q.add(j)), load_f16x8(k.add(j)), a0);
a1 = _mm256_fmadd_ps(_mm256_loadu_ps(q.add(j + 8)), load_f16x8(k.add(j + 8)), a1);
a2 = _mm256_fmadd_ps(
_mm256_loadu_ps(q.add(j + 16)),
load_f16x8(k.add(j + 16)),
a2,
);
a3 = _mm256_fmadd_ps(
_mm256_loadu_ps(q.add(j + 24)),
load_f16x8(k.add(j + 24)),
a3,
);
j += 32;
}
while j + 8 <= hd {
a0 = _mm256_fmadd_ps(_mm256_loadu_ps(q.add(j)), load_f16x8(k.add(j)), a0);
j += 8;
}
let mut sum = hsum_ps(_mm256_add_ps(_mm256_add_ps(a0, a1), _mm256_add_ps(a2, a3)));
while j < hd {
sum += *q.add(j) * super::f16_to_f32(*k.add(j));
j += 1;
}
sum
}
#[target_feature(enable = "avx2,fma,f16c")]
pub unsafe fn attn_scores_f16_avx2(
q: &[f32],
heads: usize,
keys: &[u16],
stride: usize,
n: usize,
scale: f32,
out: &mut [f32],
) {
let hd = q.len() / heads;
let mut first = 0;
while first < n {
let block = (n - first).min(super::ATTN_BLOCK);
for g in 0..heads {
let query = q.as_ptr().add(g * hd);
for i in first..first + block {
*out.get_unchecked_mut(g * n + i) =
attn_dot_f16(query, keys.as_ptr().add(i * stride), hd) * scale;
}
}
first += block;
}
}
#[target_feature(enable = "avx2,fma,f16c")]
pub unsafe fn attn_weighted_sum_f16_avx2(
weights: &[f32],
heads: usize,
n: usize,
values: &[u16],
stride: usize,
out: &mut [f32],
) {
let hd = out.len() / heads;
out.fill(0.0);
let mut col = 0;
while col + 8 <= hd {
let width = (hd - col).min(64) / 8 * 8;
let vectors = width / 8;
let mut first = 0;
while first < n {
let block = (n - first).min(super::ATTN_BLOCK);
for g in 0..heads {
let dst = out.as_mut_ptr().add(g * hd + col);
let mut acc = [_mm256_setzero_ps(); 8];
for (v, a) in acc.iter_mut().enumerate().take(vectors) {
*a = _mm256_loadu_ps(dst.add(v * 8));
}
for i in first..first + block {
let wv = _mm256_set1_ps(*weights.get_unchecked(g * n + i));
let row = values.as_ptr().add(i * stride + col);
for (v, a) in acc.iter_mut().enumerate().take(vectors) {
*a = _mm256_fmadd_ps(wv, load_f16x8(row.add(v * 8)), *a);
}
}
for (v, a) in acc.iter().enumerate().take(vectors) {
_mm256_storeu_ps(dst.add(v * 8), *a);
}
}
first += block;
}
col += width;
}
while col < hd {
for g in 0..heads {
let mut sum = 0.0f32;
for i in 0..n {
sum += *weights.get_unchecked(g * n + i)
* super::f16_to_f32(*values.get_unchecked(i * stride + col));
}
out[g * hd + col] = sum;
}
col += 1;
}
}
/// Converts floats to half bit patterns with F16C (round to nearest even); `dst.len() == src.len()`.
#[target_feature(enable = "avx2,f16c")]
pub unsafe fn f32_to_f16_slice_avx2(src: &[f32], dst: &mut [u16]) {
let mut i = 0;
while i + 8 <= src.len() {
let h = _mm256_cvtps_ph::<{ _MM_FROUND_TO_NEAREST_INT }>(_mm256_loadu_ps(
src.as_ptr().add(i),
));
_mm_storeu_si128(dst.as_mut_ptr().add(i) as *mut __m128i, h);
i += 8;
}
while i < src.len() {
dst[i] = cvt_f32_f16(src[i]);
i += 1;
}
}
/// Converts half bit patterns to floats with F16C; `dst.len() == src.len()`.
#[target_feature(enable = "avx2,f16c")]
pub unsafe fn f16_to_f32_slice_avx2(src: &[u16], dst: &mut [f32]) {
let mut i = 0;
while i + 8 <= src.len() {
let h = _mm_loadu_si128(src.as_ptr().add(i) as *const __m128i);
_mm256_storeu_ps(dst.as_mut_ptr().add(i), _mm256_cvtph_ps(h));
i += 8;
}
while i < src.len() {
dst[i] = super::f16_to_f32(src[i]);
i += 1;
}
}
#[target_feature(enable = "avx2,fma")]
pub unsafe fn swiglu_oai_avx2(
gate: &[f32],
up: &[f32],
alpha: f32,
limit: f32,
out: &mut [f32],
) {
let n = out.len().min(gate.len()).min(up.len());
let (lim, nlim) = (_mm256_set1_ps(limit), _mm256_set1_ps(-limit));
let (neg_alpha, one) = (_mm256_set1_ps(-alpha), _mm256_set1_ps(1.0));
let mut i = 0;
while i + 8 <= n {
let x = _mm256_min_ps(_mm256_loadu_ps(gate.as_ptr().add(i)), lim);
let y = _mm256_min_ps(
_mm256_max_ps(_mm256_loadu_ps(up.as_ptr().add(i)), nlim),
lim,
);
let e = exp256(_mm256_mul_ps(neg_alpha, x));
let sigmoid = _mm256_div_ps(one, _mm256_add_ps(one, e));
let r = _mm256_mul_ps(_mm256_mul_ps(x, sigmoid), _mm256_add_ps(one, y));
_mm256_storeu_ps(out.as_mut_ptr().add(i), r);
i += 8;
}
super::swiglu_oai_scalar(&gate[i..n], &up[i..n], alpha, limit, &mut out[i..n]);
}
#[target_feature(enable = "avx2,fma")]
pub unsafe fn exp_shift_sum_avx2(x: &mut [f32], max: f32) -> f32 {
let m = _mm256_set1_ps(max);
let mut acc = _mm256_setzero_ps();
let mut i = 0;
while i + 8 <= x.len() {
let e = exp256(_mm256_sub_ps(_mm256_loadu_ps(x.as_ptr().add(i)), m));
_mm256_storeu_ps(x.as_mut_ptr().add(i), e);
acc = _mm256_add_ps(acc, e);
i += 8;
}
let mut sum = hsum_ps(acc);
while i < x.len() {
x[i] = (x[i] - max).exp();
sum += x[i];
i += 1;
}
sum
}
/// Float to half with the F16C instruction (to test the portable conversion against).
#[target_feature(enable = "f16c")]
pub unsafe fn f32_to_f16_f16c(f: f32) -> u16 {
cvt_f32_f16(f)
}
/// AVX2 Q8_0 activation quantizer; bit-identical to the portable one.
#[target_feature(enable = "avx2,fma,f16c")]
pub unsafe fn quantize_q8_0_avx2(x: &[f32], out: &mut [u8]) {
let nb = x.len() / 32;
let sign_mask = _mm256_set1_ps(-0.0);
let lane_fix = _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7);
let floor127 = _mm256_set1_epi8(-127);
for ib in 0..nb {
let xb = x.as_ptr().add(ib * 32);
let yb = out.as_mut_ptr().add(ib * Q8_0_BYTES);
let v0 = _mm256_loadu_ps(xb);
let v1 = _mm256_loadu_ps(xb.add(8));
let v2 = _mm256_loadu_ps(xb.add(16));
let v3 = _mm256_loadu_ps(xb.add(24));
let amax_v = _mm256_max_ps(
_mm256_max_ps(
_mm256_andnot_ps(sign_mask, v0),
_mm256_andnot_ps(sign_mask, v1),
),
_mm256_max_ps(
_mm256_andnot_ps(sign_mask, v2),
_mm256_andnot_ps(sign_mask, v3),
),
);
let mut m4 = _mm_max_ps(
_mm256_extractf128_ps::<1>(amax_v),
_mm256_castps256_ps128(amax_v),
);
m4 = _mm_max_ps(m4, _mm_movehl_ps(m4, m4));
m4 = _mm_max_ss(m4, _mm_movehdup_ps(m4));
let amax = _mm_cvtss_f32(m4);
let d = amax / 127.0;
let id = if d != 0.0 { 1.0 / d } else { 0.0 };
let dh = cvt_f32_f16(d).to_le_bytes();
*yb = dh[0];
*yb.add(1) = dh[1];
let mul = _mm256_set1_ps(id);
const MODE: i32 = _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC;
let i0 = _mm256_cvtps_epi32(_mm256_round_ps::<MODE>(_mm256_mul_ps(v0, mul)));
let i1 = _mm256_cvtps_epi32(_mm256_round_ps::<MODE>(_mm256_mul_ps(v1, mul)));
let i2 = _mm256_cvtps_epi32(_mm256_round_ps::<MODE>(_mm256_mul_ps(v2, mul)));
let i3 = _mm256_cvtps_epi32(_mm256_round_ps::<MODE>(_mm256_mul_ps(v3, mul)));
let p01 = _mm256_packs_epi32(i0, i1);
let p23 = _mm256_packs_epi32(i2, i3);
let mut q = _mm256_packs_epi16(p01, p23);
q = _mm256_permutevar8x32_epi32(q, lane_fix);
q = _mm256_max_epi8(q, floor127);
_mm256_storeu_si256(yb.add(2) as *mut __m256i, q);
}
}
}
/// Scalar tail shared by the SIMD int4 kernels: elements `from..` of the packed product.
fn dot_i4i8_tail(w4: &[u8], x: &[i8], from: usize) -> i32 {
let n = x.len();
let mut sum = 0i32;
let mut i = from;
while i + 1 < n {
let b = w4[i >> 1];
sum += (i32::from(b & 0xF) - 8) * i32::from(x[i])
+ (i32::from(b >> 4) - 8) * i32::from(x[i + 1]);
i += 2;
}
if i < n {
sum += (i32::from(w4[i >> 1] & 0xF) - 8) * i32::from(x[i]);
}
sum
}