diff --git a/docs/models/inkling.md b/docs/models/inkling.md index 815746520..d65cd85cb 100644 --- a/docs/models/inkling.md +++ b/docs/models/inkling.md @@ -59,7 +59,8 @@ only part of the experts was not measured. Three runs each, 32 tokens written af On an RTX 20 card (Turing) the engine multiplies the experts as halves while it reads a prompt. With `--prompt-int8` it multiplies them on the int8 tensor cores, as it does on RTX 30 and newer, with the prompt's numbers rounded to 8 -bits with a scale for every 32 (`STRATA_PF_I8MMA=0` turns the int8 products off on every card). It is not the +bits with a scale for every 32 (`STRATA_PF_I8MMA=0` turns the int8 products off on every card). `--prompt-int8` takes the +same kernel on an AMD RDNA3 or RDNA4 card (HIP; `--no-prompt-int8` says the default there too). It is not the default because it moves the answers more: measured on a Quadro RTX 4000 (8 GB), which holds a third to two thirds of the experts, written after the halves' greedy answers to three prompts of 302 to 8,192 tokens, 64 tokens each, with three files (the two below and an IQ3_S), it gives the same most likely token diff --git a/engine/include/strata/kernels/iq_kernels.hpp b/engine/include/strata/kernels/iq_kernels.hpp index dad973cfc..eb7ea0166 100644 --- a/engine/include/strata/kernels/iq_kernels.hpp +++ b/engine/include/strata/kernels/iq_kernels.hpp @@ -204,16 +204,17 @@ bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, const int32_t* bounds, int n_experts, int max_rows, float* Y, int ldy, void* stream); /// The same products on the int8 tensor cores, for matrices of any number of rows (src/kernels/cuda/i8_mma.cuh): /// the weights decoded to int8 a tile at a time, the activations int8 with a scale per 32 values, FP32 sums. -/// CUDA, Ampere and newer (Turing with gemm_iq_i8_turing()). gemm_iq_i8_takes: the current card runs it for K columns of type ty (K a multiple of 256, +/// CUDA, Ampere and newer (Turing with gemm_iq_i8_turing()); HIP, RDNA3 and RDNA4 (gfx11 / gfx12 WMMA, the same sums +/// and so the same bits; with gemm_iq_i8_turing() too). gemm_iq_i8_takes: the current card runs it for K columns of type ty (K a multiple of 256, /// or of 32 for a type of 32-value blocks, MXFP4's too, of 64 for NVFP4; STRATA_PF_I8MMA=0 turns it off). gemm_iq_i8_quantize: row i of xq = row ids[i] of x (row i without ids), ld /// floats a row; xq holds rows * K * 5 / 4 bytes, 16-byte aligned. gemm_iq_i8_grouped: matrix e (n_out rows, /// mat_bytes apart) times rows bounds[e]..bounds[e+1] of an xq of total_rows rows; row i's products go to row ids[i] /// of Y (row i without ids). With `from`, row i is row from[i] of xq. With `at` (n_mats values on the device, /// multiples of 16), matrix e is at W + at[e] in place of W + e * mat_bytes. false: not launched. bool gemm_iq_i8_takes(int ty, int K); -/// The int8 kernel on Turing (sm_75) too, from now on in this process, by m8n8k16 MMAs: the same sums as on Ampere. -/// Off by default, where Turing's products are the halves' (mmq_own.cu); a model's engine turns it on (Inkling 2 -/// with --prompt-int8). +/// The int8 kernel on Turing (sm_75) by m8n8k16 MMAs, and on HIP's RDNA3 / RDNA4, from now on in this process: the same +/// sums as on Ampere. Off by default there, where the products are the halves' (mmq_own.cu); a model's engine turns it +/// on (Inkling 2 with --prompt-int8). void gemm_iq_i8_turing(bool on); /// The int8 kernel also takes type ty, from now on in this process (on false: no longer), for a type it takes only when /// asked: IQ1_S (19) and MXFP4 (39). A model's engine asks for them at load (Inkling 2: IQ1_S with diff --git a/engine/src/kernels/cuda/i8_mma.cu b/engine/src/kernels/cuda/i8_mma.cu index 2199f268d..01a86802b 100644 --- a/engine/src/kernels/cuda/i8_mma.cu +++ b/engine/src/kernels/cuda/i8_mma.cu @@ -2,10 +2,14 @@ // include/strata/kernels/iq_kernels.hpp; the kernel is i8_mma.cuh). A file of their own so that a change to them // builds without iq_kernels.cu. The weight sub-blocks are decoded by i8_expert.cuh, which this file includes as // iq_kernels.cu does, in an anonymous namespace (only what i8_mma.cuh instantiates of it is compiled here). -// CUDA only: a HIP build compiles this file empty and takes iq_kernels.cu's stubs. -#if !defined(__HIPCC__) +// HIP: RDNA3 and RDNA4 (i8_mma.cuh's i8m_wmma); a gfx906 build (wave64) compiles this file empty and takes +// iq_kernels.cu's stubs. +#if !defined(STRATA_HIP_GFX906) #include "strata/kernels/iq_kernels.hpp" #include "strata/kernels/dp4a.hpp" +#if defined(__HIPCC__) +#include "strata/kernels/gfx_arch.hpp" +#endif #include #include diff --git a/engine/src/kernels/cuda/i8_mma.cuh b/engine/src/kernels/cuda/i8_mma.cuh index e3f18b060..164e2f11b 100644 --- a/engine/src/kernels/cuda/i8_mma.cuh +++ b/engine/src/kernels/cuda/i8_mma.cuh @@ -48,12 +48,27 @@ __host__ __device__ constexpr bool i8m_raw_type(int t) { return i8m_raw_bytes(t) // Threads of a block: 512 for the widest tile, 16 warps on a multiprocessor where 8 left the products waiting on their // operands, but for Q4_K and Q5_K (RTX PRO 6000, 2,048 rows: Q3_K experts 620 -> 578 us, IQ4_XS 293 -> 246, Q8_0 [2048 // -> 8192] 309 -> 297; Q4_K [2048 -> 6144] 265 -> 280, Q5_K experts 357 -> 370); 256 otherwise. -__host__ __device__ constexpr int i8m_threads(int t, int nj, int wr = 64) { return wr == 128 || (nj == 8 && t != 12 && t != 13) ? 512 : 256; } +// (HIP: 256, 8 waves, for every tile: i8m_wmma below. RX 9070 XT, Inkling 2 Mini's experts: 512 for the widest +// tile was no faster) +__host__ __device__ constexpr int i8m_threads(int t, int nj, int wr = 64) { +#if defined(__HIPCC__) + return (void) t, (void) nj, (void) wr, 256; +#else + return wr == 128 || (nj == 8 && t != 12 && t != 13) ? 512 : 256; +#endif +} // Weight rows of a block: 128 for IQ3_XXS in the widest tile, each activation row it reads going into twice the // products (RTX PRO 6000, Qwen3.6's experts' gate|up, 2,048 rows: 472 -> 401 us); 64 otherwise (Q4_K [2048 -> 6144] // 253 -> 298, Q3_K experts 579 -> 711, Q8_0 [2048 -> 2048] 82 -> 106 with 128). The block of 128 has 512 threads, // each warp two tiles of 16 weight rows. -__host__ __device__ constexpr int i8m_rows(int t, int nj) { return nj == 8 && t == 18 ? 128 : 64; } +// (HIP: 64, the only block its products are written for) +__host__ __device__ constexpr int i8m_rows(int t, int nj) { +#if defined(__HIPCC__) + return (void) t, (void) nj, 64; +#else + return nj == 8 && t == 18 ? 128 : 64; +#endif +} // Tiles of 16 weight rows a warp multiplies: two for Q8_0, Q4_K and Q5_K in the widest tile (RTX PRO 6000, 2,048 rows: // Q4_K [2048 -> 6144] 265 -> 253 us, LFM2.5's Q4_K experts 647 -> 632, Q8_0 [2048 -> 8192] 297 -> 287), one otherwise // (Q3_K experts 578 -> 642, IQ3_XXS 473 -> 498, Q6_K 345 -> 363 with two). @@ -85,6 +100,7 @@ struct I8mSmem { static constexpr size_t bytes = (size_t) total * 4; }; +#if !defined(__HIPCC__) // (CUDA's MMA, ldmatrix and cp.async; HIP has i8m_wmma below) // (not volatile: a product has no effect but its sums, and the compiler may then move it among the others) // Turing (sm_75) has the int8 MMA only as m8n8k16: an m16n8k32 is four of them and an m16n8k16 two, on the same // operand registers (a0 / a1 the fragment's rows g and g + 8, a2 / a3 its next 16 values; b0 / b1 likewise). The @@ -129,10 +145,14 @@ __device__ __forceinline__ void i8m_ldsm4(uint32_t (&r)[4], const uint32_t* p) { #endif } +#endif + // cp.async: 16 bytes from the card's memory into shared memory, the first n of them read and the rest zeros, without // registers. i8m_cp_wait: this thread's copies have landed. __device__ __forceinline__ void i8m_cp16n(void* s, const void* g, int n) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 +#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ < 800 + (void) s, (void) g, (void) n; // (HIP: never called, RAW is CUDA's) +#else asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" ::"r"((uint32_t) __cvta_generic_to_shared(s)), "l"(g), "r"(n)); #endif } @@ -147,6 +167,87 @@ __device__ __forceinline__ void i8m_cp_wait() { #endif } +// HIP: the products on RDNA3's and RDNA4's int8 matrix cores, v_wmma_i32_16x16x16_iu8 (wave32), 16 activation rows +// (the A operand, the rows of the result) x 16 weight rows (B, its columns) x 16 values a step. A lane gives row +// (lane % 16) of A and of B: on RDNA3 (gfx11) all 16 values, lanes 16-31 the same as lanes 0-15; on RDNA4 (gfx12) the +// 8 values 8 (lane / 16) to 8 (lane / 16) + 7. A lane holds column (lane % 16) of the result, rows 2 i + lane / 16 +// (gfx11) or 8 (lane / 16) + i (gfx12), i = 0..7 (include/strata/kernels/hip_unsloth_wmma.hpp has the same layouts). +// The sums are integers, so the order of the values inside a step is free: on gfx12 a lane takes the 16 bytes +// 16 (lane / 16) .. + 15 of a 32-value block at once, the first 8 for one step and the other 8 for the next. +// A pass for another AMD card compiles the kernel empty (the host asks i8m_card() first). +#if defined(__HIPCC__) && (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || \ + defined(__gfx1150__) || defined(__gfx1151__)) +#define I8M_WMMA 11 +#elif defined(__HIPCC__) && (defined(__gfx1200__) || defined(__gfx1201__)) +#define I8M_WMMA 12 +#else +#define I8M_WMMA 0 +#endif +#if I8M_WMMA +typedef int i8m_v8 __attribute__((ext_vector_type(8))); +#if I8M_WMMA == 12 +typedef int i8m_frag __attribute__((ext_vector_type(2))); +#else +typedef int i8m_frag __attribute__((ext_vector_type(4))); +#endif +__device__ __forceinline__ i8m_v8 i8m_wmma(i8m_frag a, i8m_frag b, i8m_v8 c) { +#if I8M_WMMA == 12 + return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, a, true, b, c, false); +#else + return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, a, true, b, c, false); +#endif +} +// the operand of 16 values at p (a row of s_w or s_x: byte 16 q of a stage, a 16-value part) +__device__ __forceinline__ i8m_frag i8m_frag16(const uint32_t* p, int hi) { +#if I8M_WMMA == 12 + const uint2 v = *(const uint2*) (p + 2 * hi); + return i8m_frag{(int) v.x, (int) v.y}; +#else + (void) hi; + const uint4 v = *(const uint4*) p; + return i8m_frag{(int) v.x, (int) v.y, (int) v.z, (int) v.w}; +#endif +} +// the operands of a 32-value block at p (byte 32 kb of a stage): two steps whose sums together are the block's +__device__ __forceinline__ void i8m_frag32(const uint32_t* p, int hi, i8m_frag& f0, i8m_frag& f1) { +#if I8M_WMMA == 12 + const uint4 v = *(const uint4*) (p + 4 * hi); + f0 = i8m_frag{(int) v.x, (int) v.y}; + f1 = i8m_frag{(int) v.z, (int) v.w}; +#else + (void) hi; + f0 = i8m_frag16(p, 0); + f1 = i8m_frag16(p + 4, 0); +#endif +} +#endif +// A block's barrier. HIP: over LDS only (what the stage loop shares), so that the next stage's reads of the card's +// memory, issued before the products, are not waited for at the barrier (a __syncthreads() is a fence over all memory). +__device__ __forceinline__ void i8m_bar() { +#if I8M_WMMA == 12 + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); + asm volatile("s_wait_dscnt 0x0" ::: "memory"); + __builtin_amdgcn_s_barrier(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); +#elif I8M_WMMA == 11 + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); + __builtin_amdgcn_s_waitcnt(0x7 | (0x3f << 10)); // lgkmcnt(0) only + __builtin_amdgcn_s_barrier(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); +#else + __syncthreads(); +#endif +} +// HIP: where activation row m of a tile's scales is kept, so that a lane's 8 rows of a result (above) are 8 floats in +// a row: gfx12 rows 8 h .. 8 h + 7 as they are; gfx11 rows h, h + 2, ..., h + 14 at 8 h .. 8 h + 7 +__host__ __device__ constexpr int i8m_xpos(int m) { +#if I8M_WMMA == 11 + return (m & ~15) | ((m & 1) << 3) | ((m >> 1) & 7); +#else + return m; +#endif +} + // N 32-bit words from p, which is 2-byte aligned: the aligned words that hold them, joined by a funnel shift (N + 1 // reads where p is not 4-byte aligned, N where it is; the last a 16-bit read, so that nothing past the run is read). // i8_ld32 reads a word as two 16-bit halves, 2 N reads for a run. @@ -417,7 +518,7 @@ __global__ void __launch_bounds__(i8m_threads(T, NJ, WR)) i8m_kernel(const uint8 const float* __restrict__ XS, const int32_t* __restrict__ bounds, int ch_per_e, const int32_t* __restrict__ ids, const int32_t* __restrict__ from, const long long* __restrict__ at, float* __restrict__ Y, long long ldy) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 // (a pass for an older card compiles this empty: the host asks i8m_arch_kernel first) +#if (defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750) || I8M_WMMA // (a pass for an older card compiles this empty: the host asks i8m_arch_kernel / i8m_card first) using SM = I8mSmem; constexpr int MT = SM::MT, LDS = SM::LDS, LDB = SM::LDB, XQ = SM::XQ, XSTR = SM::XSTR; // NT threads. A warp multiplies NA tiles of 16 weight rows (two where the activation rows are many: each piece of @@ -425,6 +526,7 @@ __global__ void __launch_bounds__(i8m_threads(T, NJ, WR)) i8m_kernel(const uint8 // side down the weight rows, CG across the activation rows. constexpr int NT = i8m_threads(T, NJ, WR), NA = i8m_tiles_a(T, NJ, WR), RG = WR / (16 * NA), CG = NT / 32 / RG; constexpr int NJW = 2 * NJ / CG, NX = MT * 16 / NT; + (void) NJW; constexpr int RT = NT / WR; // threads of a weight row: each decodes 8 / RT of its 8 sub-blocks a stage constexpr bool TWO = i8m_two(T), HAS_MIN = i8_min_type(T), MIN16 = i8m_min16(T); constexpr int LDM = SM::LDM, S16 = SM::S16; @@ -484,6 +586,7 @@ __global__ void __launch_bounds__(i8m_threads(T, NJ, WR)) i8m_kernel(const uint8 const bool w_in = n0 + wr < n_out; I8P const blob = I8_GPTR(mat + (size_t) n0 * row_bytes); const uint32_t row_off = (uint32_t) ((size_t) wr * row_bytes); +#if !I8M_WMMA // (HIP: its own tiles, below) // its tensor-core tiles: weight rows i0 + 16 a + g and 8 more, activation rows j0 + g as columns, j0 = 8 (CG n + jp) const int warp = tid >> 5, g = (tid & 31) >> 2, tg = tid & 3; const int i0 = (warp % RG) * 16 * NA, jp = warp / RG; @@ -497,6 +600,7 @@ __global__ void __launch_bounds__(i8m_threads(T, NJ, WR)) i8m_kernel(const uint8 for (int n = 0; n < NJW; ++n) #pragma unroll for (int l = 0; l < 4; ++l) acc[a][n][l] = 0.0f; +#endif // A stage as it is read: this thread's sub-blocks of its weight row, its 16-byte pieces of the activation rows // and its activation scales. @@ -542,22 +646,51 @@ __global__ void __launch_bounds__(i8m_threads(T, NJ, WR)) i8m_kernel(const uint8 } i8m_cp_commit(); } - } else if (w_in) { + } else if (I8M_WMMA || w_in) { #pragma unroll for (int part = 0; part < PER; ++part) { +#if I8M_WMMA + // HIP: every read is made, of a place inside the matrix where the sub-block is not there (put() then + // stores zeros for it), so that no read sits in a branch: the compiler can then count the reads in + // flight and does not wait for all of them (the activations' too) before the next + const bool ok = w_in && here(S, i8m_sub(r0, part)); + const int ib = ok ? i8m_sub(r0, part) : 0; + const int S_ = ok ? S : 0; + const uint32_t row_off_ = w_in ? row_off : 0u; +#else const int ib = i8m_sub(r0, part); if (!here(S, ib)) continue; - if constexpr (T == 11) i8m_q3k_load(blob + row_off, S, ib, wraw[part]); - else if constexpr (T == 10) i8m_q2k_load(blob + row_off, S, ib, wraw[part]); - else if constexpr (T == 8) i8m_q8_load(blob + row_off, S, ib, wraw[part]); - else if constexpr (T == 14) i8m_q6k_load(blob + row_off, S, ib, wraw[part]); - else if constexpr (T == 23) i8m_iq4xs_load(blob + row_off, S, ib, wraw[part]); - else if constexpr (T == 19) i8m_iq1s_load(blob + row_off, S, ib, wraw[part]); - else if constexpr (T == 39) i8m_mxfp4_load(blob + row_off, S, ib, wraw[part]); - else if constexpr (T == 40) i8m_nvfp4_load(blob + row_off, S, ib, wraw[part]); - else i8_load(blob, i8_offs(row_off, ib & 3), 2 * S + (ib >> 2), wraw[part]); + const int S_ = S; + const uint32_t row_off_ = row_off; +#endif + if constexpr (T == 11) i8m_q3k_load(blob + row_off_, S_, ib, wraw[part]); + else if constexpr (T == 10) i8m_q2k_load(blob + row_off_, S_, ib, wraw[part]); + else if constexpr (T == 8) i8m_q8_load(blob + row_off_, S_, ib, wraw[part]); + else if constexpr (T == 14) i8m_q6k_load(blob + row_off_, S_, ib, wraw[part]); + else if constexpr (T == 23) i8m_iq4xs_load(blob + row_off_, S_, ib, wraw[part]); + else if constexpr (T == 19) i8m_iq1s_load(blob + row_off_, S_, ib, wraw[part]); + else if constexpr (T == 39) i8m_mxfp4_load(blob + row_off_, S_, ib, wraw[part]); + else if constexpr (T == 40) i8m_nvfp4_load(blob + row_off_, S_, ib, wraw[part]); + else i8_load(blob, i8_offs(row_off_, ib & 3), 2 * S_ + (ib >> 2), wraw[part]); } } +#if I8M_WMMA // (HIP: no read in a branch, as above; put() zeros what is not there) +#pragma unroll + for (int n = 0; n < NX; ++n) { + const int tok = NT / 16 * n + (tid >> 4), col = S * 256 + (tid & 15) * 16; + const bool ok = tok < ntok && col < K; // (xrow[n] is 0 past ntok) + xr[n] = *(const uint4*) (X + (size_t) xrow[n] * K + (size_t) (ok ? col : 0)); + if constexpr (MIN16) x16[n] = XD[(size_t) xrow[n] * (K / 32) + (ok ? (size_t) S * 8 + ((tid & 15) >> 1) : 0)]; + } +#pragma unroll + for (int c = 0; c < NSC; ++c) { + const int i = tid + c * NT, tok = i >> 3; + const bool ok = i < MT * 8 && tok < ntok && here(S, i & 7); + const size_t at = ok ? (size_t) srow[c] * (K / 32) + (size_t) S * 8 + (i & 7) : 0; + xdr[c] = XD[at]; + if constexpr (HAS_MIN) xsr[c] = XS[at]; + } +#else #pragma unroll for (int n = 0; n < NX; ++n) { // 16 bytes of activation row (NT / 16) n + tid / 16 const int tok = NT / 16 * n + (tid >> 4); @@ -576,6 +709,7 @@ __global__ void __launch_bounds__(i8m_threads(T, NJ, WR)) i8m_kernel(const uint8 if constexpr (HAS_MIN) xsr[c] = XS[at]; } } +#endif }; const auto put = [&](int S) { if constexpr (RAW) { // this thread's sub-blocks out of the raw stage, read as fetch() reads the card's memory @@ -637,11 +771,24 @@ __global__ void __launch_bounds__(i8m_threads(T, NJ, WR)) i8m_kernel(const uint8 } #pragma unroll for (int n = 0; n < NX; ++n) { +#if I8M_WMMA // (fetch() read something in place of what is not there) + { + const int tok = NT / 16 * n + (tid >> 4); + if (!(tok < ntok && S * 256 + (tid & 15) * 16 < K)) { + xr[n] = make_uint4(0, 0, 0, 0); + if constexpr (MIN16) x16[n] = 0.0f; + } + } +#endif *(uint4*) (s_x + (NT / 16 * n + (tid >> 4)) * I8M_LD + (tid & 15) * 4) = xr[n]; if constexpr (MIN16) { // the sum of the thread's 16 codes, times their block's scale const int sum = __dp4a((int) xr[n].w, 0x01010101, __dp4a((int) xr[n].z, 0x01010101, __dp4a((int) xr[n].y, 0x01010101, __dp4a((int) xr[n].x, 0x01010101, 0)))); +#if I8M_WMMA + s_x16[(tid & 15) * S16 + i8m_xpos(NT / 16 * n + (tid >> 4))] = x16[n] * (float) sum; +#else s_x16[(tid & 15) * S16 + NT / 16 * n + (tid >> 4)] = x16[n] * (float) sum; +#endif } } #pragma unroll @@ -649,13 +796,168 @@ __global__ void __launch_bounds__(i8m_threads(T, NJ, WR)) i8m_kernel(const uint8 const int i = tid + c * NT; if (i < MT * 8) { const int tok = i >> 3; +#if I8M_WMMA // HIP: by block, [MT] scales then (a type with a minimum) [MT] scale * sum, a row at i8m_xpos() + const bool ok = tok < ntok && here(S, i & 7); + float* const p = s_xq + (i & 7) * XSTR + i8m_xpos(tok); + p[0] = ok ? xdr[c] : 0.0f; + if constexpr (HAS_MIN) p[MT] = ok ? xsr[c] : 0.0f; +#else float* const p = s_xq + (i & 7) * XSTR + (tok >> 1) * XQ + (tok & 1); p[0] = xdr[c]; if constexpr (HAS_MIN) p[2] = xsr[c]; +#endif } } }; +#if I8M_WMMA + // HIP (i8m_wmma above). The block's 8 waves: WN side by side down the 4 tiles of 16 weight rows, TN tiles each, + // and WM across the activation rows' NJ tiles of 16, TM each, tile wm + WM u (u = 0..TM - 1: the waves in front + // take the first tiles of a block with fewer rows). A product as CUDA's above, term for term: per 32-value block + // (per 16 values for a type with a scale per 16) its integer sum, sum * (weight scale * activation scale) added to + // the float sum, then the minimum's term, the blocks in their order; so the bits are CUDA's. + static_assert((NT == 256 || NT == 512) && WR == 64, "the HIP products are written for 8 or 16 waves and 64 weight rows"); + constexpr int NW = NT / 32, WN = NJ >= 4 && NW == 8 ? 2 : 4, TN = 4 / WN, WM = NJ < NW / WN ? NJ : NW / WN, TM = NJ / WM; + const int lane = tid & 31, l16 = lane & 15, hi = lane >> 4, wave = tid >> 5; + const int wn = wave % WN, wm = wave / WN; + float acc[TM][TN][8]; +#pragma unroll + for (int u = 0; u < TM; ++u) +#pragma unroll + for (int t = 0; t < TN; ++t) +#pragma unroll + for (int i = 0; i < 8; ++i) acc[u][t][i] = 0.0f; + const uint32_t* const b_row = s_w + (16 * wn * TN + l16) * I8M_LD; // this lane's weight row of tile t: + 16 t rows + // FULL: every tile of the wave has rows (the common case), so no tile's test sits among the products + const auto products = [&](auto full) { + constexpr bool FULL = decltype(full)::value; + if constexpr (TWO) { +#pragma unroll 2 + for (int q = 0; q < 16; ++q) { // a 16-value part: one step + i8m_frag B[TN]; + float w[TN], m16[TN]; +#pragma unroll + for (int t = 0; t < TN; ++t) { + const int row = 16 * (wn * TN + t) + l16; + B[t] = i8m_frag16(b_row + 16 * t * I8M_LD + 4 * q, hi); + w[t] = s_ws[row * LDS + q]; + m16[t] = 0.0f; + if constexpr (MIN16) m16[t] = s_m16[row * LDM + q]; + } +#pragma unroll + for (int u = 0; u < TM; ++u) { + const int m0 = 16 * (wm + WM * u); + if (!FULL && m0 >= ntok) break; + const i8m_frag A = i8m_frag16(s_x + (m0 + l16) * I8M_LD + 4 * q, hi); + const float4* const xp = (const float4*) (s_xq + (q >> 1) * XSTR + m0 + 8 * hi); + const float4 xa = xp[0], xb = xp[1]; + const float x[8] = {xa.x, xa.y, xa.z, xa.w, xb.x, xb.y, xb.z, xb.w}; + float sm[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + if constexpr (MIN16) { + const float4* const sp = (const float4*) (s_x16 + q * S16 + m0 + 8 * hi); + const float4 sa4 = sp[0], sb4 = sp[1]; + sm[0] = sa4.x; sm[1] = sa4.y; sm[2] = sa4.z; sm[3] = sa4.w; + sm[4] = sb4.x; sm[5] = sb4.y; sm[6] = sb4.z; sm[7] = sb4.w; + } +#pragma unroll + for (int t = 0; t < TN; ++t) { + const i8m_v8 c = i8m_wmma(A, B[t], i8m_v8{0, 0, 0, 0, 0, 0, 0, 0}); +#pragma unroll + for (int i = 0; i < 8; ++i) { + acc[u][t][i] = fmaf((float) c[i], w[t] * x[i], acc[u][t][i]); + if constexpr (MIN16) acc[u][t][i] = fmaf(m16[t], sm[i], acc[u][t][i]); + } + } + } + } + } else { +#pragma unroll 2 + for (int kb = 0; kb < 8; ++kb) { // a 32-value block: two steps + i8m_frag B0[TN], B1[TN]; + float w[TN], mn[TN]; +#pragma unroll + for (int t = 0; t < TN; ++t) { + const int row = 16 * (wn * TN + t) + l16; + i8m_frag32(b_row + 16 * t * I8M_LD + 8 * kb, hi, B0[t], B1[t]); + mn[t] = 0.0f; + if constexpr (SM::PK) { + const float2 v = *(const float2*) (s_ws + row * LDS + 2 * kb); + w[t] = v.x; + mn[t] = v.y; + } else { + w[t] = s_ws[row * LDS + kb]; + if constexpr (HAS_MIN) mn[t] = s_wm[row * LDB + kb]; + } + } +#pragma unroll + for (int u = 0; u < TM; ++u) { + const int m0 = 16 * (wm + WM * u); + if (!FULL && m0 >= ntok) break; + i8m_frag A0, A1; + i8m_frag32(s_x + (m0 + l16) * I8M_LD + 8 * kb, hi, A0, A1); + const float4* const xp = (const float4*) (s_xq + kb * XSTR + m0 + 8 * hi); + const float4 xa = xp[0], xb = xp[1]; + const float x[8] = {xa.x, xa.y, xa.z, xa.w, xb.x, xb.y, xb.z, xb.w}; + float sm[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + if constexpr (HAS_MIN) { + const float4* const sp = (const float4*) (s_xq + kb * XSTR + MT + m0 + 8 * hi); + const float4 sa4 = sp[0], sb4 = sp[1]; + sm[0] = sa4.x; sm[1] = sa4.y; sm[2] = sa4.z; sm[3] = sa4.w; + sm[4] = sb4.x; sm[5] = sb4.y; sm[6] = sb4.z; sm[7] = sb4.w; + } +#pragma unroll + for (int t = 0; t < TN; ++t) { + i8m_v8 c = i8m_wmma(A0, B0[t], i8m_v8{0, 0, 0, 0, 0, 0, 0, 0}); + c = i8m_wmma(A1, B1[t], c); +#pragma unroll + for (int i = 0; i < 8; ++i) { + acc[u][t][i] = fmaf((float) c[i], w[t] * x[i], acc[u][t][i]); + if constexpr (HAS_MIN) acc[u][t][i] = fmaf(mn[t], sm[i], acc[u][t][i]); + } + } + } + } + } + }; + const auto multiply = [&]() { + if (wm >= WM) return; + if (16 * (wm + WM * (TM - 1)) < ntok) products(std::true_type{}); + else products(std::false_type{}); + }; + (void) LDB; (void) XQ; (void) LDM; (void) S16; + + const int stages = (K + 255) / 256; + fetch(0); + for (int S = 0; S < stages; ++S) { + i8m_bar(); // the stage before is multiplied (and the tables are written) + put(S); + i8m_bar(); + if (S + 1 < stages) fetch(S + 1); // read while this stage is multiplied + multiply(); + } + if (wm >= WM) return; +#pragma unroll + for (int u = 0; u < TM; ++u) { + const int m0 = 16 * (wm + WM * u); + if (m0 >= ntok) break; +#pragma unroll + for (int i = 0; i < 8; ++i) { +#if I8M_WMMA == 12 + const int m = m0 + 8 * hi + i; +#else + const int m = m0 + 2 * i + hi; +#endif + const int id = s_id[m]; + if (id < 0) continue; + float* const out = Y + (size_t) id * (size_t) ldy; +#pragma unroll + for (int t = 0; t < TN; ++t) { + const int n = n0 + 16 * (wn * TN + t) + l16; + if (n < n_out) out[n] = acc[u][t][i]; + } + } + } +#else // The products of a stage. A warp's operands come out of shared memory by ldmatrix, four 8 x 16-byte pieces an // instruction: its two tiles of 16 weight rows (NA = 2) for two 32-value blocks, and an 8-row tile of activations // for the same two, which then goes into the products of both weight tiles; a thread's two activation rows' scales @@ -816,9 +1118,11 @@ __global__ void __launch_bounds__(i8m_threads(T, NJ, WR)) i8m_kernel(const uint8 } } } +#endif // I8M_WMMA #endif } +#if !defined(__HIPCC__) // the architecture the code running on this card was compiled for (a build may hold no pass for the card's own) __global__ void i8m_arch_kernel(int* out) { #if defined(__CUDA_ARCH__) @@ -828,13 +1132,16 @@ __global__ void i8m_arch_kernel(int* out) { #endif } +#endif + struct I8mCard { bool read = false, on = false; int arch = 0; // the architecture of the code it runs (i8m_arch_kernel) size_t shared = 0, shared_sm = 0; // a block's most, a multiprocessor's }; -// gemm_iq_i8_turing(): the kernel also on Turing's code (sm_75), whose products a model asks for +// gemm_iq_i8_turing(): the kernel also where it is off by default, which a model asks for: Turing's code (sm_75) and +// HIP's RDNA3 / RDNA4 std::atomic i8m_turing{false}; // the current card: int8 tensor cores in the code it runs (Ampere's, or Turing's when asked), and the shared memory @@ -846,6 +1153,23 @@ I8mCard i8m_card() { int dev = 0; if (off || cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return I8mCard{}; std::lock_guard lock(mu); +#if defined(__HIPCC__) + // HIP: RDNA3's and RDNA4's matrix cores (i8m_wmma), arch 1100 or 1200; any other AMD card has no pass of the kernel + if (!known[dev].read) { + I8mCard c; + c.read = true; + cudaDeviceProp p; + if (cudaGetDeviceProperties(&p, dev) == cudaSuccess) { + c.arch = gfx_arch_is_gfx12_wmma(p.gcnArchName) ? 1200 : gfx_arch_is_gfx11_wmma(p.gcnArchName) ? 1100 : 0; + c.shared = (size_t) p.sharedMemPerBlock; + c.shared_sm = (size_t) p.maxSharedMemoryPerMultiProcessor; + } + known[dev] = c; + } + I8mCard c = known[dev]; + c.on = c.arch != 0 && i8m_turing.load(std::memory_order_relaxed); + return c; +#else if (!known[dev].read) { I8mCard c; c.read = true; @@ -864,6 +1188,7 @@ I8mCard i8m_card() { I8mCard c = known[dev]; c.on = c.arch >= 800 || (c.arch >= 750 && i8m_turing.load(std::memory_order_relaxed)); return c; +#endif } template @@ -873,7 +1198,7 @@ bool i8m_launch(int dev, dim3 grid, cudaStream_t s, const uint8_t* W, size_t mat constexpr size_t bytes = I8mSmem::bytes; static bool attr[64]; // the attribute belongs to a card (see gemm_iq_f16_grouped) if (!attr[dev]) { - cudaFuncSetAttribute(i8m_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) bytes); + (void) cudaFuncSetAttribute(i8m_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) bytes); attr[dev] = true; } i8m_kernel<<>>(W, mat_bytes, row_bytes, n_out, K, X, XD, XS, bounds, ch, @@ -883,7 +1208,11 @@ bool i8m_launch(int dev, dim3 grid, cudaStream_t s, const uint8_t* W, size_t mat // 64 weight rows a block: 128 measured slower on an RTX PRO 6000 (a dense Q8_0 [2048 -> 8192] times 2,048 rows 0.61 ms // against 0.46, the experts no faster), so only 64 is built +#if defined(__HIPCC__) +#define STRATA_I8M_TILES(X) X(1, 64) X(2, 64) X(4, 64) X(8, 64) // (HIP: i8m_rows()) +#else #define STRATA_I8M_TILES(X) X(1, 64) X(2, 64) X(4, 64) X(8, 64) X(8, 128) +#endif template size_t i8m_tile_bytes(int nj, int wr, bool raw) { @@ -906,19 +1235,33 @@ bool i8m_launch_type(const I8mCard& card, int dev, cudaStream_t s, const uint8_t // two blocks to one: 6% slower). (The blocks a multiprocessor by shared memory, 1 KB of it the system's a block.) static const bool raw_on = [] { const char* v = std::getenv("STRATA_I8M_RAW"); return v == nullptr || v[0] != '0'; }(); const auto per_sm = [&](size_t b) { return card.shared_sm / (b + 1024); }; - // (Turing has no cp.async to copy it with) - const bool raw = raw_on && card.arch >= 800 && i8m_raw_type(T) && K % 256 == 0 && (uintptr_t) W % 16 == 0 && + // (Turing has no cp.async to copy it with, nor has HIP) +#if defined(__HIPCC__) + constexpr bool kRaw = false; +#else + constexpr bool kRaw = i8m_raw_type(T); +#endif + const bool raw = kRaw && raw_on && card.arch >= 800 && i8m_raw_type(T) && K % 256 == 0 && (uintptr_t) W % 16 == 0 && (i8m_raw_bytes(T) % 16 != 0 || (row_bytes % 16 == 0 && mat_bytes % 16 == 0)) && i8m_tile_bytes(nj, wr, true) <= card.shared && per_sm(i8m_tile_bytes(nj, wr, true)) >= per_sm(i8m_tile_bytes(nj, wr, false)); while (nj > 1 && i8m_tile_bytes(nj, wr, raw) > card.shared) nj /= 2; if (i8m_tile_bytes(nj, wr, raw) > card.shared) return false; const long long ch = (max_rows + 16 * nj - 1) / (16 * nj), gy = (long long) n_mats * ch; - if (gy > 65535) return false; + // More blocks than the grid's y side holds (65,535): the matrices in runs of launches. A row's product does not + // depend on its launch, and the bounds are rows of the whole xq, so each run takes its matrices' bounds and places. + if (gy > 65535) { + const int per = (int) (65535 / ch); + for (int m0 = 0; m0 < n_mats; m0 += per) + if (!i8m_launch_type(card, dev, s, at ? W : W + (size_t) m0 * mat_bytes, mat_bytes, row_bytes, n_out, K, X, XD, XS, + bounds + m0, n_mats - m0 < per ? n_mats - m0 : per, max_rows, ids, from, at ? at + m0 : nullptr, Y, ldy)) + return false; + return true; + } const dim3 grid((unsigned) ((n_out + wr - 1) / wr), (unsigned) gy); #define STRATA_I8M_GO(NJ_, WR_) \ if (nj == NJ_ && wr == WR_) \ - return raw ? i8m_launch(dev, grid, s, W, mat_bytes, row_bytes, n_out, K, X, XD, XS, \ + return raw ? i8m_launch(dev, grid, s, W, mat_bytes, row_bytes, n_out, K, X, XD, XS, \ bounds, (int) ch, ids, from, at, Y, ldy) \ : i8m_launch(dev, grid, s, W, mat_bytes, row_bytes, n_out, K, X, XD, XS, bounds, (int) ch, \ ids, from, at, Y, ldy); diff --git a/engine/src/kernels/cuda/iq_kernels.cu b/engine/src/kernels/cuda/iq_kernels.cu index 390fdde8d..f44384dd2 100644 --- a/engine/src/kernels/cuda/iq_kernels.cu +++ b/engine/src/kernels/cuda/iq_kernels.cu @@ -8461,7 +8461,7 @@ bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, } } // namespace strata::kernels -#if defined(__HIPCC__) +#if defined(STRATA_HIP_GFX906) // (i8_mma.cu is empty there; the other HIP builds have it on RDNA3 / RDNA4) namespace strata::kernels { bool gemm_iq_i8_takes(int, int) { return false; } void gemm_iq_i8_turing(bool) {} diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index ab0e27454..a204ef2fb 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -131,9 +131,9 @@ struct Options { std::string attn_requant; ///< Inkling 2: its attention's six matrices quantized again to this type at load ///< (q4_0, q5_0 or iq4_nl; --attn-requant); empty: the file's types bool loop_bf16 = false; ///< Inkling 2: its loop controllers' matrices in BF16, not the file's F32 (--loop-bf16) - int prompt_int8 = -1; ///< Inkling 2: on Turing its prompt products on the int8 tensor cores, as on Ampere - ///< (gemm_iq_i8_turing()); -1: the default, off; 1: --prompt-int8; 0: --no-prompt-int8, - ///< Turing's halves and cuBLAS + int prompt_int8 = -1; ///< Inkling 2: on Turing and AMD's RDNA3 / RDNA4 its prompt products on the int8 tensor + ///< cores, as on Ampere (gemm_iq_i8_turing()); -1: the default, off; 1: --prompt-int8; + ///< 0: --no-prompt-int8, the halves and BLAS float cache_bias = 0; ///< a token's few-at-a-time routing adds this to the score of each expert in VRAM ///< before it picks its experts; their weights stay the router's own ///< (--cache-bias, qwen35moe and inkling2_loop, route_cached()); 0: the router's own diff --git a/engine/src/poly/inkling2.cpp b/engine/src/poly/inkling2.cpp index c20d37404..c5732f67d 100644 --- a/engine/src/poly/inkling2.cpp +++ b/engine/src/poly/inkling2.cpp @@ -226,8 +226,8 @@ void Inkling2::load_geometry() { if (attn_type_) guess_type_ = attn_type_; ctrl_bf16_ = opt_.loop_bf16; #if !defined(STRATA_GPU_METAL) - // Turing's prompt products on the int8 kernel that Ampere and newer take by default (i8_mma.cuh), only with - // --prompt-int8: on Turing it gave the same most likely token as the halves at 560 of 576 steps (97.2%), under + // Turing's and RDNA3 / RDNA4's prompt products on the int8 kernel that Ampere and newer take by default + // (i8_mma.cuh), only with --prompt-int8: on Turing it gave the same most likely token as the halves at 560 of 576 steps (97.2%), under // the 97.8% a default change needs, so the halves and cuBLAS stay Turing's default (STRATA_PF_I8MMA=0 turns the // kernel off on every card) kernels::gemm_iq_i8_turing(opt_.prompt_int8 == 1); diff --git a/engine/src/poly/main.cpp b/engine/src/poly/main.cpp index e7eff913c..9d7d40f30 100644 --- a/engine/src/poly/main.cpp +++ b/engine/src/poly/main.cpp @@ -1756,12 +1756,13 @@ void usage() { " says the default (the last --attn-requant counts)\n" " --loop-bf16 Inkling 2: its loop controllers' matrices in BF16, not F32;\n" " --no-loop-bf16 says the default (F32; the last one counts)\n" - " --prompt-int8 Inkling 2 on an RTX 20 (Turing): its prompt products on the int8 tensor\n" - " cores as on RTX 30 and newer, not as halves and cuBLAS (the default on\n" - " Turing): faster prompts, and the answers move more, activations int8 a\n" - " 32 values; --no-prompt-int8 says the default; STRATA_PF_I8MMA=0 turns the\n" - " int8 kernel off on every card; with it, a prompt batch's experts in VRAM\n" - " go in one launch a class of rows, the same numbers in fewer launches\n" + " --prompt-int8 Inkling 2 on an RTX 20 (Turing) or an AMD RDNA3 / RDNA4 card: its prompt\n" + " products on the int8 tensor cores as on RTX 30 and newer, not as halves\n" + " and cuBLAS / BLAS (the default there): faster prompts, and the answers\n" + " move more, activations int8 a 32 values; --no-prompt-int8 says the\n" + " default; STRATA_PF_I8MMA=0 turns the int8 kernel off on every card; on\n" + " Turing with it, a prompt batch's experts in VRAM go in one launch a class\n" + " of rows, the same numbers in fewer launches\n" " (STRATA_POLY_EXPERT_TILES=0: a launch a run of slots again)\n" " --skip-weight F in place of --tail-skip: an expert outside VRAM that every token of a\n" " window weighs under F of its experts' weight is left out (default 0 = off)\n" diff --git a/engine/src/poly/mmq_own.cu b/engine/src/poly/mmq_own.cu index 8fd1a4f45..d6558e333 100644 --- a/engine/src/poly/mmq_own.cu +++ b/engine/src/poly/mmq_own.cu @@ -32,6 +32,8 @@ // block-scaled FP4 tensor cores instead, the activations two FP4 terms under a float a row (nvfp4_x2.hpp, about 8 // bits against a half's 11), its products straight to dst's rows and its rows read by index as the int8 ones are. // NVFP4 takes the int8 kernel only with STRATA_PREFILL_NVFP4=w4a8 (nvfp4_w4a8()), on any card that has it. +// +// HIP, with --prompt-int8 (gemm_iq_i8_turing()): the int8 kernel on RDNA3 / RDNA4 too, NVFP4 included, as on Ampere. #include "mmq.hpp" #if STRATA_POLY_X2 #include "nvfp4_x2.hpp" @@ -284,9 +286,29 @@ bool nvfp4_w4a8() { return asked; } +#ifdef STRATA_MMQ_OWN_HIP +// The int8 kernel on RDNA3's and RDNA4's matrix cores (i8_mma.cuh's i8m_wmma), for the types and rows it takes, in +// place of the FP16 tiles or the BLAS loop: opt-in with --prompt-int8 (Inkling 2), as on Turing; STRATA_PF_I8MMA=0 turns +// it off for every model. The activations are int8 a 32 values where the halves keep 11 bits, as on CUDA's Ampere and +// newer by default (the same kernel's numbers, bit for bit). NVFP4 goes with it unless STRATA_PREFILL_NVFP4 names a +// mode (w4a8: the same; any other: the halves). +bool nvfp4_default() { + static const bool unset = [] { + const char* v = std::getenv("STRATA_PREFILL_NVFP4"); + return !v || !*v; + }(); + return unset; +} +#endif + // the int8 kernel takes a matrix of this type with rows this long, whatever their number bool int8_rows(int t, int64_t cols) { - return !blas_only() && cols <= 0x7fffffff && (t != 40 || nvfp4_w4a8()) && kernels::gemm_iq_i8_takes(t, (int) cols); +#ifdef STRATA_MMQ_OWN_HIP + const bool nv4 = nvfp4_w4a8() || nvfp4_default(); +#else + const bool nv4 = nvfp4_w4a8(); +#endif + return !blas_only() && cols <= 0x7fffffff && (t != 40 || nv4) && kernels::gemm_iq_i8_takes(t, (int) cols); } // the rows' halves, then a float a row (back) diff --git a/engine/src/poly/mmq_paths_test.cu b/engine/src/poly/mmq_paths_test.cu index be6ffa00d..db6270fa4 100644 --- a/engine/src/poly/mmq_paths_test.cu +++ b/engine/src/poly/mmq_paths_test.cu @@ -17,10 +17,12 @@ // long enough (whole blocks cut from a model's tensor), in place of ggml's quantization of random weights. // With STRATA_PREFILL_NVFP4=w4a8 NVFP4 takes the int8 tiles where the card has them, and is checked as the int8 types are. // -// usage: poly_mmq_paths_test [--turing-int8] (--turing-int8: the int8 path on Turing too, gemm_iq_i8_turing(); exit 0: every product within 2% RMS of the reference, and an int8 product within +// usage: poly_mmq_paths_test [--turing-int8] (--turing-int8: the int8 path on Turing and on HIP too, gemm_iq_i8_turing(); exit 0: every product within 2% RMS of the reference, and an int8 product within // 1e-5 RMS of its own numbers; 77: no card). Rows of 2,048 values for every type, then rows of 1,152 (Inkling 2's // experts' downs) for Q8_0, IQ4_NL and NVFP4. Where a row's product does not depend on its launch // (Mmq::split_exact()), 100 of the dense rows multiplied as a launch of their own give the same bits. +// Where the int8 tiles take a type, also matrices of 500 rows (not whole tiles of 64) times 10, 20 and 256 rows, +// four experts of 10 rows at most, and (Q8_0) 70,000 one-row matrices by offset, more blocks than a grid's y side. #include "mmq.hpp" #include "ggml.h" #include "strata/kernels/iq_kernels.hpp" @@ -35,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -71,6 +74,47 @@ Err compare(const std::vector& y, const std::vector& ref, int64_t return {std::sqrt(se / std::max(sr, 1e-300)), me / std::max(mr, 1e-300)}; } +// STRATA_MMQ_TEST_DUMP=DIR: an int8 product's floats as they are, DIR/__.bin, and one line a +// type in DIR/inputs.txt with an FNV-1a hash of its weights' and activations' bytes; so that two cards' products +// (CUDA's and HIP's int8 tiles) can be compared bit for bit on the same inputs. STRATA_MMQ_TEST_REF=DIR: each such +// product is also compared with DIR's file of the same name (another card's dump), and the test fails where one is +// missing or differs, or where DIR/inputs.txt's line for the type is not this run's. +const char* dump_dir() { + static const char* d = std::getenv("STRATA_MMQ_TEST_DUMP"); + return d && *d ? d : nullptr; +} +const char* ref_dir() { + static const char* d = std::getenv("STRATA_MMQ_TEST_REF"); + return d && *d ? d : nullptr; +} +int ref_same = 0, ref_bad = 0; +// against the reference dump of the same name: false where it is missing or differs +bool ref_check(const std::string& name, const void* p, size_t n) { + if (!ref_dir()) return true; + std::ifstream f(std::string(ref_dir()) + "/" + name, std::ios::binary); + std::vector r((std::istreambuf_iterator(f)), std::istreambuf_iterator()); + const bool same = f.is_open() && r.size() == n && std::memcmp(r.data(), p, n) == 0; + if (same) ++ref_same; + else { + ++ref_bad; + std::printf("reference %s: %s\n", name.c_str(), f.is_open() ? "OTHER BYTES" : "MISSING"); + } + return same; +} +uint64_t fnv(const void* p, size_t n, uint64_t h = 1469598103934665603ull) { + for (size_t i = 0; i < n; ++i) h = (h ^ ((const uint8_t*) p)[i]) * 1099511628211ull; + return h; +} +// (false: the reference has other bytes) +bool dump(const char* type, int64_t k, const char* what, const std::vector& y) { + const std::string name = std::string(type) + "_" + std::to_string(k) + "_" + what + ".bin"; + if (dump_dir()) { + std::ofstream f(std::string(dump_dir()) + "/" + name, std::ios::binary); + f.write((const char*) y.data(), (std::streamsize) (y.size() * sizeof(float))); + } + return ref_check(name, y.data(), y.size() * sizeof(float)); +} + } // namespace int main(int argc, char** argv) { @@ -83,7 +127,7 @@ int main(int argc, char** argv) { const char* forced = std::getenv("STRATA_POLY_PROMPT_BLAS"); std::printf("path: %s\n", forced && forced[0] == '1' ? "BLAS (STRATA_POLY_PROMPT_BLAS=1)" : "the card's"); // the 32-value types, the K-quants, the i-quants, MXFP4, NVFP4 - const std::vector types_2048 = {2, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 29, 39, 40}; + const std::vector types_2048 = {2, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 29, 39, 40, 42}; const std::vector types_1152 = {8, 20, 40}; const int asked[] = {19, 39}; // the types the int8 tiles take only when asked for (int t : asked) strata::kernels::gemm_iq_i8_allow(t, true); @@ -180,6 +224,24 @@ int main(int argc, char** argv) { if (int8) reference(r, 0, true, &ref8[(size_t) (r * kOut)]); } const Err dense = compare(y, ref, kTokens, kOut, kOut); + bool ref_ok = true; // (STRATA_MMQ_TEST_REF: every product of this type as the reference's) + if (int8 && (dump_dir() || ref_dir())) { + char line[160]; + std::snprintf(line, sizeof line, "%s %lld weights %llx activations %llx", ggml_type_name(ty), (long long) kIn, + (unsigned long long) fnv(wq.data(), wq.size()), (unsigned long long) fnv(x.data(), x.size() * sizeof(float))); + if (dump_dir()) std::ofstream(std::string(dump_dir()) + "/inputs.txt", std::ios::app) << line << "\n"; + if (ref_dir()) { // the reference's inputs must be these + std::ifstream f(std::string(ref_dir()) + "/inputs.txt"); + bool found = false; + for (std::string l; std::getline(f, l);) found = found || l == line; + if (!found) { + std::printf("reference inputs for %s %lld: NOT THESE\n", ggml_type_name(ty), (long long) kIn); + ++ref_bad; + ref_ok = false; + } + } + ref_ok = dump(ggml_type_name(ty), kIn, "dense", y) && ref_ok; + } // rows 37 to 136 as a launch of their own bool apart = true; if (Mmq::split_exact(t, kOut)) { @@ -196,6 +258,7 @@ int main(int argc, char** argv) { Mmq::quantize(dx, nullptr, xq, t, kIn, kIn, kTokens, nullptr); mmq.mul(dw, t, kOut, kIn, mat, kExperts, xq, dbounds, dperm, kTokens, 149, dy, kOut, nullptr); if (!ok(cudaMemcpy(y.data(), dy, y.size() * sizeof(float), cudaMemcpyDeviceToHost), "experts' product")) return 1; + if (int8) ref_ok = dump(ggml_type_name(ty), kIn, "experts", y) && ref_ok; std::vector back((size_t) (kTokens * kOut)); for (int e = 0; e < kExperts; ++e) for (int64_t r = bounds_h[e]; r < bounds_h[e + 1]; ++r) { @@ -276,6 +339,7 @@ int main(int argc, char** argv) { mmq.mul(dw, t, kOut, kIn, mat, kExperts, xq, dbounds, dperm, 61, 149, dy, kOut, nullptr, dsrc); if (!ok(cudaMemcpy(y2.data(), dy, y2.size() * sizeof(float), cudaMemcpyDeviceToHost), "rows by index")) return 1; const bool same = std::memcmp(y1.data(), y2.data(), y1.size() * sizeof(float)) == 0; + if (int8) ref_ok = dump(ggml_type_name(ty), kIn, "by_index", y2) && ref_ok; std::printf("%-8s rows read by index: %s\n", ggml_type_name(ty), same ? "same products" : "OTHER PRODUCTS"); fine = fine && same; } @@ -323,6 +387,85 @@ int main(int argc, char** argv) { } cudaFree(gy); cudaFree(gdq); + + if (int8) { + // The int8 tile's other shapes: matrices of kOut2 rows (not whole tiles of 64: the rows past the last are + // not read, and their products not written), and launches of 10 and 20 rows (the tiles of 16 and 32 + // activation rows); dense, and four experts of 10 rows at most (the first kOut2 rows of each matrix) + constexpr int64_t kOut2 = 500; + const int32_t small_h[kExperts + 1] = {0, 10, 10, 17, 20}; + int32_t* dsmall = upload(std::vector(small_h, small_h + kExperts + 1)); + if (!dsmall) return 1; + const auto against = [&](const std::vector& yy, int64_t rows, const std::vector& expert_of, const char* what) { + std::vector r((size_t) (rows * kOut)), r2((size_t) (rows * kOut2)); + for (int64_t i = 0; i < rows; ++i) { + reference(i, expert_of[(size_t) i], true, &r[(size_t) (i * kOut)]); + std::copy_n(&r[(size_t) (i * kOut)], kOut2, &r2[(size_t) (i * kOut2)]); + } + const Err e = compare(yy, r2, rows, kOut2, kOut2); + const bool same = dump(ggml_type_name(ty), kIn, what, yy); + const bool good = e.rms < 1e-5 && same; + std::printf("%-8s %s (%lld outputs): int8 numbers RMS error %.2e, largest %.2e %s\n", ggml_type_name(ty), what, + (long long) kOut2, e.rms, e.top, good ? "ok" : "WRONG"); + return good; + }; + bool shapes = true; + for (const int64_t rows : {(int64_t) 10, (int64_t) 20, kTokens}) { + std::vector ys((size_t) (rows * kOut2)); + Mmq::quantize(dx, nullptr, xq, t, kIn, kIn, rows, nullptr); + mmq.mul(dw, t, kOut2, kIn, 0, 1, xq, nullptr, nullptr, rows, rows, dy, kOut2, nullptr); + if (!ok(cudaMemcpy(ys.data(), dy, ys.size() * sizeof(float), cudaMemcpyDeviceToHost), "short rows")) return 1; + shapes = against(ys, rows, std::vector((size_t) rows, 0), ("dense" + std::to_string(rows) + "x500").c_str()) && shapes; + } + { + std::vector ys((size_t) (20 * kOut2)); + Mmq::quantize(dx, nullptr, xq, t, kIn, kIn, 20, nullptr); + mmq.mul(dw, t, kOut2, kIn, mat, kExperts, xq, dsmall, nullptr, 20, 10, dy, kOut2, nullptr); + if (!ok(cudaMemcpy(ys.data(), dy, ys.size() * sizeof(float), cudaMemcpyDeviceToHost), "small experts")) return 1; + std::vector eo(20); + for (int e = 0; e < kExperts; ++e) + for (int32_t r = small_h[e]; r < small_h[e + 1]; ++r) eo[(size_t) r] = e; + shapes = against(ys, 20, eo, "experts20x500") && shapes; + } + cudaFree(dsmall); + if (t == 8 && kIn == 2048) { + // More launches' blocks than a grid's y side holds: 70,000 matrices of one row each (all the same + // matrix, by offset), row i token i % 256: each row's product is the dense product's row, bit for bit + constexpr int kMany = 70000; + std::vector ids_h(kMany), mb(kMany + 1); + for (int i = 0; i < kMany; ++i) ids_h[(size_t) i] = i % (int) kTokens; + for (int i = 0; i <= kMany; ++i) mb[(size_t) i] = i; + int32_t* dids = upload(ids_h); + int32_t* dmb = upload(mb); + int64_t* dat0 = upload(std::vector((size_t) kMany, 0)); + void* xq_many = nullptr; + float* dy_many = nullptr; + if (!dids || !dmb || !dat0 || !ok(cudaMalloc(&xq_many, Mmq::q8_bytes(kMany, kIn)), "cudaMalloc") || + !ok(cudaMalloc(&dy_many, (size_t) kMany * kOut * sizeof(float)), "cudaMalloc")) + return 1; + std::vector yd((size_t) (kTokens * kOut)), ym((size_t) kMany * kOut); + Mmq::quantize(dx, nullptr, xq, t, kIn, kIn, kTokens, nullptr); + mmq.mul(dw, t, kOut, kIn, 0, 1, xq, nullptr, nullptr, kTokens, kTokens, dy, kOut, nullptr); + Mmq::quantize(dx, dids, xq_many, t, kIn, kIn, kMany, nullptr); + mmq.mul_at(dw, dat0, t, kOut, kIn, kMany, xq_many, dmb, nullptr, kMany, 1, dy_many, kOut, nullptr); + if (!ok(cudaMemcpy(yd.data(), dy, yd.size() * sizeof(float), cudaMemcpyDeviceToHost), "dense product") || + !ok(cudaMemcpy(ym.data(), dy_many, ym.size() * sizeof(float), cudaMemcpyDeviceToHost), "many matrices")) + return 1; + bool many = true; + for (int i = 0; i < kMany && many; ++i) + many = std::memcmp(&ym[(size_t) i * kOut], &yd[(size_t) (i % kTokens) * kOut], kOut * sizeof(float)) == 0; + std::printf("%-8s %d matrices of a row (more blocks than a grid side): %s\n", ggml_type_name(ty), kMany, + many ? "same products" : "OTHER PRODUCTS"); + shapes = shapes && many; + cudaFree(dids); + cudaFree(dmb); + cudaFree(dat0); + cudaFree(xq_many); + cudaFree(dy_many); + } + fine = fine && shapes; + } + fine = fine && ref_ok; bad += !fine; cudaFree(dw); } @@ -335,6 +478,8 @@ int main(int argc, char** argv) { cudaFree(dbounds); } ggml_quantize_free(); + if (ref_dir()) std::printf("reference %s: %d products the same, %d not\n", ref_dir(), ref_same, ref_bad); + if (ref_bad && !bad) bad = 1; std::printf("%s\n", bad ? "FAIL" : "PASS"); return bad ? 1 : 0; } diff --git a/terminal/data/settings-register.json b/terminal/data/settings-register.json index 1b115a170..47f672fb3 100644 --- a/terminal/data/settings-register.json +++ b/terminal/data/settings-register.json @@ -23816,6 +23816,66 @@ "retire_after": "", "retired_in": "" }, + { + "name": "STRATA_MMQ_TEST_DUMP", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "engine/src/poly/mmq_paths_test.cu", + "line": 83, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "flag", + "default_state": null, + "code_default": null, + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [], + "status": "research", + "owner": "poly", + "note": "test only: poly_mmq_paths_test writes each int8 product's floats to DIR/__.bin and the inputs' hashes to DIR/inputs.txt, to compare CUDA's and HIP's int8 tiles bit for bit (engine/src/poly/mmq_paths_test.cu)", + "retire_after": "", + "retired_in": "", + "first_date": "2026-11-24", + "last_date": "2026-11-24" + }, + { + "name": "STRATA_MMQ_TEST_REF", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "engine/src/poly/mmq_paths_test.cu", + "line": 87, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "flag", + "default_state": null, + "code_default": null, + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [], + "status": "research", + "owner": "poly", + "note": "test only: poly_mmq_paths_test compares each int8 product's bytes with DIR's file of the same name (another card's STRATA_MMQ_TEST_DUMP) and fails where one is missing or differs (engine/src/poly/mmq_paths_test.cu)", + "retire_after": "", + "retired_in": "", + "first_date": "2026-11-24", + "last_date": "2026-11-24" + }, { "name": "STRATA_MMQ_TIER_SORT", "backends": [