Skip to content

A 2.78-trillion-parameter Kimi K3 running inference on a single CPU in 8.24 GB of RAM. Portable C99: no BLAS, no framework, no GPU.

perf(mxfp4): flat-row AVX2 path when group is a multiple of 16

Fareed Khanae3b9e907dc7
diff --git a/src/core/k3_ops.c b/src/core/k3_ops.c
index 6946c79..673c3bc 100644
--- a/src/core/k3_ops.c
+++ b/src/core/k3_ops.c
@@ -1102,8 +1102,6 @@ void k3_matmul_bf16(float *y, const float *x, const uint16_t *W, int in, int out
__m256d v0 = _mm256_setzero_pd(), v1 = _mm256_setzero_pd();
__m256d v2 = _mm256_setzero_pd(), v3 = _mm256_setzero_pd();
for (; i + 15 < in; i += 16) {
- /* bf16 -> f32 is a 16-bit left shift, so widen u16 to u32, shift,
- * and reinterpret. No table, no rounding. */
const __m128i h0 = _mm_loadl_epi64((const __m128i *)(row + i));
const __m128i h1 = _mm_loadl_epi64((const __m128i *)(row + i + 4));
const __m128i h2 = _mm_loadl_epi64((const __m128i *)(row + i + 8));
@@ -1254,9 +1252,13 @@ static void k3_e8m0_init(void)
* - A scale byte of 255 is NaN by the OCP MX spec and zeroes its whole group.
*
* ACCURACY CONTRACT. This kernel is deliberately NOT bit-identical to
- * dequantise-then-k3_matmul, and no caller should assume it is. It sums each group of
- * 32 and applies that group's scale before accumulating; dequantise-then-matmul sums
- * every term of the row under one set of accumulators. The orders differ.
+ * dequantise-then-k3_matmul, and no caller should assume it is. On AVX2 with a
+ * group that is a multiple of 16 (K3 uses 32) it runs the FLAT ROW PATH below: the
+ * E8M0 power-of-two scale is folded into each E2M1 weight exactly, and the whole
+ * row is summed by sixteen independent double accumulator lanes (four __m256d).
+ * Otherwise it sums each
+ * group of 32 and applies that group's scale before accumulating. Both orderings
+ * differ from dequantise-then-matmul's single accumulator set.
*
* The difference is bounded and tiny. Every individual product is EXACT in double, an
* E2M1 value carries 3 mantissa bits and x carries 24, so the product needs 27 of the
@@ -1300,6 +1302,105 @@ void k3_matmul_mxfp4(float *y, const float *x, const unsigned char *packed,
const unsigned char *sr = scales + (size_t)r * ngrp;
double acc = 0.0;
+#if defined(__AVX2__)
+ if (xd && (group & 15) == 0) {
+ /* FLAT ROW PATH. Every E8M0 scale is a power of two (K3_E8M0[sb] =
+ * 2^(sb-127), 0 for the NaN byte 255), so folding it into the E2M1 weight
+ * before the FMA is EXACT in fp32: a 3-bit mantissa shifted by an exponent
+ * does not round, and the only overflow case (sb >= 251 times weight 6)
+ * produces inf exactly as the dequantised reference does. That folds the
+ * per-group scale step out of the accumulation, so the whole row is one
+ * flat vectorised dot product: four independent double accumulator chains
+ * v0..v3, a single horizontal reduction at the end, and none of the
+ * per-group scalar reduction, the a[4] store-forwarding, or the serial
+ * `acc` chain that the grouped path below pays once per group.
+ *
+ * The accumulator count is a deliberate trade-off. An earlier version
+ * ran eight chains over 32-element blocks, but eight accumulators plus
+ * the decode temporaries exceed the 16 ymm registers and the compiler
+ * spills one accumulator to the stack every block - reintroducing the
+ * store-forwarding this path exists to avoid. Four chains over 16-element
+ * chunks fit without a spill, and the loop is decode-bound on the shuffle
+ * port (permutevar8x32, cvtepu8_epi32 and cvtps_pd all issue there), not
+ * FMA-latency-bound, so the shorter chain depth is not what limits it.
+ *
+ * Lane k of v0..v3 holds elements == k (mod 16), and the final tree is
+ * ((v0+v2)+(v1+v3)) lane-wise and then (a0+a1)+(a2+a3), the same shape as
+ * the scalar reduction, so every lane holds a sum of the same element
+ * classes in the same order as the dequantised reference and the error
+ * stays a few ulps of double, far inside the 1e-6 gate.
+ *
+ * Requires `group` to be a multiple of 16 so no 16-element chunk straddles
+ * a scale boundary (K3 uses group 32). Anything else takes the grouped path
+ * below, which handles arbitrary group <= 64. */
+ const __m256 LUT = _mm256_setr_ps(0.0f, 0.5f, 1.0f, 1.5f,
+ 2.0f, 3.0f, 4.0f, 6.0f);
+ const __m128i m0f = _mm_set1_epi8(0x0F);
+ const __m256i m07 = _mm256_set1_epi32(7);
+ const __m256i m08 = _mm256_set1_epi32(8);
+ __m256d v0 = _mm256_setzero_pd(), v1 = _mm256_setzero_pd();
+ __m256d v2 = _mm256_setzero_pd(), v3 = _mm256_setzero_pd();
+ int i = 0, g = 0, c = 0;
+ const int cpg = group >> 4; /* 16-element chunks per group */
+
+ for (; i + 15 < in; i += 16) {
+ const unsigned char sb = sr[g];
+ if (sb == 255) goto flat_skip;
+ {
+ const __m256 LUTs = _mm256_mul_ps(
+ LUT, _mm256_set1_ps(K3_E8M0[sb]));
+ const __m128i b = _mm_loadl_epi64(
+ (const __m128i *)(pr + (i >> 1)));
+ const __m128i u = _mm_unpacklo_epi8(
+ _mm_and_si128(b, m0f),
+ _mm_and_si128(_mm_srli_epi16(b, 4), m0f));
+ const __m256i c0 = _mm256_cvtepu8_epi32(u);
+ const __m256i c1 = _mm256_cvtepu8_epi32(_mm_srli_si128(u, 8));
+ const __m256 w0 = _mm256_xor_ps(
+ _mm256_permutevar8x32_ps(LUTs, _mm256_and_si256(c0, m07)),
+ _mm256_castsi256_ps(
+ _mm256_slli_epi32(_mm256_and_si256(c0, m08), 28)));
+ const __m256 w1 = _mm256_xor_ps(
+ _mm256_permutevar8x32_ps(LUTs, _mm256_and_si256(c1, m07)),
+ _mm256_castsi256_ps(
+ _mm256_slli_epi32(_mm256_and_si256(c1, m08), 28)));
+ v0 = _mm256_fmadd_pd(
+ _mm256_cvtps_pd(_mm256_castps256_ps128(w0)),
+ _mm256_loadu_pd(xd + i), v0);
+ v1 = _mm256_fmadd_pd(
+ _mm256_cvtps_pd(_mm256_extractf128_ps(w0, 1)),
+ _mm256_loadu_pd(xd + i + 4), v1);
+ v2 = _mm256_fmadd_pd(
+ _mm256_cvtps_pd(_mm256_castps256_ps128(w1)),
+ _mm256_loadu_pd(xd + i + 8), v2);
+ v3 = _mm256_fmadd_pd(
+ _mm256_cvtps_pd(_mm256_extractf128_ps(w1, 1)),
+ _mm256_loadu_pd(xd + i + 12), v3);
+ }
+ flat_skip:
+ if (++c == cpg) { c = 0; g++; }
+ }
+ {
+ /* Horizontal reduction without touching memory, same tree as the
+ * grouped path: (a0+a1)+(a2+a3). */
+ const __m256d q = _mm256_add_pd(
+ _mm256_add_pd(v0, v2), _mm256_add_pd(v1, v3));
+ const __m128d t = _mm_add_pd(
+ _mm256_castpd256_pd128(q), _mm256_extractf128_pd(q, 1));
+ acc = _mm_cvtsd_f64(_mm_add_sd(t, _mm_unpackhi_pd(t, t)));
+ }
+ /* Scalar tail, at most 15 elements, all inside one group (i is 16-aligned
+ * and group is a multiple of 16, so a tail this short cannot cross a scale
+ * boundary). Scale folded the same way as the vector path. */
+ for (; i < in; i++) {
+ const unsigned char by = pr[i >> 1];
+ const unsigned char nib = (i & 1) ? (by >> 4) : (by & 0x0F);
+ acc = fma((double)(K3_E2M1[nib] * K3_E8M0[sr[i / group]]), xd[i], acc);
+ }
+ y[r] = (float)acc;
+ continue;
+ }
+#endif
for (int g = 0; g < ngrp; g++) {
const unsigned char sb = sr[g];
if (sb == 255) continue; /* NaN scale: contribute nothing */
@@ -1321,22 +1422,22 @@ void k3_matmul_mxfp4(float *y, const float *x, const unsigned char *packed,
xdg = xlocal;
}
- /* Four double lanes partitioned by i%4, reduced as (s0+s1)+(s2+s3), in BOTH
- * the scalar and the AVX2 path so the two agree bit for bit on every
- * machine. The split is written out rather than left to the compiler
- * because a sequential floating-point reduction may not be reassociated
- * without -ffast-math, which this build does not set: expressed as one
- * serial accumulator, the hottest loop in the engine compiles to scalar
- * adds no matter what the surrounding code looks like.
+ /* Four double lanes partitioned by i%4, reduced as (s0+s1)+(s2+s3), in
+ * the scalar path, so on machines without AVX2 the reduction is the
+ * same on every compiler. The split is written out rather than left to
+ * the compiler because a sequential floating-point reduction may not be
+ * reassociated without -ffast-math, which this build does not set:
+ * expressed as one serial accumulator, the hottest loop in the engine
+ * compiles to scalar adds no matter what the surrounding code looks
+ * like.
*
- * The lane split changes the summation order. See the accuracy contract on
- * the function above for why that is bounded at ~1e-16 relative. */
- /* Two fused vector accumulators over the 32-element group, element i to
- * accumulator (i/4)%2, lanewise-summed then cross-lane paired; the scalar
- * path is the identical partition with fma(), which is the same IEEE
- * operation, so both paths stay bit-identical. Same reasoning as the
- * fp32/bf16 kernels above; the group is short, so two accumulators
- * suffice to break the add-latency chain. */
+ * The lane split changes the summation order. See the accuracy contract
+ * on the function above for why that is bounded at ~1e-16 relative. */
+ /* The AVX2 grouped path below uses four __m256d accumulators over each
+ * 16-element chunk, so its intra-lane summation order differs from the
+ * scalar path; see the NIBBLE DECODE comment below for the accuracy
+ * contract. The group is short, so four accumulators suffice to break
+ * the add-latency chain. */
double sub;
int i = 0;
#if defined(__AVX2__)
@@ -1354,30 +1455,64 @@ void k3_matmul_mxfp4(float *y, const float *x, const unsigned char *packed,
* XORed in. Code 8 gives 0.0f ^ 0x80000000 = -0.0f, which is what
* K3_E2M1[8] holds, so the negative zero survives.
*
- * BIT-IDENTICAL TO WHAT IT REPLACES, not merely close. The decoded floats
- * are the same table values, and the products still enter the same two
- * accumulators in the same order: wv's low half is elements i..i+3 and
- * its high half i+4..i+7, the same partition the two _mm_loadu_ps of wf
- * produced. The bench FNV1a of the output is unchanged. */
+ * ACCURACY CONTRACT (test_expert.c:219) is maxrel < 1e-6 against
+ * dequant-then-matmul, NOT bit-identity. This grouped path is the
+ * FALLBACK for group not a multiple of 16, or a failed xd hoist; on
+ * the normal K3 shape the flat row path above is taken instead. It
+ * keeps four independent accumulators (v0..v3) to break the FMA
+ * latency chain, so its intra-lane accumulation order differs from
+ * the scalar path below; the difference is a few ulps of double,
+ * orders of magnitude inside the 1e-6 gate. The bench FNV1a of the
+ * mxfp4 output differs from the pre-optimisation value -- that hash
+ * is a determinism check, not a correctness oracle. */
const __m256 LUT = _mm256_setr_ps(0.0f, 0.5f, 1.0f, 1.5f,
2.0f, 3.0f, 4.0f, 6.0f);
const __m128i m0f = _mm_set1_epi8(0x0F);
const __m256i m07 = _mm256_set1_epi32(7);
const __m256i m08 = _mm256_set1_epi32(8);
+ /* 16-element iteration: ONE 8-byte load yields all 16 nibbles, decoded
+ * into c0/c1 by unpacking the low/high nibble masks. Each block feeds its
+ * own accumulator (v0..v3), so per iteration every accumulator chain is a
+ * single FMA -- four independent depth-1 chains hide both the decode
+ * latency and the FMA latency. Group 32 collapses to two iterations. The
+ * scalar tail handles 8-15 and 0-7 remainders. */
__m256d v0 = _mm256_setzero_pd(), v1 = _mm256_setzero_pd();
+ __m256d v2 = _mm256_setzero_pd(), v3 = _mm256_setzero_pd();
+ for (; i + 15 < n; i += 16) {
+ const __m128i b = _mm_loadl_epi64((const __m128i *)(pb + (i >> 1)));
+ const __m128i lo = _mm_and_si128(b, m0f);
+ const __m128i hi = _mm_and_si128(_mm_srli_epi16(b, 4), m0f);
+ /* unpacklo interleaves the low 8 bytes of lo and hi, which together
+ * cover all 16 elements in order: [e0,e1,e2,...,e15]. Split that 16
+ * bytes into the low 8 (elems 0-7) and high 8 (elems 8-15). */
+ const __m128i u16 = _mm_unpacklo_epi8(lo, hi);
+ const __m256i c0 = _mm256_cvtepu8_epi32(u16);
+ const __m256i c1 = _mm256_cvtepu8_epi32(_mm_srli_si128(u16, 8));
+ const __m256 w0 = _mm256_xor_ps(
+ _mm256_permutevar8x32_ps(LUT, _mm256_and_si256(c0, m07)),
+ _mm256_castsi256_ps(
+ _mm256_slli_epi32(_mm256_and_si256(c0, m08), 28)));
+ const __m256 w1 = _mm256_xor_ps(
+ _mm256_permutevar8x32_ps(LUT, _mm256_and_si256(c1, m07)),
+ _mm256_castsi256_ps(
+ _mm256_slli_epi32(_mm256_and_si256(c1, m08), 28)));
+ v0 = _mm256_fmadd_pd(_mm256_cvtps_pd(_mm256_castps256_ps128(w0)),
+ _mm256_loadu_pd(xdg + i), v0);
+ v1 = _mm256_fmadd_pd(_mm256_cvtps_pd(_mm256_extractf128_ps(w0, 1)),
+ _mm256_loadu_pd(xdg + i + 4), v1);
+ v2 = _mm256_fmadd_pd(_mm256_cvtps_pd(_mm256_castps256_ps128(w1)),
+ _mm256_loadu_pd(xdg + i + 8), v2);
+ v3 = _mm256_fmadd_pd(_mm256_cvtps_pd(_mm256_extractf128_ps(w1, 1)),
+ _mm256_loadu_pd(xdg + i + 12), v3);
+ }
+ /* 8-element remainder: same AVX2 decode + FMA as before. Runs at most
+ * once, for the 8-15 remainder after the 16-element loop. */
for (; i + 7 < n; i += 8) {
- /* Eight elements live in four packed bytes. memcpy, not a cast: the
- * row is unaligned and char* -> int32_t* would be a strict-aliasing
- * violation. It compiles to the one movd it looks like. */
int32_t four;
memcpy(&four, pb + (i >> 1), 4);
const __m128i b = _mm_cvtsi32_si128(four);
- /* srli_epi16 crosses the byte boundary, but the mask discards
- * everything it dragged in, so each byte keeps its own high nibble. */
const __m128i lo = _mm_and_si128(b, m0f);
const __m128i hi = _mm_and_si128(_mm_srli_epi16(b, 4), m0f);
- /* Interleave BEFORE widening: low nibble is the even element, high
- * the odd, which is the order K3_E2M1_PAIR encoded. */
const __m256i c = _mm256_cvtepu8_epi32(_mm_unpacklo_epi8(lo, hi));
const __m256 wv = _mm256_xor_ps(
_mm256_permutevar8x32_ps(LUT, _mm256_and_si256(c, m07)),
@@ -1389,7 +1524,8 @@ void k3_matmul_mxfp4(float *y, const float *x, const unsigned char *packed,
_mm256_loadu_pd(xdg + i + 4), v1);
}
double a[4];
- _mm256_storeu_pd(a, _mm256_add_pd(v0, v1));
+ _mm256_storeu_pd(a, _mm256_add_pd(_mm256_add_pd(v0, v2),
+ _mm256_add_pd(v1, v3)));
sub = (a[0] + a[1]) + (a[2] + a[3]);
}
/* Sub-8 remainder, decoded one nibble at a time. K3 never reaches it (group