/* avx_gemm.cpp -- the GEMM family and the two vocabulary edges. * * nt: C[M,N] = A[M,K] @ B[N,K]^T * * B is stored TRANSPOSED because that is the layout every weight in a transformer already has, so * both operands are k-contiguous and the inner loop is a DOT PRODUCT over k rather than an outer * product over n. That single fact decides the whole shape of this file, and it is worth being * explicit about what it costs, because the textbook GEMM does the opposite. * * ============================== WHY DOT PRODUCT AND NOT OUTER PRODUCT ============================== * * The classical high-performance GEMM (Goto's, and every BLAS since) packs B into panels laid out * so the inner loop broadcasts one A element against a VECTOR of n, accumulating C[m, n0:n0+w] in * registers with no horizontal reduction anywhere. It is the right shape when you may choose B's * layout. * * Here B's layout is given, it is k-contiguous, and a transformer weight is READ ONCE PER LAUNCH -- * there is no second GEMM against the same weight to amortise a pack over. Packing B into n-major * panels would mean touching the largest operand twice to save horizontal reductions that only * happen once per output element. At decode (M = 1) the whole GEMM is a matvec: the weight is * streamed exactly once, the arithmetic intensity is 2 flops a byte, and nothing about the * instruction mix matters because the memory system is the wall. At prefill the register blocking * below recovers most of what a packed form would give. * * So: REGISTER-BLOCKED DOT PRODUCT. MR rows of A against NR rows of B, MR*NR vector accumulators * live across the whole k loop, MR + NR vector loads per k step, and the horizontal reduction paid * once per output element rather than once per k step. * * ============================== THE BLOCK SIZE IS THE REGISTER FILE, AND IT WAS SWEPT ============================== * * MEASURED, gemm_nt bf16 at M=512, N=2048, K=2048, one thread, on the part libavx/README.md names: * * AVX-512, 32 ZMM 4x4 23.2 ms 4x6 22.1 ms <-- chosen * 6x4 24.2 ms 6x6 24.0 ms * 8x4 23.8 ms 8x2 35.2 ms 12x2 34.1 ms * AVX2/AVX, 16 YMM 3x3 34.4 ms 2x6 30.7 ms <-- chosen * 2x5 31.9 ms 2x4 34.8 ms 2x3 40.5 ms * 3x4 58.4 ms 4x3 58.1 ms * * TWO THINGS IN THAT TABLE ARE WORTH MORE THAN THE CHOICE. The first is the cliff: 3x4 and 4x3 at * AVX2 are 58 ms against 31-34 for everything around them, because 12 accumulators plus 3 or 4 A * vectors plus one B vector is 16 or 17 live in a 16-register file -- the spill lands INSIDE the k * loop and costs 1.9x. That is why this is written out per level rather than derived from a * formula, and why the numbers sit next to the code. * * The second is that WIDER IN N BEAT WIDER IN M at both levels, at equal arithmetic intensity: * 2x6 and 3x3 both load 8 vectors for 12 and 9 FMAs respectively -- intensity 1.5 either way -- and * 2x6 is 11% faster. The B vector is loaded once and reused across the MR inner iterations, so a * small MR keeps fewer values live and schedules better. Nothing about the flop count predicts * this; it came out of the sweep. * * scalar stays 2x2, where "vector" is one float and the blocking only helps the load/store * scheduler. * * ============================== ONE MICROKERNEL, NOT TWENTY-EIGHT ============================== * * libref templates its inner loop on (A dtype, B dtype) and selects through a function pointer, * because for it the per-element dtype switch WOULD be the cost -- one element is read per FLOP. * That is 16 instantiations for the plain family and 28 for the quantised one. * * This plugin instead PACKS TO f32 and has ONE microkernel: * * A is widened once into a contiguous [M, K] f32 buffer -- M*K conversions * each B row is widened once, per n-block, into a thread-local buffer -- N*K conversions * * The conversion count is the same as the fused form's (every element of both operands is * converted exactly once either way); what it buys is that W4, W2, MXFP4, fp8 and i8 all arrive at * the same code, so the packed-nibble unpack is written once (avx_support.cpp) and the microkernel * never sees a dtype. 28 instantiations x 4 ISA levels of hand-written vector code is not a * maintainable object, and the ones nobody runs would be the ones that are wrong. * * What it costs is an L1 round trip: the packed rows are written and read back. Against an operand * that came from L2 or DRAM -- which a weight always did -- that is not measurable, and the * exception is stated where it happens (an f32 contiguous A is used in place, unpacked). * * THE MEMORY THIS COSTS IS BOUNDED BY THE M BLOCK below -- the pack is MB*K floats, not M*K -- and * it is not blocked over K. That is a deliberate omission: K-blocking would bound the pack further * but would force the C accumulator into memory, because the k reduction could then no longer live * in registers across the whole launch. C is M*N floats, larger than the pack at every shape this * plugin sees, and another pass over it. * * ============================== PARALLELISM IS OVER N ============================== * * A decode step is M = 1 and a verify step is M <= 64, so an M-major split leaves all but one core * idle on exactly the shape the engine spends its life in. N is thousands in every GEMM a * transformer issues. libref made the same choice for the same reason. Each thread owns whole * output elements, so the summation order does not depend on the thread count and two runs at * different loads are bit-identical. */ #include "avx_vec.h" #include "avx_common.h" #include "avx_rows.h" #include using namespace avx; #include "avx_had.h" /* ================================================================== register blocking */ #if AVX_LEVEL == 3 constexpr int64_t MR = 4, NR = 6; #elif AVX_LEVEL == 2 || AVX_LEVEL == 1 constexpr int64_t MR = 2, NR = 6; #else constexpr int64_t MR = 2, NR = 2; #endif /* MR x NR dot products over [k0, k1), accumulated into `out` (which is ADDED to, not overwritten, * so the grouped GEMM can call this per group). * * The tail is summed separately and added to the horizontal reduction rather than folded into a * masked vector: the two give different orders and the masked form is only free at AVX-512. One * order, four levels. */ template static inline void dot_block(const float* A, int64_t lda, const float* B, int64_t ldb, int64_t k0, int64_t k1, float out[MB_][NB_]) { vf acc[MB_][NB_]; for (int i = 0; i < MB_; ++i) for (int j = 0; j < NB_; ++j) acc[i][j] = vf_zero(); int64_t k = k0; for (; k + VF_N <= k1; k += VF_N) { vf av[MB_]; for (int i = 0; i < MB_; ++i) av[i] = vf_loadu(A + i * lda + k); for (int j = 0; j < NB_; ++j) { const vf bv = vf_loadu(B + j * ldb + k); for (int i = 0; i < MB_; ++i) acc[i][j] = vf_fma(av[i], bv, acc[i][j]); } } for (int i = 0; i < MB_; ++i) for (int j = 0; j < NB_; ++j) { float s = vf_hsum(acc[i][j]); for (int64_t t = k; t < k1; ++t) s += A[i * lda + t] * B[j * ldb + t]; out[i][j] += s; } } /* One dot product, for the ragged edge of the M and N loops. Four accumulators, which is what * covers the FMA latency; the edge is at most MR-1 by NR-1 blocks of a launch, so its cost is * noise, but writing it as a scalar loop would make a narrow GEMM (N < NR) run scalar throughout * and a draft head's lm_head is exactly that shape. */ static inline float dot1(const float* a, const float* b, int64_t k0, int64_t k1) { vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero(); int64_t k = k0; for (; k + 4 * VF_N <= k1; k += 4 * VF_N) { a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0); a1 = vf_fma(vf_loadu(a + k + VF_N), vf_loadu(b + k + VF_N), a1); a2 = vf_fma(vf_loadu(a + k + 2 * VF_N), vf_loadu(b + k + 2 * VF_N), a2); a3 = vf_fma(vf_loadu(a + k + 3 * VF_N), vf_loadu(b + k + 3 * VF_N), a3); } for (; k + VF_N <= k1; k += VF_N) a0 = vf_fma(vf_loadu(a + k), vf_loadu(b + k), a0); float s = vf_hsum(vf_add(vf_add(a0, a1), vf_add(a2, a3))); for (; k < k1; ++k) s += a[k] * b[k]; return s; } /* ================================================================== operand readings * libref/ref_gemm.h's, and they are copied for the same reason avx_common.h copies the addressing * helpers: they are the CONTRACT for which bytes an operand's (row, col) lives at, not a * convenience. `row_stride` (avx_common.h) in particular is the one that makes an oracle wrong * when it is wrong -- a rank-3 [tokens, heads, width] activation read as [tokens, heads*width] has * a row stride that is the product of the trailing dimensions and NOT stride[rank-2], and taking * the head stride instead lands row 0 correctly and starts every row after it `width` elements * in. */ struct Mat { const RadTensor* t; int64_t rs, cs; }; static inline Mat as_mat(const RadTensor* t, int64_t cols) { Mat m{ t, cols, 1 }; if (t->rank < 2) return m; m.cs = t->stride[t->rank - 1]; m.rs = row_stride(t, cols); return m; } /* A quantised operand's scale stream. libref/ref_gemm.h is the definition, including the `rblk` * rule that makes a DeepSeek-style [ceil(N/128)][ceil(K/128)] block grid readable: without it a * 17408-row weight's 136-row scale plane is read as if it had 17408 rows and lands on groups = 0, * which is a plausible wrong number rather than a diagnosable failure. */ struct Scales { const void* p; uint32_t dt; int64_t rs, cs, group, rblk; bool e8m0; inline float grp(int64_t row, int64_t g) const { const int64_t i = (rblk > 1 ? row / rblk : row) * rs + g * cs; if (e8m0) { const uint8_t e = ((const uint8_t*)p)[i]; return e == 0xff ? std::nanf("") : std::ldexp(1.0f, (int)e - 127); } return rad_load_f32(p, dt, i); } }; static Scales make_scales(const RadTensor* s, int64_t rows, int64_t K, bool mxfp4_weight) { Scales q{}; q.rblk = 1; if (!s || !s->data || rows <= 0 || numel(s) <= 0) { q.p = nullptr; q.group = K; q.dt = RAD_F32; return q; } q.p = s->data; q.dt = s->dtype; /* libref's reading, block for block: a rank-2 stream with fewer rows than the operand is a * block grid whatever the remainder, and a flat stream shorter than the row count is one * scale per block of rows rather than a per-row stream to read past its end. */ int64_t groups = 0; if (s->rank >= 2) { const int64_t srows = s->shape[s->rank - 2]; q.rblk = srows >= rows ? 1 : grid_block(rows, srows); groups = s->shape[s->rank - 1]; q.rs = s->stride[s->rank - 2]; q.cs = s->stride[s->rank - 1]; } else { const int64_t nel = numel(s); if (nel >= rows) { groups = nel / rows; q.rs = groups; } else { groups = 1; q.rblk = grid_block(rows, nel); q.rs = 1; } q.cs = 1; } q.group = grid_block(K, groups); q.e8m0 = mxfp4_weight && (s->dtype == RAD_U8); return q; } /* ================================================================== packing * A row of an operand, widened into f32 and made contiguous. Returns the caller's own pointer when * the operand is ALREADY dense f32 -- the one case where the pack is skipped entirely, and the * reason a f32 GEMM does not pay for the generality. */ static const float* pack_rows(const Mat& m, int64_t r0, int64_t nrows, int64_t K, float* dst, int64_t ldd) { const RadTensor* t = m.t; if (m.cs == 1 && t->dtype == RAD_F32 && m.rs == ldd) return (const float*)t->data + r0 * m.rs; for (int64_t r = 0; r < nrows; ++r) { const int64_t base = (r0 + r) * m.rs; if (m.cs == 1) { const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1 : (t->dtype == RAD_I2) ? 3 : 0; if (!sub || (base & sub) == 0) { row_to_f32(t->dtype, byte_at(t->data, t->dtype, base), dst + r * ldd, K); continue; } } for (int64_t k = 0; k < K; ++k) dst[r * ldd + k] = ld_elem(t->data, t->dtype, base + k * m.cs); } return dst; } /* ================================================================== the driver * * `SB`/`SA` null means the unquantised family, which is the same loop with one group of width K * and both scales 1 -- so there is one driver and not two. The grouped form accumulates the * sub-sum from the RAW CODES and scales once at the end of the group, which is what an int8 WMMA * kernel does and what libref does; folding the scales into every product instead would be a * different number in the last bits and the checker would blame the kernel for the choice. */ static int gemm_drive(const Mat& ma, const Mat& mb, const Scales* SA, const Scales* SB, const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N, int64_t K) { const int64_t ys_r = row_stride(Y, N); const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; const int64_t g = (SB && SB->p && SB->group > 0) ? SB->group : K; const int64_t ngrp = (K + g - 1) / g; /* An activation grid FINER than the weight's cannot have its scale hoisted out of the group. * No format in this project has one; the branch exists so that a format that did would be * refused rather than silently mis-scaled. */ const bool coarse_a = !SA || !SA->p || SA->group >= g; if (!coarse_a) return RAD_E_UNSUPPORTED; /* ================================================== THE M BLOCK, AND A NULL RESULT * * The loop nest below is (M block) x (N block) x (K). With the N loop outermost and the whole * of A packed, every one of the N/NR n-blocks walks the ENTIRE packed A, so at M=512, K=2048 * that is a 4 MiB panel re-read 341 times: 1.4 GiB of traffic to do 4.3 GFLOP. Blocking M so * the panel stays resident is the textbook fix, and the traffic argument predicts a large win. * * MEASURED, AND THE PREDICTION DOES NOT HOLD HERE. gemm_nt bf16 at M=512, N=2048, K=2048, * AVX-512, one thread, sweeping the panel target: * * 128 KiB 26.0 ms 4 MiB 25.4 ms * 256 KiB 23.4 ms 16 MiB 25.4 ms * 1 MiB 24.0 ms 256 MiB 25.0 ms (= no blocking at this shape) * * Six percent, not the several-fold the traffic argument implies -- and at M=64 it is WORSE * (2.85 ms unblocked against 2.91 at 256 KiB), because there the block splits a batch that did * not need splitting and B gets packed twice. * * THE REASON IS THE PART. The measurement above comes from one with 128 MiB of L3, where the * 4 MiB A panel never leaves cache however many times it is walked -- so the traffic the * blocking removes is served at L3 bandwidth and not DRAM's. On a part with a 32 MiB L3 * the same argument still holds; on one with 8 MiB the blocking is the several-fold win the * theory predicts. It is kept because it is never much worse and is much better on hardware * the measurement above cannot represent -- but it is recorded here as a SIX PERCENT effect on * a large-cache part, and not as the fix it looks like. * * THE BLOCK SIZE IS COMPUTED FROM K, NOT TUNED: the panel is MB x K floats against a fixed * byte target. There is nothing to search -- unlike a GPU tile it does not interact with an * occupancy limit -- which is why avx_registry.cpp declares no tunable axes. The target is * stated rather than probed from CPUID because the cache descriptors there are a fiction on * more parts than they are a fact, and the sweep above shows the curve is flat enough that * being wrong about it costs ten percent rather than an order. */ enum { AVX_L2_PANEL = 256 * 1024 }; int64_t MB = (int64_t)AVX_L2_PANEL / ((int64_t)K * (int64_t)sizeof(float)); if (MB < MR) MB = MR; if (MB > M) MB = M; const int64_t lda = K; float* apack = (float*)scratch_raw((size_t)MB * (size_t)K * sizeof(float) + 64); const int64_t nblocks = (N + NR - 1) / NR; for (int64_t mb0 = 0; mb0 < M; mb0 += MB) { const int64_t mrows = (M - mb0) < MB ? (M - mb0) : MB; /* Packed on the calling thread, before the parallel region: every worker reads it, and * nothing inside the region touches this arena, so the pointer cannot move under them. */ const float* Ap = pack_rows(ma, mb0, mrows, K, apack, lda); AVX_PARALLEL_FOR_IF(mrows * N * K >= 65536) for (int64_t nb = 0; nb < nblocks; ++nb) { const int64_t n0 = nb * NR; const int64_t nn = (N - n0) < NR ? (N - n0) : NR; const int64_t ldb = K; float* bbuf = scratch_f32((size_t)NR * (size_t)K); const float* Bp = pack_rows(mb, n0, nn, K, bbuf, ldb); for (int64_t m0 = 0; m0 < mrows; m0 += MR) { const int64_t mm = (mrows - m0) < MR ? (mrows - m0) : MR; float acc[MR][NR]; for (int i = 0; i < MR; ++i) for (int j = 0; j < NR; ++j) acc[i][j] = 0.0f; for (int64_t gi = 0; gi < ngrp; ++gi) { const int64_t k0 = gi * g, k1 = (k0 + g < K) ? k0 + g : K; if (mm == MR && nn == NR) { float sub[MR][NR]; for (int i = 0; i < MR; ++i) for (int j = 0; j < NR; ++j) sub[i][j] = 0.0f; dot_block(Ap + m0 * lda, lda, Bp, ldb, k0, k1, sub); for (int j = 0; j < NR; ++j) { const float sb = (SB && SB->p) ? SB->grp(n0 + j, gi) : 1.0f; for (int i = 0; i < MR; ++i) { const float sa = (SA && SA->p) ? SA->grp(mb0 + m0 + i, k0 / SA->group) : 1.0f; acc[i][j] += sub[i][j] * sa * sb; } } } else { for (int64_t j = 0; j < nn; ++j) { const float sb = (SB && SB->p) ? SB->grp(n0 + j, gi) : 1.0f; for (int64_t i = 0; i < mm; ++i) { const float sa = (SA && SA->p) ? SA->grp(mb0 + m0 + i, k0 / SA->group) : 1.0f; acc[i][j] += dot1(Ap + (m0 + i) * lda, Bp + j * ldb, k0, k1) * sa * sb; } } } } for (int64_t i = 0; i < mm; ++i) for (int64_t j = 0; j < nn; ++j) { float v = acc[i][j]; if (bias) v += ldt(bias, (n0 + j) * laststride(bias)); stt(Y, (mb0 + m0 + i) * ys_r + (n0 + j) * ys_c, v); } } } } return RAD_OK; } /* ================================================================== the bf16 outer-product path * * AN ENCODER'S GEMM IS ALL PREFILL: M is the step's whole token count, thousands of rows, every * launch. The driver above is shaped for decode -- it packs A on the calling thread one M block at * a time and re-widens each weight row into f32 once per M block -- and at M = 3000, K = 2048 that * is the weight widened a hundred times over, behind a single-threaded pack, for 0.14 TFLOPS on a * 16-core part. * * Where both operands are bf16 with unit element stride and the CPU has AVX512_BF16 (Zen 4 on, * Cooper Lake and Sapphire Rapids on), this path runs instead, and it is the OUTER-PRODUCT form * this file otherwise argues against -- because here M is large enough to pay for the one thing * that argument says it costs, a pack of B: * * B is packed ONCE A CALL, in parallel, into panels of 48 columns in vdpbf16ps's pair layout, * Bp[panel][K/2][48][2]: one k-pair of 48 columns is three zmm, read contiguously. Columns past * N and the second half of an odd K's last pair are zeros. * The microkernel is 8 rows of A by one panel: per k-pair, three panel loads, eight 32-bit * broadcasts of A's (k, k+1) pair, 24 vdpbf16ps into 24 accumulators. NO HORIZONTAL REDUCTION * anywhere -- each accumulator lane is one output element -- and a row is stored as three * 16-wide vectors. * Threads take tiles of (64 rows) x (up to four panels), dynamically. Within a tile the panel * loop is outer, so a panel (K x 96 bytes: 48 KiB at K = 512, 192 KiB at K = 2048) stays in L2 * while the tile's row blocks stream through it. * * MEASURED on a 9950X3D, 16 threads, M = 2048: 6.9 TFLOPS at N = 4096, K = 512 and 6.1 at * N = 512, K = 2048. The dot-product form -- vdpbf16ps along K straight out of both rows, 4 x 6 * blocks -- reached 1.5 at both: at K = 512 a block does sixteen k steps and then 24 sixteen-lane * reductions, so the reductions were most of its instruction stream. Below 128 rows the per-call * pack is not paid back, and that form (gemm_bf16_dot) still runs there. * * It is one instruction stream inside the AVX-512 object, compiled for the extra feature with a * function attribute and entered only after __builtin_cpu_supports says the CPU has it: an * AVX-512 part without BF16 takes the driver above, unchanged. * * THE ARITHMETIC: products of bf16 pairs in f32, accumulated per output in k order two at a time, * with bf16 denormals read as zero (the instruction's DAZ); the bias is the accumulator's start * and the store rounds to nearest even. A different summation order from the driver's, inside the * checker's bf16 tolerance like every vectorised reduction here. Each output element is computed * by one thread, so the result does not depend on the thread count. */ #if AVX_LEVEL == 3 #define AVX_BF16_TARGET __attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16"))) constexpr int64_t BP_COLS = 48; /* columns a panel: three zmm of f32 accumulators */ constexpr int64_t BP_MR = 8; /* rows of A a microkernel */ /* f32 -> bf16 round-to-nearest-even, sixteen lanes, a NaN kept a (quiet) NaN: the scalar * converter's arithmetic, vectorised. */ AVX_BF16_TARGET static inline __m256i bf16_rne16(__m512 x) { const __m512i u = _mm512_castps_si512(x); const __m512i lsb = _mm512_and_si512(_mm512_srli_epi32(u, 16), _mm512_set1_epi32(1)); __m512i r = _mm512_srli_epi32(_mm512_add_epi32(_mm512_add_epi32(u, _mm512_set1_epi32(0x7fff)), lsb), 16); const __mmask16 nan = _mm512_cmpgt_epu32_mask(_mm512_and_si512(u, _mm512_set1_epi32(0x7fffffff)), _mm512_set1_epi32(0x7f800000)); r = _mm512_mask_mov_epi32(r, nan, _mm512_or_si512(_mm512_srli_epi32(u, 16), _mm512_set1_epi32(0x40))); return _mm512_cvtepi32_epi16(r); } /* MR_ rows of A against one packed panel, over all of K, stored to the panel's `cols` columns of * Y rows 0..MR_-1 (Y already offset to the block's first element). `bv` starts the accumulators: * the bias, or zeros. */ template AVX_BF16_TARGET static inline void op_block(const uint16_t* A, int64_t lda, const uint16_t* panel, int64_t K, const __m512* bv, void* Y, int64_t ys_r, bool yb, int64_t cols) { __m512 acc[MR_][3]; #pragma GCC unroll 8 for (int i = 0; i < MR_; ++i) { acc[i][0] = bv[0]; acc[i][1] = bv[1]; acc[i][2] = bv[2]; } const int64_t kp_full = K / 2; const uint16_t* bp = panel; for (int64_t kp = 0; kp < kp_full; ++kp, bp += 2 * BP_COLS) { const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)bp); const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 32)); const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 64)); #pragma GCC unroll 8 for (int i = 0; i < MR_; ++i) { uint32_t pr; std::memcpy(&pr, A + i * lda + 2 * kp, 4); const __m512bh av = (__m512bh)_mm512_set1_epi32((int)pr); acc[i][0] = _mm512_dpbf16_ps(acc[i][0], av, b0); acc[i][1] = _mm512_dpbf16_ps(acc[i][1], av, b1); acc[i][2] = _mm512_dpbf16_ps(acc[i][2], av, b2); } } if (K & 1) { /* The odd last k: A's element alone in the pair's low half, never the one past the row. */ const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)bp); const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 32)); const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 64)); #pragma GCC unroll 8 for (int i = 0; i < MR_; ++i) { const __m512bh av = (__m512bh)_mm512_set1_epi32((int)(uint32_t)A[i * lda + K - 1]); acc[i][0] = _mm512_dpbf16_ps(acc[i][0], av, b0); acc[i][1] = _mm512_dpbf16_ps(acc[i][1], av, b1); acc[i][2] = _mm512_dpbf16_ps(acc[i][2], av, b2); } } /* Every accumulator index is a constant, so the block never leaves the registers. */ auto mask = [&](int64_t c0) { const int64_t w = cols - c0 <= 0 ? 0 : (cols - c0 < 16 ? cols - c0 : 16); return (__mmask16)((1u << w) - 1); }; const __mmask16 m0 = mask(0), m1 = mask(16), m2 = mask(32); #pragma GCC unroll 8 for (int i = 0; i < MR_; ++i) { if (yb) { uint16_t* yr = (uint16_t*)Y + i * ys_r; _mm256_mask_storeu_epi16(yr, m0, bf16_rne16(acc[i][0])); _mm256_mask_storeu_epi16(yr + 16, m1, bf16_rne16(acc[i][1])); _mm256_mask_storeu_epi16(yr + 32, m2, bf16_rne16(acc[i][2])); } else { float* yr = (float*)Y + i * ys_r; _mm512_mask_storeu_ps(yr, m0, acc[i][0]); _mm512_mask_storeu_ps(yr + 16, m1, acc[i][1]); _mm512_mask_storeu_ps(yr + 32, m2, acc[i][2]); } } } /* THE SMALL-M FORM: vdpbf16ps along K straight out of both rows, 4 x 6 blocks, no pack. The pack * in gemm_bf16_dp touches every weight once a call -- 250 MB a forward pass for EmbeddingGemma * 2 -- which an encoder step of thousands of rows amortises and a single 16-token query does not: * there the outer-product path took a query from 13 to 17 ms. The pack pays for itself where the rows it * serves are many; by the measured rates (1.5 against 6 TFLOPS, the pack streaming at memory * speed) that is from about 75 rows, and 128 is the switch. */ template AVX_BF16_TARGET static inline void dp_block(const uint16_t* A, int64_t lda, const uint16_t* B, int64_t ldb, int64_t K, float out[MB_][NB_]) { __m512 acc[MB_][NB_]; for (int i = 0; i < MB_; ++i) for (int j = 0; j < NB_; ++j) acc[i][j] = _mm512_setzero_ps(); int64_t k = 0; for (; k + 32 <= K; k += 32) { __m512bh av[MB_]; for (int i = 0; i < MB_; ++i) av[i] = (__m512bh)_mm512_loadu_si512((const void*)(A + i * lda + k)); for (int j = 0; j < NB_; ++j) { const __m512bh bv = (__m512bh)_mm512_loadu_si512((const void*)(B + j * ldb + k)); for (int i = 0; i < MB_; ++i) acc[i][j] = _mm512_dpbf16_ps(acc[i][j], av[i], bv); } } if (k < K) { const __mmask32 mk = (__mmask32)((1ull << (K - k)) - 1); __m512bh av[MB_]; for (int i = 0; i < MB_; ++i) av[i] = (__m512bh)_mm512_maskz_loadu_epi16(mk, (const void*)(A + i * lda + k)); for (int j = 0; j < NB_; ++j) { const __m512bh bv = (__m512bh)_mm512_maskz_loadu_epi16(mk, (const void*)(B + j * ldb + k)); for (int i = 0; i < MB_; ++i) acc[i][j] = _mm512_dpbf16_ps(acc[i][j], av[i], bv); } } for (int i = 0; i < MB_; ++i) for (int j = 0; j < NB_; ++j) out[i][j] = _mm512_reduce_add_ps(acc[i][j]); } static inline uint16_t f32_bf16_rne(float f) { uint32_t u; std::memcpy(&u, &f, 4); if ((u & 0x7f800000u) == 0x7f800000u && (u & 0x007fffffu)) return (uint16_t)((u >> 16) | 0x40u); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } AVX_BF16_TARGET static void gemm_bf16_dot(const uint16_t* A, int64_t lda, const uint16_t* B, int64_t ldb, const RadTensor* Y, int64_t ys_r, const RadTensor* bias, int64_t M, int64_t N, int64_t K) { const bool yb = Y->dtype == RAD_BF16; /* The tile grid: 64 rows of A by a column count chosen so there are at least four tiles a * thread, capped at 192 columns. */ constexpr int64_t BMR = 4, BNR = 6, MC = 64; const int64_t mt = (M + MC - 1) / MC; #ifdef _OPENMP const int64_t nth = (int64_t)avx_team_size(); #else const int64_t nth = 1; #endif int64_t want_nt = (4 * nth + mt - 1) / mt; if (want_nt < 1) want_nt = 1; int64_t NC = (N + want_nt - 1) / want_nt; NC = ((NC + BNR - 1) / BNR) * BNR; if (NC > 192) NC = 192; if (NC < BNR) NC = BNR; const int64_t ntl = (N + NC - 1) / NC; auto store = [&](int64_t m, int64_t n, float v) { if (bias) v += ldt(bias, n * laststride(bias)); if (yb) ((uint16_t*)Y->data)[m * ys_r + n] = f32_bf16_rne(v); else ((float*)Y->data)[m * ys_r + n] = v; }; #ifdef _OPENMP #pragma omp parallel for schedule(dynamic, 1) num_threads(avx_team_size()) #endif for (int64_t t = 0; t < mt * ntl; ++t) { const int64_t m_lo = (t / ntl) * MC, n_lo = (t % ntl) * NC; const int64_t m_hi = m_lo + MC < M ? m_lo + MC : M; const int64_t n_hi = n_lo + NC < N ? n_lo + NC : N; for (int64_t n0 = n_lo; n0 < n_hi; n0 += BNR) { const int64_t nn = n_hi - n0 < BNR ? n_hi - n0 : BNR; for (int64_t m0 = m_lo; m0 < m_hi; m0 += BMR) { const int64_t mm = m_hi - m0 < BMR ? m_hi - m0 : BMR; if (mm == BMR && nn == BNR) { float o[BMR][BNR]; dp_block(A + m0 * lda, lda, B + n0 * ldb, ldb, K, o); for (int i = 0; i < BMR; ++i) for (int j = 0; j < BNR; ++j) store(m0 + i, n0 + j, o[i][j]); } else { for (int64_t i = 0; i < mm; ++i) for (int64_t j = 0; j < nn; ++j) { float o[1][1]; dp_block<1, 1>(A + (m0 + i) * lda, lda, B + (n0 + j) * ldb, ldb, K, o); store(m0 + i, n0 + j, o[0][0]); } } } } } } /* A bf16 x bf16 product into Y, or false when this path does not apply and the driver should run. */ AVX_BF16_TARGET static bool gemm_bf16_dp(const Mat& ma, const Mat& mb, const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N, int64_t K) { static const bool have = __builtin_cpu_supports("avx512bf16"); if (!have || M < 16) return false; if (ma.t->dtype != RAD_BF16 || mb.t->dtype != RAD_BF16 || ma.cs != 1 || mb.cs != 1) return false; if (Y->dtype != RAD_BF16 && Y->dtype != RAD_F32) return false; const int64_t ys_r = row_stride(Y, N); const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; if (ys_c != 1) return false; const uint16_t* A = (const uint16_t*)ma.t->data; const uint16_t* B = (const uint16_t*)mb.t->data; const int64_t lda = ma.rs, ldb = mb.rs; if (M < 128) { gemm_bf16_dot(A, lda, B, ldb, Y, ys_r, bias, M, N, K); return true; } const bool yb = Y->dtype == RAD_BF16; const size_t yel = yb ? 2 : 4; /* ---- the pack, into the calling thread's arena before any worker reads it */ const int64_t np = (N + BP_COLS - 1) / BP_COLS; const int64_t kp_n = (K + 1) / 2; const int64_t pstride = kp_n * 2 * BP_COLS; /* uint16 a panel */ uint16_t* Bp = (uint16_t*)scratch_raw((size_t)(np * pstride) * sizeof(uint16_t) + 64); #ifdef _OPENMP #pragma omp parallel for schedule(static) num_threads(avx_team_size()) if(np * pstride >= 65536) #endif for (int64_t p = 0; p < np; ++p) { uint32_t* dst = (uint32_t*)(Bp + p * pstride); const int64_t n0 = p * BP_COLS; for (int64_t c = 0; c < BP_COLS; ++c) { const int64_t n = n0 + c; if (n >= N) { for (int64_t kp = 0; kp < kp_n; ++kp) dst[kp * BP_COLS + c] = 0; continue; } const uint16_t* row = B + n * ldb; for (int64_t kp = 0; kp < K / 2; ++kp) { uint32_t pr; std::memcpy(&pr, row + 2 * kp, 4); dst[kp * BP_COLS + c] = pr; } if (K & 1) dst[(kp_n - 1) * BP_COLS + c] = (uint32_t)row[K - 1]; } } /* ---- the tile grid: 64-row M blocks by groups of panels, at least four tiles a thread */ constexpr int64_t MC = 64; const int64_t mt = (M + MC - 1) / MC; #ifdef _OPENMP const int64_t nth = (int64_t)avx_team_size(); #else const int64_t nth = 1; #endif int64_t groups = (4 * nth + mt - 1) / mt; if (groups < 1) groups = 1; int64_t PG = (np + groups - 1) / groups; if (PG > 4) PG = 4; if (PG < 1) PG = 1; const int64_t ng = (np + PG - 1) / PG; #ifdef _OPENMP #pragma omp parallel for schedule(dynamic, 1) num_threads(avx_team_size()) #endif for (int64_t t = 0; t < mt * ng; ++t) { const int64_t m_lo = (t / ng) * MC, p_lo = (t % ng) * PG; const int64_t m_hi = m_lo + MC < M ? m_lo + MC : M; const int64_t p_hi = p_lo + PG < np ? p_lo + PG : np; for (int64_t p = p_lo; p < p_hi; ++p) { const int64_t n0 = p * BP_COLS; const int64_t cols = N - n0 < BP_COLS ? N - n0 : BP_COLS; __m512 bv[3]; for (int v = 0; v < 3; ++v) { alignas(64) float bb[16]; for (int e = 0; e < 16; ++e) { const int64_t n = n0 + 16 * v + e; bb[e] = (bias && n < N) ? ldt(bias, n * laststride(bias)) : 0.0f; } bv[v] = _mm512_load_ps(bb); } const uint16_t* panel = Bp + p * pstride; for (int64_t m0 = m_lo; m0 < m_hi; m0 += BP_MR) { const int64_t mm = m_hi - m0 < BP_MR ? m_hi - m0 : BP_MR; const uint16_t* Ar = A + m0 * lda; void* Yr = (char*)Y->data + (size_t)(m0 * ys_r + n0) * yel; switch (mm) { case 8: op_block<8>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; case 7: op_block<7>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; case 6: op_block<6>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; case 5: op_block<5>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; case 4: op_block<4>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; case 3: op_block<3>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; case 2: op_block<2>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; default: op_block<1>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break; } } } } return true; } #endif /* Shared entry for gemm_nt / gemm_nt_bias / logits_gemm. `nkey`/`kkey` name which parameters carry * N and K, because logits_gemm spells them n_vocab and n_embd. */ /* gemm_nt_bias's epilogue (docs/OPS.md): an activation of the stored product, then a residual, * each step read back from and stored to the output's dtype -- the unfused chain, as libref has it. */ static void gemm_epilogue(const RadTensor* Y, const RadTensor* res, int act, int64_t M, int64_t N) { const int64_t ys = laststride(Y), yr = Y->rank >= 2 ? Y->stride[Y->rank - 2] : N; const int64_t rs = res ? laststride(res) : 0, rr = res && res->rank >= 2 ? res->stride[res->rank - 2] : N; AVX_PARALLEL_FOR_IF(M * N >= AVX_PAR_MIN) for (int64_t m = 0; m < M; ++m) for (int64_t n = 0; n < N; ++n) { const int64_t o = m * yr + n * ys; float v = ldt(Y, o); if (act == 1) { v = 0.5f * v * (1.0f + std::erf(v * 0.70710678118654752f)); stt(Y, o, v); } else if (act == 2) { v = 0.5f * v * (1.0f + std::tanh(0.7978845608028654f * (v + 0.044715f * v * v * v))); stt(Y, o, v); } if (res) stt(Y, o, ldt(res, m * rr + n * rs) + ldt(Y, o)); } } static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, const char* kkey) { /* gemm_nt_bias is a, b, bias, res?, y; the other two are a, b, y. */ const int nt = bias_operand ? 5 : 3; if (a->n_t < nt || !a->t[0].data || !a->t[1].data || !a->t[nt - 1].data) return RAD_E_INVAL; const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[nt - 1]; const RadTensor* bias = bias_operand ? rad_arg_in(a, 2) : nullptr; const RadTensor* res = bias_operand ? rad_arg_in(a, 3) : nullptr; static const char* kActs[] = { "none", "gelu", "gelu_tanh" }; const int act = bias_operand ? p_enum(a, "act", kActs, 3, 0) : 0; const int64_t K = p_int(a, kkey, B->rank >= 2 ? B->shape[B->rank - 1] : 0); const int64_t N = p_int(a, nkey, B->rank >= 2 ? B->shape[B->rank - 2] : 0); if (K <= 0 || N <= 0) return RAD_E_SHAPE; const int64_t M = numel(Y) / N; if (M <= 0) return RAD_E_SHAPE; if (numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE; if (bias && numel(bias) < N) return RAD_E_SHAPE; if (res && numel(res) < M * N) return RAD_E_SHAPE; const Mat ma = as_mat(A, K), mb = as_mat(B, K); #if AVX_LEVEL == 3 if (!gemm_bf16_dp(ma, mb, Y, bias, M, N, K)) #endif { const int st = gemm_drive(ma, mb, nullptr, nullptr, Y, bias, M, N, K); if (st < 0) return st; } if (act || res) gemm_epilogue(Y, res, act, M, N); return RAD_OK; } static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) { const int nt = bias_operand ? 6 : 5; if (a->n_t < nt || !a->t[0].data || !a->t[2].data || !a->t[nt - 1].data) return RAD_E_INVAL; const RadTensor *A = &a->t[0], *B = &a->t[2], *Y = &a->t[nt - 1]; const RadTensor* as_ = rad_arg_in(a, 1); const RadTensor* bs_ = rad_arg_in(a, 3); const RadTensor* bias = bias_operand ? rad_arg_in(a, 4) : nullptr; const int64_t K = p_int(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0); const int64_t N = p_int(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0); if (K <= 0 || N <= 0) return RAD_E_SHAPE; const int64_t M = numel(Y) / N; if (M <= 0) return RAD_E_SHAPE; if (numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE; if (bias && numel(bias) < N) return RAD_E_SHAPE; const bool mx = B->dtype == RAD_FP4E2M1; Scales SA = make_scales(as_, M, K, false); Scales SB = make_scales(bs_, N, K, mx); /* `group` is what the SELECTOR matches on; the loop uses the group the scale stream actually * implies. They agree in every well-formed call, and where they do not the stream is the one * that describes the bytes -- so a disagreement is refused rather than silently resolved. */ const int64_t gp = p_int(a, "group", 0); if (gp > 0 && SB.p && SB.group != gp) return RAD_E_SHAPE; const Mat ma = as_mat(A, K), mb = as_mat(B, K); return gemm_drive(ma, mb, &SA, &SB, Y, bias, M, N, K); } AVX_KERNEL(gemm_nt) { return gemm_nt_impl(a, false, "N", "K"); } AVX_KERNEL(gemm_nt_bias) { return gemm_nt_impl(a, true, "N", "K"); } AVX_KERNEL(gemm_nt_q) { return gemm_ntq_impl(a, false); } AVX_KERNEL(gemm_nt_q_bias) { return gemm_ntq_impl(a, true); } /* ------------------------------------------------------------------ gemm_nt_q_gated */ /* gemm_nt_q over a [N, K] gate_up plane -- N is the WEIGHT's rows, twice the fused width, gate half * first -- with gated_quant_fp8 as the epilogue; the output is [M, N/2]. * * BYTE-IDENTICAL TO THE PAIR IT STANDS FOR, gemm_nt_q into a bf16 [M, N] tensor and then * gated_quant_fp8 over it. The product is gemm_drive's, the same driver at the same blocking; both * halves are narrowed to bf16 by the ABI's own converter, which is what gemm_nt_q's element store * does to a bf16 output; and the gate and the codes are avx_had.h's, which gated_quant_fp8 runs. * Taking either half off the f32 accumulator instead would be a different function. * * The f32 plane between the two is materialised whole, in a buffer the calling thread keeps: the * driver parallelises over the plane's columns, and the epilogue over its rows. `act` is REQUIRED * here where the quantiser defaults it -- an implementation may compile one gate, and a default * would let it resolve for the other. */ AVX_KERNEL(gemm_nt_q_gated) { if (a->n_t < 6) return RAD_E_INVAL; const RadTensor *A = &a->t[0], *B = &a->t[2], *q = &a->t[4], *s = &a->t[5]; const RadTensor* as_ = rad_arg_in(a, 1); const RadTensor* bs_ = rad_arg_in(a, 3); const RadTensor* ob = rad_arg_in(a, 6); if (!A->data || !B->data || !q->data || !s->data) return RAD_E_INVAL; const int64_t K = p_int(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0); const int64_t N = p_int(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0); if (K <= 0 || N <= 0 || (N & 1)) return RAD_E_SHAPE; const int64_t n = N / 2; static const char* kActs[] = { "silu", "sigmoid" }; const int act = p_enum(a, "act", kActs, 2, -1); if (act != 0 && act != 1) return RAD_E_INVAL; int64_t g = p_int(a, "group", 0); if (g <= 0 || g > n) g = n; const int64_t ngrp = (n + g - 1) / g; const int64_t M = numel(q) / n; if (M <= 0 || numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE; if (numel(s) < M * ngrp) return RAD_E_SHAPE; if (ob && numel(ob) < M * n) return RAD_E_SHAPE; const bool mx = B->dtype == RAD_FP4E2M1; const Scales SA = make_scales(as_, M, K, false); const Scales SB = make_scales(bs_, N, K, mx); const Mat ma = as_mat(A, K), mb = as_mat(B, K); static thread_local std::vector plane; if (plane.size() < (size_t)(M * N)) plane.resize((size_t)(M * N)); RadTensor Y{}; Y.data = plane.data(); Y.dtype = RAD_F32; Y.rank = 2; Y.shape[0] = M; Y.shape[1] = N; Y.stride[0] = N; Y.stride[1] = 1; const int rc = gemm_drive(ma, mb, &SA, &SB, &Y, nullptr, M, N, K); if (rc != RAD_OK) return rc; const float* P = plane.data(); AVX_PARALLEL_FOR_IF(M * N >= AVX_PAR_MIN) for (int64_t m = 0; m < M; ++m) { float* row = scratch_f32((size_t)N); float* out = scratch_f32_b((size_t)n); float* tmp = scratch_f32_c((size_t)n); for (int64_t j = 0; j < N; ++j) row[j] = rad_bf16_to_f32(rad_f32_to_bf16(P[m * N + j])); gate_bf16(row, row + n, out, n, act, tmp); fp8_emit(out, tmp, n, g, q, s, ob, m); } return RAD_OK; } /* The same arithmetic as gemm_nt, and a separate op anyway: lm_head is its own access class * (RAD_ACCESS_VOCAB) and the sampler wants to fuse against it, so the two have to be selectable * apart even when one kernel serves both. N and K are spelled n_vocab and n_embd. */ AVX_KERNEL(logits_gemm) { return gemm_nt_impl(a, false, "n_vocab", "n_embd"); } /* ================================================================== the vocabulary edges * * A gather, not a GEMM. A NEGATIVE token id writes a ZERO ROW -- the padding convention a batch * with a short sequence needs. `vocab_offset` makes the table this rank's slice of a vocab-parallel * embedding: ids stay GLOBAL, one outside the slice writes a zero row, and summing the ranks * reconstructs x. * * WITHOUT AN OFFSET AN ID AT OR ABOVE n_vocab STILL FAILS THE LAUNCH, because there it is a caller * bug rather than another rank's token and a plausible embedding is the worst possible answer. * With one, this kernel cannot know the global vocabulary, so the bound is the caller's. */ template static int embed_impl(const RadArgs* a) { const int nt = QUANT ? 4 : 3; /* embed_lookup_q's scale (operand 2) is optional; everything else must be there. */ for (int i = 0; i < nt; ++i) if (!(QUANT && i == 2) && !rad_arg_in(a, i)) return RAD_E_INVAL; const RadTensor* tok = &a->t[0]; const RadTensor* wte = &a->t[1]; const RadTensor* sc = QUANT ? &a->t[2] : nullptr; const RadTensor* x = &a->t[nt - 1]; const int64_t n_embd = p_int(a, "n_embd", wte->rank >= 2 ? wte->shape[wte->rank - 1] : 0); const int64_t n_vocab = p_int(a, "n_vocab", wte->rank >= 2 ? wte->shape[wte->rank - 2] : 0); const int64_t voff = p_int(a, "vocab_offset", 0); if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return RAD_E_SHAPE; const int64_t M = numel(x) / n_embd; if (M <= 0 || numel(tok) < M || numel(wte) < n_vocab * n_embd) return RAD_E_SHAPE; /* An absent scale is one (ref_embed_lookup_q says why the op allows it). embed_lookup's * `mult` is the same multiply, a parameter instead of a table scale. */ const float scale = QUANT ? (sc->data && numel(sc) >= 1 ? ldt(sc, 0) : 1.0f) : p_f32(a, "mult", 1.0f); /* Validated before the loop, because an OpenMP body cannot return. */ if (voff == 0) for (int64_t m = 0; m < M; ++m) if (ldi(tok, offlin(tok, m)) >= n_vocab) return RAD_E_INVAL; const int64_t ws = wte->rank >= 2 ? wte->stride[wte->rank - 2] : n_embd; const int64_t wc = wte->rank >= 2 ? wte->stride[wte->rank - 1] : 1; /* A ROW COPY WHEN NOTHING HAS TO CHANGE, which for the unquantised gather is the usual case: * the table and the activation are the same dtype and a memcpy moves the row at the width of * the machine instead of through an f32 round trip that would also re-round it. */ const bool copy = !QUANT && scale == 1.0f && wte->dtype == x->dtype && wc == 1 && laststride(x) == 1; const size_t rowb = copy ? (size_t)((rad_dtype_bits(x->dtype) * n_embd) / 8) : 0; AVX_PARALLEL_FOR_IF(M * n_embd >= AVX_PAR_MIN) for (int64_t m = 0; m < M; ++m) { const int64_t id = ldi(tok, offlin(tok, m)) - voff; const int64_t xb = rowoff(x, m, n_embd), xs = laststride(x); const bool have_row = id >= 0 && id < n_vocab; if (copy) { void* dst = (void*)byte_at(x->data, x->dtype, xb); if (have_row) std::memcpy(dst, byte_at(wte->data, wte->dtype, id * ws), rowb); else std::memset(dst, 0, rowb); continue; } float* s = scratch_f32((size_t)n_embd); if (!have_row) { for (int64_t i = 0; i < n_embd; ++i) s[i] = 0.0f; } else if (wc == 1) { row_to_f32(wte->dtype, byte_at(wte->data, wte->dtype, id * ws), s, n_embd); if (scale != 1.0f) { const vf vs = vf_set1(scale); int64_t i = 0; for (; i + VF_N <= n_embd; i += VF_N) vf_storeu(s + i, vf_mul(vf_loadu(s + i), vs)); for (; i < n_embd; ++i) s[i] *= scale; } } else { for (int64_t i = 0; i < n_embd; ++i) s[i] = ld_elem(wte->data, wte->dtype, id * ws + i * wc) * scale; } if (xs == 1) out_row(x, xb, n_embd, s); else for (int64_t i = 0; i < n_embd; ++i) stt(x, xb + i * xs, s[i]); } return RAD_OK; } AVX_KERNEL(embed_lookup) { return embed_impl(a); } /* ================================================================== the E4M3 table into bf16 * * The form a model serves -- an E4M3 table, a bf16 activation -- is a gather whose rows are usually * not in memory, and avx_ngram.cpp is where they come from: a row cache shared by every thread, a * direct read for each miss, a reader a step ahead. What stays here is the part that is this * level's: turning a row of codes into bf16 through the call's 256-entry table. * * AT AVX-512 THE TABLE LIVES IN EIGHT REGISTERS. 256 bf16 are 512 bytes; vpermt2w indexes 64 words * across a register pair, so four of them look every code up in its quarter and the code's top two * bits pick the quarter -- a dozen instructions for 32 codes, against 32 dependent loads. Below * AVX-512 the table has no in-register form (vpshufb indexes 16 bytes and a gather issues one load * a lane, the null result in README.md), so those levels look a code up at a time. * * EVERY ROW IS A CACHE MISS, so each row's lines are requested kAhead rows before its decode: * a batch is thousands of rows scattered over the row cache, and a decode that waited for each * row's lines in turn would spend its time on the memory latency rather than the lookups. */ static void decode_e4m3_rows(const uint8_t* const* src, uint16_t* const* dst, int64_t count, int64_t n, const uint16_t* lut) { constexpr int64_t kAhead = 8; #if AVX_LEVEL >= 3 __m512i t[8]; for (int k = 0; k < 8; ++k) t[k] = _mm512_loadu_si512((const void*)(lut + 32 * k)); const __m512i bit6 = _mm512_set1_epi16(0x40), bit7 = _mm512_set1_epi16(0x80); auto pick = [&](__m512i ix) { const __m512i q0 = _mm512_permutex2var_epi16(t[0], ix, t[1]); const __m512i q1 = _mm512_permutex2var_epi16(t[2], ix, t[3]); const __m512i q2 = _mm512_permutex2var_epi16(t[4], ix, t[5]); const __m512i q3 = _mm512_permutex2var_epi16(t[6], ix, t[7]); const __mmask32 h6 = _mm512_test_epi16_mask(ix, bit6); const __mmask32 h7 = _mm512_test_epi16_mask(ix, bit7); return _mm512_mask_blend_epi16(h7, _mm512_mask_blend_epi16(h6, q0, q1), _mm512_mask_blend_epi16(h6, q2, q3)); }; #endif for (int64_t r = 0; r < count; ++r) { if (r + kAhead < count) { const uintptr_t p = (uintptr_t)src[r + kAhead]; for (uintptr_t q = p & ~(uintptr_t)63; q < p + (uintptr_t)n; q += 64) __builtin_prefetch((const void*)q); } const uint8_t* s = src[r]; uint16_t* d = dst[r]; #if AVX_LEVEL >= 3 int64_t i = 0; for (; i + 32 <= n; i += 32) { const __m512i ix = _mm512_cvtepu8_epi16(_mm256_loadu_si256((const __m256i*)(s + i))); _mm512_storeu_si512((void*)(d + i), pick(ix)); } if (i < n) { const __mmask32 k = (__mmask32)((1u << (n - i)) - 1u); const __m512i ix = _mm512_cvtepu8_epi16(_mm256_maskz_loadu_epi8(k, s + i)); _mm512_mask_storeu_epi16((void*)(d + i), k, pick(ix)); } #else for (int64_t i = 0; i < n; ++i) d[i] = lut[s[i]]; #endif } } /* A bf16 table's rows ARE their output: the decode is a copy, and the row cache in front of it is * the whole of the work, as it is for the E4M3 table. */ static void decode_bf16_rows(const uint8_t* const* src, uint16_t* const* dst, int64_t count, int64_t n, const uint16_t*) { for (int64_t r = 0; r < count; ++r) std::memcpy(dst[r], src[r], (size_t)n * sizeof(uint16_t)); } /* The call in avx_ngram.cpp's form, or false: i32 ids, a dense E4M3 table with its scale or a * dense bf16 table without one, bf16 rows at one pitch. */ static bool rows_form(const RadArgs* a, RowGather* g) { /* The scale is optional, so it is not part of what must be present. */ if (!rad_arg_in(a, 0) || !rad_arg_in(a, 1) || !rad_arg_in(a, 3)) return false; const RadTensor* tok = &a->t[0]; const RadTensor* wte = &a->t[1]; const RadTensor* sc = &a->t[2]; const RadTensor* x = &a->t[3]; if (tok->dtype != RAD_I32 || !rad_tensor_is_contiguous(tok)) return false; if (!rad_tensor_is_contiguous(wte)) return false; const bool e4m3 = wte->dtype == RAD_F8E4M3; if (!e4m3 && wte->dtype != RAD_BF16) return false; const bool scaled = sc->data && numel(sc) >= 1; if (x->dtype != RAD_BF16 || scaled != e4m3) return false; const int64_t n_embd = p_int(a, "n_embd", wte->rank >= 2 ? wte->shape[wte->rank - 1] : 0); const int64_t n_vocab = p_int(a, "n_vocab", wte->rank >= 2 ? wte->shape[wte->rank - 2] : 0); if (n_embd <= 0 || n_vocab <= 0) return false; int64_t ld = -1; if (rad_tensor_is_contiguous(x)) ld = n_embd; else if (x->rank == 2 && x->shape[1] == n_embd && x->stride[1] == 1) ld = x->stride[0]; if (ld < n_embd) return false; g->ids = (const int32_t*)tok->data; g->M = numel(x) / n_embd; g->tab = (const uint8_t*)wte->data; g->n_vocab = n_vocab; g->n_embd = n_embd; g->voff = p_int(a, "vocab_offset", 0); g->scale = e4m3 ? ldt(sc, 0) : 1.0f; g->row_bytes = e4m3 ? n_embd : 2 * n_embd; g->out = (uint16_t*)x->data; g->x_ld = ld; const RadTensor* ahd = rad_arg_in(a, 4); const bool ahead = ahd && ahd->dtype == RAD_I32 && rad_tensor_is_contiguous(ahd) && numel(ahd); g->ahead = ahead ? (const int32_t*)ahd->data : nullptr; g->n_ahead = ahead ? numel(ahd) : 0; g->rank = a->rank; g->world_size = a->world_size; return true; } AVX_KERNEL(embed_lookup_q) { RowGather g; if (!rows_form(a, &g)) return embed_impl(a); if (g.voff < 0 || g.M <= 0 || numel(&a->t[0]) < g.M || numel(&a->t[1]) < g.n_vocab * g.n_embd) return RAD_E_SHAPE; /* Checked before the gather, not inside it: a refusal halfway through would leave the output * half written and the step would carry on over it. The bound is embed_impl's -- with an offset * an id outside this rank's slice is another rank's row and writes a zero one. */ if (g.voff == 0) for (int64_t m = 0; m < g.M; ++m) if ((int64_t)g.ids[m] >= g.n_vocab) return RAD_E_INVAL; return row_gather(g, g.row_bytes == g.n_embd ? decode_e4m3_rows : decode_bf16_rows); }