diff --git a/docs/HIP.md b/docs/HIP.md index 79dca90a..d4451a40 100644 --- a/docs/HIP.md +++ b/docs/HIP.md @@ -213,6 +213,11 @@ By default HIP runs Inkling 2 on the faster attention and controller kernels. Th text can differ from the older kernels and from Vulkan at a near tie. `--fixed-experts` keeps the older kernels. `STRATA_DS_FAST_KERNELS=0` selects the older kernels, and `1` the faster ones under `--fixed-experts` too. +On WMMA cards the prompt attention is `ink_attn_prefill_128_wm` and the decode attention `ink_attn_128_g3` +(three query heads sharing a KV head in one block). Both run the `q8` cache format on either side, so `--kv` pairs +like `f16-q8` and `q8` keep the fast kernels: q8 K rows ride through shared memory as packed 8-byte units and are +expanded there, halving the KV memory for 1038 pp / 48.1 tok/s against f16's 1200 / 50.4. + `bench --pp 512,4096 --tg 64`, alternating runs with a browser open on the desktop: | | pp 4096 | decode | diff --git a/src/backend.rs b/src/backend.rs index efbacad0..fd596807 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -65,7 +65,8 @@ unsafe impl Plain for u64 {} /// Pointer arguments are device addresses; strides are in floats unless named otherwise. /// The backend `kind` ("cuda", "vulkan" or "hip") on GPU `device`; with no kind, CUDA if it loads, else Vulkan. /// Refuses a `--device` list with several indices on the HIP backend: `hip::Gpu` opens one device per process -/// (hipSetDevice runs once, in `Gpu::new`), so a split over two cards would run both layers on the first one. +/// (`hipSetDevice` is per-thread, so every thread that calls into a `Gpu` reselects its card), so a split over two +/// cards would run both layers on the first one. pub fn check_devices(kind: Option<&str>, devices: &[usize]) -> anyhow::Result<()> { if kind == Some("hip") && devices.len() > 1 { anyhow::bail!("the hip backend runs one device: --device {} needs cuda or vulkan", devices.iter().map(|d| d.to_string()).collect::>().join(",")); @@ -215,6 +216,8 @@ pub trait Backend: Send { /// Free the graph recorded under `key`, if there is one. For a caller whose keys change as it runs (a graph holds /// device memory, and CUDA stops recording at a fixed number of them). fn graph_drop(&self, _key: u64) -> anyhow::Result<()> { Ok(()) } + /// Whether the stream is recording a graph right now: no synchronous call may be issued inside one. + fn capturing(&self) -> bool { false } /// Free every recorded graph, after buffers they use were replaced (a slot's KV cache grew). fn graph_clear(&self) -> anyhow::Result<()> { Ok(()) } /// Queue the ops of `f`, none of which reads what another writes, with no ordering among them (Vulkan: no diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 64454c0e..08b17cc4 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -4919,6 +4919,253 @@ extern "C" __global__ void __launch_bounds__(128) ink_attn_128(const float*, con const u16*, const float*, float*, int, int, int, int, int, int, int, const int*) { __trap(); } #endif +#if K_MODE <= 1 && V_MODE <= 1 +// ink_attn_128 with the GQA group combined: the three query heads that share a KV head (nh = 3 nkv) run in one +// block, so each K chunk is staged and each V chunk is walked once per block instead of three times. Per-head +// scores, softmax and PV keep the exact operation order of the per-head kernel. K and V may each be f16 or q8 +// (K_MODE/V_MODE 0/1, any mix): a q8 row is 136 B (128 int8 values, four f16 scales per 32 values), staged +// padded to 144 B, and every value is dequantized as rh(q * scale), exactly what ldkv1_at gives. +extern "C" __global__ void __launch_bounds__(128) ink_attn_128_g3(const float* q, const float* r, const float* sink, + const u16* k, const u16* v, const float* bias, float* sc, int rows, int at, int ring, int nkv, int hd, + int nr, int ext, const int* pos_ptr) { + constexpr int HD = 128, PQ = HD + 8, G = 3; + // A q8 row: 128 signed-byte values + four f16 block scales = 136 B; the staged row pads to 144 B (PK words). + constexpr int KB = HD + HD / 16, PK = (KB + 8) / 2; + __shared__ __align__(16) float qs[G * HD], rs[G * 32], lg[G * 128], ac[G][4][HD]; + __shared__ __align__(16) u16 ks[64 * (K_MODE == 1 ? PK : PQ)]; + int h0 = blockIdx.x * G; + int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + if (pos_ptr) { int pos = *pos_ptr; rows = min(pos + 1, ring); at = pos % ring; } + int i0 = blockIdx.y * 128, n = i0 < rows ? min(128, rows - i0) : 0; + if (n == 0) { // a chunk past the keys: neutral partials for the merge (exp(-3e38) is 0) + for (int g = 0; g < G; g++) { + float* o = sc + ((size_t)(h0 + g) * gridDim.y + blockIdx.y) * (HD + 2); + if (tid < HD) o[2 + tid] = 0.f; + if (tid == 0) { o[0] = -3.0e38f; o[1] = 0.f; } + } + return; + } + for (int g = 0; g < G; g++) { + if (tid < HD) qs[g * HD + tid] = q[(h0 + g) * HD + tid] * rsqrtf((float)HD); + if (tid < nr) rs[g * 32 + tid] = r[(h0 + g) * nr + tid]; + } + int i = i0 + warp * 32 + lane; + bool live = i < i0 + n; + // Two phases of 64 rows: warps 0-1 stage and score the chunk's first half, warps 2-3 the second, each warp + // reading only rows it staged itself (a warp barrier publishes them). The tile holds 64 rows instead of 128, + // which halves shared memory to ~28 KiB: two blocks live per CU, and their eight waves hide the load latencies + // that a single block leaves fully exposed. + float d[G]; +#pragma unroll + for (int g = 0; g < G; g++) d[g] = live ? 0.f : -3.0e38f; + __syncthreads(); // qs/rs staged by all four warps must be visible before any warp's QK +#pragma unroll + for (int ph = 0; ph < 2; ph++) { + if ((warp >> 1) == ph) { + if constexpr (K_MODE == 0) { + // Loads in batches of four: each round issues four outstanding global loads before the shared + // stores consume them, so the DRAM latency overlaps instead of serializing per row. + int kw = nkv * HD; +#pragma unroll + for (int b = 0; b < 8; b++) { + uint4 x[4]; int rr[4], pp[4]; +#pragma unroll + for (int j = 0; j < 4; j++) { + int s2 = lane + 32 * (b * 4 + j), row = s2 >> 4, part = s2 & 15, key = ph * 64 + row; + rr[j] = row; pp[j] = part; + x[j] = key < n ? *(const uint4*)(k + (size_t)(i0 + key) * kw + blockIdx.x * HD + part * 8) + : make_uint4(0u, 0u, 0u, 0u); + } +#pragma unroll + for (int j = 0; j < 4; j++) *(uint4*)(ks + rr[j] * PQ + pp[j] * 8) = x[j]; + } + } else if (n == 128) { + // A full chunk: all 64 rows are live, so only the slots past the 1088 units of the tile guard. +#pragma unroll + for (int b = 0; b < 9; b++) { + uint2 x[4]; int rr[4], pp[4]; +#pragma unroll + for (int j = 0; j < 4; j++) { + int s2 = lane + 32 * (b * 4 + j), row = s2 / 17, part = s2 - row * 17; + rr[j] = row; pp[j] = part; + x[j] = s2 < 64 * 17 ? *(const uint2*)((const unsigned char*)k + ((size_t)(i0 + ph * 64 + row) * nkv + blockIdx.x) * KB + part * 8) + : make_uint2(0u, 0u); + } +#pragma unroll + for (int j = 0; j < 4; j++) if (rr[j] < 64) *(uint2*)(ks + rr[j] * PK + pp[j] * 4) = x[j]; + } + } else { + // q8 rows stage as 17 eight-byte units: 16 value units, then one holding the four f16 scales. +#pragma unroll + for (int b = 0; b < 9; b++) { + uint2 x[4]; int rr[4], pp[4]; bool ok[4]; +#pragma unroll + for (int j = 0; j < 4; j++) { + int s2 = lane + 32 * (b * 4 + j), row = s2 / 17, part = s2 - row * 17, key = ph * 64 + row; + ok[j] = s2 < 64 * 17 && key < n; + rr[j] = row; pp[j] = part; + x[j] = ok[j] ? *(const uint2*)((const unsigned char*)k + ((size_t)(i0 + key) * nkv + blockIdx.x) * KB + part * 8) + : make_uint2(0u, 0u); + } +#pragma unroll + for (int j = 0; j < 4; j++) if (rr[j] < 64) *(uint2*)(ks + rr[j] * PK + pp[j] * 4) = x[j]; + } + } + __syncwarp(); + if (live) { + if constexpr (K_MODE == 0) { + const u16* kr = ks + ((warp & 1) * 32 + lane) * PQ; + for (int m = 0; m < HD / 8; m++) { + uint4 w = *(const uint4*)(kr + 8 * m); + float2 a = ink_h2f2(w.x), b = ink_h2f2(w.y), c = ink_h2f2(w.z), e = ink_h2f2(w.w); +#pragma unroll + for (int g = 0; g < G; g++) { + const float* qh = qs + g * HD; + d[g] += qh[8 * m + 0] * a.x + qh[8 * m + 1] * a.y + qh[8 * m + 2] * b.x + qh[8 * m + 3] * b.y + + qh[8 * m + 4] * c.x + qh[8 * m + 5] * c.y + qh[8 * m + 6] * e.x + qh[8 * m + 7] * e.y; + } + } + } else { + const unsigned char* kr = (const unsigned char*)ks + ((warp & 1) * 32 + lane) * (PK * 2); + uint4 sw = *(const uint4*)(kr + HD); // the four block scales of the row in one load + float2 sc01 = ink_h2f2(sw.x), sc23 = ink_h2f2(sw.y); + float sc[4] = { sc01.x, sc01.y, sc23.x, sc23.y }; +#pragma unroll + for (int m = 0; m < HD / 16; m++) { + uint4 w = *(const uint4*)(kr + 16 * m); // two eight-value groups + float s = sc[m >> 1]; + unsigned lo = w.x, hi = w.y; + float v0 = rh((signed char)(lo & 0xff) * s), v1 = rh((signed char)(lo >> 8 & 0xff) * s), + v2 = rh((signed char)(lo >> 16 & 0xff) * s), v3 = rh((signed char)((lo >> 24) & 0xff) * s), + v4 = rh((signed char)(hi & 0xff) * s), v5 = rh((signed char)(hi >> 8 & 0xff) * s), + v6 = rh((signed char)(hi >> 16 & 0xff) * s), v7 = rh((signed char)((hi >> 24) & 0xff) * s); +#pragma unroll + for (int g = 0; g < G; g++) { + const float* qh = qs + g * HD; + d[g] += qh[16 * m + 0] * v0 + qh[16 * m + 1] * v1 + qh[16 * m + 2] * v2 + qh[16 * m + 3] * v3 + + qh[16 * m + 4] * v4 + qh[16 * m + 5] * v5 + qh[16 * m + 6] * v6 + qh[16 * m + 7] * v7; + } + lo = w.z, hi = w.w; + v0 = rh((signed char)(lo & 0xff) * s), v1 = rh((signed char)(lo >> 8 & 0xff) * s), + v2 = rh((signed char)(lo >> 16 & 0xff) * s), v3 = rh((signed char)((lo >> 24) & 0xff) * s), + v4 = rh((signed char)(hi & 0xff) * s), v5 = rh((signed char)(hi >> 8 & 0xff) * s), + v6 = rh((signed char)(hi >> 16 & 0xff) * s), v7 = rh((signed char)((hi >> 24) & 0xff) * s); +#pragma unroll + for (int g = 0; g < G; g++) { + const float* qh = qs + g * HD; + d[g] += qh[16 * m + 8] * v0 + qh[16 * m + 9] * v1 + qh[16 * m + 10] * v2 + qh[16 * m + 11] * v3 + + qh[16 * m + 12] * v4 + qh[16 * m + 13] * v5 + qh[16 * m + 14] * v6 + qh[16 * m + 15] * v7; + } + } + } + int dist = at - i; if (dist < 0) dist += rows; + if (dist < ext) { + const float* br = bias + (size_t)dist * nr; + for (int c0 = 0; c0 < nr; c0 += 4) { + float bv[4]; +#pragma unroll + for (int q = 0; q < 4; q++) bv[q] = (c0 + q < nr) ? br[c0 + q] : 0.f; +#pragma unroll + for (int q = 0; q < 4; q++) { + d[0] += rs[c0 + q] * bv[q]; d[1] += rs[32 + c0 + q] * bv[q]; d[2] += rs[64 + c0 + q] * bv[q]; + } + } + } + } + } + __syncthreads(); + } + if (live) { d[0] -= sink[h0]; d[1] -= sink[h0 + 1]; d[2] -= sink[h0 + 2]; } + float wmax[G], wsum[G]; +#pragma unroll + for (int g = 0; g < G; g++) wmax[g] = warp_max(d[g]); + __shared__ __align__(16) float sm[G][2][32]; + __syncthreads(); + if (lane == 0) + for (int g = 0; g < G; g++) sm[g][0][warp] = wmax[g]; + __syncthreads(); + float mx[G], z[G]; +#pragma unroll + for (int g = 0; g < G; g++) { + mx[g] = warp_max(lane < 4 ? sm[g][0][lane] : -3.0e38f); + float p = live ? expf(d[g] - mx[g]) : 0.f; + lg[g * 128 + tid] = p; + wsum[g] = warp_sum(p); + } + __syncthreads(); + if (lane == 0) + for (int g = 0; g < G; g++) sm[g][1][warp] = wsum[g]; + __syncthreads(); +#pragma unroll + for (int g = 0; g < G; g++) z[g] = warp_sum(lane < 4 ? sm[g][1][lane] : 0.0f); + __syncthreads(); + float a0[G], a1[G], a2[G], a3[G]; +#pragma unroll + for (int g = 0; g < G; g++) { a0[g] = 0.f; a1[g] = 0.f; a2[g] = 0.f; a3[g] = 0.f; } + // Same batching for the V walk: eight row loads in flight before their products run. + if constexpr (V_MODE == 0) { + int kw = nkv * HD; + for (int j0 = warp; j0 < n; j0 += 4 * 8) { + uint2 vw[8]; int jj[8]; +#pragma unroll + for (int b = 0; b < 8; b++) { + int j = j0 + b * 4; jj[b] = j; + vw[b] = j < n ? *(const uint2*)(v + (size_t)(i0 + j) * kw + blockIdx.x * HD + 4 * lane) : make_uint2(0u, 0u); + } +#pragma unroll + for (int b = 0; b < 8; b++) { + int j = jj[b]; + if (j >= n) continue; + float2 v01 = ink_h2f2(vw[b].x), v23 = ink_h2f2(vw[b].y); +#pragma unroll + for (int g = 0; g < G; g++) { + float pj = lg[g * 128 + j]; + a0[g] += pj * v01.x; a1[g] += pj * v01.y; a2[g] += pj * v23.x; a3[g] += pj * v23.y; + } + } + } + } else { + for (int j0 = warp; j0 < n; j0 += 4 * 8) { + unsigned vw[8]; float vs[8]; int jj[8]; +#pragma unroll + for (int b = 0; b < 8; b++) { + int j = j0 + b * 4; jj[b] = j; + if (j < n) { + const unsigned char* vr = (const unsigned char*)v + ((size_t)(i0 + j) * nkv + blockIdx.x) * KB; + vw[b] = *(const unsigned*)(vr + 4 * lane); + vs[b] = h2f(*(const u16*)(vr + HD + 2 * (lane >> 3))); + } else { vw[b] = 0u; vs[b] = 0.f; } + } +#pragma unroll + for (int b = 0; b < 8; b++) { + int j = jj[b]; + if (j >= n) continue; + float v0 = rh((signed char)(vw[b] & 0xff) * vs[b]), v1 = rh((signed char)(vw[b] >> 8 & 0xff) * vs[b]), + v2 = rh((signed char)(vw[b] >> 16 & 0xff) * vs[b]), v3 = rh((signed char)((vw[b] >> 24) & 0xff) * vs[b]); +#pragma unroll + for (int g = 0; g < G; g++) { + float pj = lg[g * 128 + j]; + a0[g] += pj * v0; a1[g] += pj * v1; a2[g] += pj * v2; a3[g] += pj * v3; + } + } + } + } +#pragma unroll + for (int g = 0; g < G; g++) + *(float4*)&ac[g][warp][4 * lane] = make_float4(a0[g], a1[g], a2[g], a3[g]); + __syncthreads(); +#pragma unroll + for (int g = 0; g < G; g++) { + float* o = sc + ((size_t)(h0 + g) * gridDim.y + blockIdx.y) * (HD + 2); + if (tid < HD) o[2 + tid] = ac[g][0][tid] + ac[g][1][tid] + ac[g][2][tid] + ac[g][3][tid]; + if (tid == 0) { o[0] = mx[g]; o[1] = z[g]; } + } +} +#else +extern "C" __global__ void __launch_bounds__(128) ink_attn_128_g3(const float*, const float*, const float*, const u16*, + const u16*, const float*, float*, int, int, int, int, int, int, int, const int*) { __trap(); } +#endif + #if K_MODE == 2 && V_MODE == 2 // ink_attn_128 on a q4 cache, whose row of 128 values is 72 bytes: the nibbles, then the four block scales. A 128-thread // block owns 128 key positions and stages their K rows in shared memory with coalesced 8-byte loads; lane i of warp w @@ -4999,17 +5246,37 @@ extern "C" __global__ void __launch_bounds__(128) ink_attn_128_q4(const float*, #endif extern "C" __global__ void ink_attn_merge(const float* sc, const float* gate, float* out, int chunks, int hd) { - int h = blockIdx.x, t = threadIdx.x; + int h = blockIdx.x, t = threadIdx.x, lane = t & 31, w = t >> 5; + __shared__ float red[4], oacc[4][128]; const float* p = sc + (size_t)h * chunks * (hd + 2); + // The chunk scan runs warp-strided: every warp covers a quarter of the chunks for all 128 dims (four dims + // per thread), so each staging row is fully written and the cross-warp sums below are safe. float mx = 0.f; - for (int j = 0; j < chunks; j++) mx = fmaxf(mx, p[j * (hd + 2)]); - float z = expf(-mx), o = 0.f; - for (int j = 0; j < chunks; j++) { - float e = expf(p[j * (hd + 2)] - mx); - z += p[j * (hd + 2) + 1] * e; - if (t < hd) o += p[j * (hd + 2) + 2 + t] * e; - } - if (t < hd) out[h * hd + t] = o / z * sigmoid(gate[h * hd + t]); + for (int j = w; j < chunks; j += 4) mx = fmaxf(mx, p[j * (hd + 2)]); + mx = warp_max(mx); + if (lane == 0) red[w] = mx; + __syncthreads(); + mx = fmaxf(fmaxf(red[0], red[1]), fmaxf(red[2], red[3])); + float z = 0.f, o0 = 0.f, o1 = 0.f, o2 = 0.f, o3 = 0.f; // sink logit 0 added once below + __syncthreads(); // red is reused for the z stage: every warp must have read mx before any warp writes z + for (int j = w; j < chunks; j += 4) { + const float* pj = p + j * (hd + 2); + float e = expf(pj[0] - mx); + z += pj[1] * e; + o0 += pj[2 + lane] * e; + o1 += (lane + 32 < hd) ? pj[2 + lane + 32] * e : 0.f; + o2 += (lane + 64 < hd) ? pj[2 + lane + 64] * e : 0.f; + o3 += (lane + 96 < hd) ? pj[2 + lane + 96] * e : 0.f; + } + // All lanes of a warp hold the same z, so one lane stages it; the four dim partials fill the row. + if (lane == 0) red[w] = z; + oacc[w][lane] = o0; + if (lane + 32 < hd) oacc[w][lane + 32] = o1; + if (lane + 64 < hd) oacc[w][lane + 64] = o2; + if (lane + 96 < hd) oacc[w][lane + 96] = o3; + __syncthreads(); + z = expf(-mx) + red[0] + red[1] + red[2] + red[3]; + if (t < hd) out[h * hd + t] = (oacc[0][t] + oacc[1][t] + oacc[2][t] + oacc[3][t]) / z * sigmoid(gate[h * hd + t]); } // Inkling 2 causal prefill attention with online softmax + virtual sink logit 0. @@ -5459,6 +5726,251 @@ extern "C" __global__ void __launch_bounds__(192) ink_attn_prefill_128_tc( const float* bias, float* outp, int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) {} #endif +#if STRATA_HIP && GEMM_WMMA && K_MODE <= 1 && V_MODE <= 1 +// Flash-style Inkling 2 prefill attention for head_dim 128 on the f16 or q8 cache (K_MODE/V_MODE 0/1, any mix): +// the tile layout and matrix-core path of attn_prefill_t (64 queries a block, 32-key K/V tiles, scores staged +// through f32 shared memory), carrying the Inkling extras: the relative-bias rows, the new-token K/V split, ring +// rows, a per-token sink and the output gate. A quantized side loads raw 136 B rows (128 int8 values + four f16 +// scales) with 8-byte cp.async and dequantizes them in place into the f16 tile before each WMMA read. +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_wm( + const float* q, const float* r, const float* sink, const float* gate, + const u16* kc, const u16* vc, const u16* kc_new, const u16* vc_new, + const float* bias, float* outp, + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win) { + constexpr int HD = 128, PQ = HD + 8, BQ = 64, BK = 32, PW = BK + 8; + extern __shared__ __align__(16) u16 wm_sm[]; + u16* qs = wm_sm; + u16* ks = qs + BQ * PQ; + u16* vs = ks + BK * PQ; + u16* ps = vs + BK * PQ; + float* st = (float*)(ps + BQ * PW); + float* rs = st + BQ * PW; + int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, g = lane >> 2, t4 = lane & 3; + // A q8 K/V row: 128 signed-byte values + four f16 block scales = 136 B, loaded packed and expanded in place. + constexpr int KB = HD + HD / 16; + int q0 = (gridDim.x - 1 - blockIdx.x) * BQ, h = blockIdx.y, kvh = h / (nh / nkv); + constexpr int kwr = K_MODE == 1 ? KB / 2 : HD, vwr = V_MODE == 1 ? KB / 2 : HD; + int kvd = nkv * kwr, kvd_v = nkv * vwr; + const float scale = 1.f / sqrtf((float)HD); + for (int i = tid; i < BQ * HD / 4; i += 128) { + int rr = i / (HD / 4), c = (i % (HD / 4)) * 4; + float4 v = q0 + rr < nt ? *(const float4*)(q + (size_t)(q0 + rr) * nh * HD + h * HD + c) : make_float4(0.f, 0.f, 0.f, 0.f); + *(uint2*)(qs + rr * PQ + c) = make_uint2(h2pack(v.x * scale, v.y * scale), h2pack(v.z * scale, v.w * scale)); + } + for (int i = tid; i < BQ * 32; i += 128) { + int rr = i >> 5, c = i & 31, t = q0 + rr; + rs[rr * 32 + c] = (c < nr && t < nt) ? r[((size_t)t * nh + h) * nr + c] : 0.f; + } + int last = pos + min(q0 + BQ, nt) - 1; + int kmin = (win > 0 && pos + q0 + 1 > win) ? (pos + q0 + 1 - win) : 0; + int qp[2] = {pos + q0 + warp * 16 + g, pos + q0 + warp * 16 + g + 8}; + float o[HD / 8][4] = {}, m[2] = {-INFINITY, -INFINITY}, l[2] = {0.f, 0.f}; + auto sr = [&](const u16* cache, const u16* fresh, int kp) -> const u16* { + if (fresh && kp >= pos) return fresh + (size_t)(kp - pos) * kvd + kvh * kwr; + return cache + (size_t)(win > 0 ? kp % ring : kp) * kvd + kvh * kwr; + }; + auto sr_v = [&](const u16* cache, const u16* fresh, int kp) -> const u16* { + if (fresh && kp >= pos) return fresh + (size_t)(kp - pos) * kvd_v + kvh * vwr; + return cache + (size_t)(win > 0 ? kp % ring : kp) * kvd_v + kvh * vwr; + }; + constexpr int N = BK * HD / 8 / 128; + auto ld = [&](int k0, u16* dst, const u16* cache, const u16* fresh) { + if constexpr (K_MODE == 0) { +#pragma unroll + for (int n = 0; n < N; n++) { + int i = tid + n * 128, rr = i / (HD / 8), c = (i % (HD / 8)) * 8, kp = k0 + rr; + cp_async16(dst + rr * PQ + c, sr(cache, fresh, min(kp, last)) + c, kp <= last); + } + } else { + // 17 eight-byte units a row: rows packed at KB bytes, expanded to the PQ-word tile by deq(). +#pragma unroll + for (int n = 0; n < 5; n++) { + int i = tid + n * 128, rr = i / 17, u = i - rr * 17, kp = k0 + rr; + cp_async8((unsigned char*)dst + rr * KB + u * 8, + (const unsigned char*)sr(cache, fresh, min(kp, last)) + u * 8, i < BK * 17 && kp <= last); + } + } + cp_async_commit(); + }; + auto ld_v = [&](int k0, u16* dst, const u16* cache, const u16* fresh) { + if constexpr (V_MODE == 0) { +#pragma unroll + for (int n = 0; n < N; n++) { + int i = tid + n * 128, rr = i / (HD / 8), c = (i % (HD / 8)) * 8, kp = k0 + rr; + cp_async16(dst + rr * PQ + c, sr_v(cache, fresh, min(kp, last)) + c, kp <= last); + } + } else { +#pragma unroll + for (int n = 0; n < 5; n++) { + int i = tid + n * 128, rr = i / 17, u = i - rr * 17, kp = k0 + rr; + cp_async8((unsigned char*)dst + rr * KB + u * 8, + (const unsigned char*)sr_v(cache, fresh, min(kp, last)) + u * 8, i < BK * 17 && kp <= last); + } + } + cp_async_commit(); + }; + // Expand a packed q8 tile (17 eight-byte units a row, KB bytes rows) into the f16 tile (PQ words a row) in + // place: every thread first pulls its units and scales into registers, a barrier separates the read phase + // from the write phase, so the wider f16 footprint can never clobber an unread source byte. + auto deq = [&](u16* tile) { + unsigned lo[5], hi[5]; float sc[5]; +#pragma unroll + for (int rbk = BK * 17 - 1 - tid, n = 0; rbk >= 0; rbk -= 128, n++) { + int rr = rbk / 17, u = rbk - rr * 17; + const unsigned char* src = (const unsigned char*)tile + rr * KB; + lo[n] = *(const unsigned*)(src + u * 8); + hi[n] = *(const unsigned*)(src + u * 8 + 4); + sc[n] = h2f(*(const u16*)(src + HD + 2 * (u >> 2))); + } + __syncthreads(); +#pragma unroll + for (int rbk = BK * 17 - 1 - tid, n = 0; rbk >= 0; rbk -= 128, n++) { + int rr = rbk / 17, u = rbk - rr * 17, v = rr * PQ + u * 8; + float s = sc[n]; unsigned x = lo[n], y = hi[n]; + *(u32*)(tile + v) = h2pack(rh((signed char)(x & 0xff) * s), rh((signed char)(x >> 8 & 0xff) * s)); + *(u32*)(tile + v + 2) = h2pack(rh((signed char)(x >> 16 & 0xff) * s), rh((signed char)((x >> 24) & 0xff) * s)); + *(u32*)(tile + v + 4) = h2pack(rh((signed char)(y & 0xff) * s), rh((signed char)(y >> 8 & 0xff) * s)); + *(u32*)(tile + v + 6) = h2pack(rh((signed char)(y >> 16 & 0xff) * s), rh((signed char)((y >> 24) & 0xff) * s)); + } + }; + ld(kmin, ks, kc, kc_new); + ld_v(kmin, vs, vc, vc_new); + for (int k0 = kmin; k0 <= last; k0 += BK) { + cp_async_wait<1>(); + __syncthreads(); + if constexpr (K_MODE == 1) { + deq(ks); + __syncthreads(); + } + float s[BK / 8][4] = {}; + { + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane); + float* sw = st + warp * 16 * PW; + const u16* qrow = qs + (warp * 16 + l16) * PQ + w0; +#pragma unroll + for (int kg = 0; kg < BK / 16; kg++) { + strata_hip::strata_f8 acc; +#pragma unroll + for (int i = 0; i < 8; i++) acc[i] = 0.0f; + const u16* krow = ks + (kg * 16 + l16) * PQ + w0; +#pragma unroll + for (int kk = 0; kk < HD; kk += 16) + acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(qrow + kk), strata_hip::strata_ld_wmma(krow + kk), acc); +#pragma unroll + for (int i = 0; i < 8; i++) sw[STRATA_WMMA_ROW(lane, i) * PW + kg * 16 + l16] = acc[i]; + } + __syncwarp(); +#pragma unroll + for (int ng = 0; ng < BK / 8; ng++) +#pragma unroll + for (int i = 0; i < 4; i++) + s[ng][i] = sw[(g + 8 * (i >> 1)) * PW + ng * 8 + 2 * t4 + (i & 1)]; + } + __syncthreads(); + if (k0 + BK <= last) ld(k0 + BK, ks, kc, kc_new); + else cp_async_commit(); + float mx[2] = {m[0], m[1]}; + for (int ng = 0; ng < BK / 8; ng++) + for (int e = 0; e < 4; e++) { + int key = k0 + ng * 8 + 2 * t4 + (e & 1), rw = e >> 1; + if (key > qp[rw] || (win > 0 && key + win <= qp[rw])) { + s[ng][e] = -INFINITY; + } else { + int dist = qp[rw] - key; + if (dist < ext) { + const float* rrow = rs + (warp * 16 + g + 8 * rw) * 32; + const float* br = bias + (size_t)dist * nr; + float b = 0.f; + for (int c = 0; c < nr; c++) b += rrow[c] * br[c]; + s[ng][e] += b; + } + } + mx[rw] = fmaxf(mx[rw], s[ng][e]); + } + float c[2], ms[2]; + for (int rw = 0; rw < 2; rw++) { + mx[rw] = fmaxf(mx[rw], __shfl_xor_sync(0xffffffff, mx[rw], 1)); + mx[rw] = fmaxf(mx[rw], __shfl_xor_sync(0xffffffff, mx[rw], 2)); + ms[rw] = mx[rw] == -INFINITY ? 0.0f : mx[rw]; + c[rw] = expf(m[rw] - ms[rw]); + m[rw] = mx[rw]; + l[rw] *= c[rw]; + } + for (int ng = 0; ng < BK / 8; ng++) + for (int e = 0; e < 4; e++) { float p = expf(s[ng][e] - ms[e >> 1]); s[ng][e] = p; l[e >> 1] += p; } +#pragma unroll + for (int d = 0; d < HD / 8; d++) { o[d][0] *= c[0]; o[d][1] *= c[0]; o[d][2] *= c[1]; o[d][3] *= c[1]; } + cp_async_wait<1>(); + __syncthreads(); + if constexpr (V_MODE == 1) { + deq(vs); + __syncthreads(); + } + { + const int l16 = lane & 15, w0 = STRATA_WMMA_K0(lane); +#pragma unroll + for (int ng = 0; ng < BK / 8; ng++) { + *(u32*)(ps + (warp * 16 + g) * PW + ng * 8 + 2 * t4) = h2pack(s[ng][0], s[ng][1]); + *(u32*)(ps + (warp * 16 + g + 8) * PW + ng * 8 + 2 * t4) = h2pack(s[ng][2], s[ng][3]); + } + __syncwarp(); + float* sw = st + warp * 256; +#pragma unroll + for (int dt = 0; dt < HD / 16; dt++) { + strata_hip::strata_f8 acc; +#pragma unroll + for (int i = 0; i < 8; i++) acc[i] = 0.0f; +#pragma unroll + for (int kg = 0; kg < BK / 16; kg++) { + const u16* pa = ps + (warp * 16 + l16) * PW + kg * 16 + w0; + const u16* pb = vs + (kg * 16 + w0) * PQ + dt * 16 + l16; + acc = strata_hip::strata_wmma(strata_hip::strata_ld_wmma(pa), strata_hip::strata_ld_wmma_t(pb, PQ), acc); + } +#pragma unroll + for (int i = 0; i < 8; i++) sw[STRATA_WMMA_ROW(lane, i) * 16 + l16] = acc[i]; + __syncwarp(); +#pragma unroll + for (int rw = 0; rw < 2; rw++) +#pragma unroll + for (int e = 0; e < 2; e++) { + o[2 * dt][2 * rw + e] += sw[(g + 8 * rw) * 16 + 2 * t4 + e]; + o[2 * dt + 1][2 * rw + e] += sw[(g + 8 * rw) * 16 + 8 + 2 * t4 + e]; + } + __syncwarp(); + } + } + __syncthreads(); + if (k0 + BK <= last) ld_v(k0 + BK, vs, vc, vc_new); + else cp_async_commit(); + } + for (int rw = 0; rw < 2; rw++) { + l[rw] += __shfl_xor_sync(0xffffffff, l[rw], 1); + l[rw] += __shfl_xor_sync(0xffffffff, l[rw], 2); + } +#pragma unroll + for (int rw = 0; rw < 2; rw++) { + int t = q0 + warp * 16 + g + 8 * rw; + if (t >= nt) continue; + float* orow = outp + (size_t)t * nh * HD + h * HD; + const float* gt = gate + (size_t)t * nh * HD + h * HD; + float sk = sink[(size_t)t * nh + h]; + float M = fmaxf(m[rw], sk); + float sc = m[rw] == -INFINITY ? 0.0f : expf(m[rw] - M); + float den = l[rw] * sc + expf(sk - M); + float inv = den > 0.0f ? sc / den : 0.0f; +#pragma unroll + for (int d = 0; d < HD / 8; d++) + for (int e = 0; e < 2; e++) { + int col = d * 8 + 2 * t4 + e; + orow[col] = o[d][2 * rw + e] * inv * sigmoid(gt[col]); + } + } +} +#else +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_wm(const float*, const float*, const float*, + const float*, const u16*, const u16*, const u16*, const u16*, const float*, float*, int, int, int, int, + int, int, int, int) { __trap(); } +#endif // The same attention for a layer that sees every key, where the K/V rows of a long prompt do not stay in the cache. // The arithmetic of a (query, key) pair and the order of the keys are those of ink_attn_prefill_t: same bits. template diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 989c3f11..7c8d1c4b 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -7,7 +7,7 @@ use crate::backend::{BATCHED, Backend, Buf, DeviceTimer, MOE_GATE_X, PrefillRead use cudarc::driver::{CudaContext, CudaEvent, CudaFunction, CudaGraph, CudaSlice, CudaStream, DevicePtr, PinnedHostSlice, LaunchConfig, PushKernelArg, result, sys}; use cudarc::nvrtc::Ptx; use std::collections::{BTreeMap, HashMap, VecDeque}; -use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed}; use std::hash::{Hash, Hasher}; use std::sync::Arc; @@ -18,13 +18,13 @@ pub(crate) const QTYPES: [GgmlType; 30] = { use GgmlType::*; [F32, BF16, F8E4M3, Q8_0, Q2K, Q3K, Q4K, Q5K, Q6K, IQ1S, IQ1M, IQ2XXS, IQ2XS, IQ2S, IQ3XXS, IQ3S, IQ4XS, IQ4NL, Q2_0, TQ1_0, PTQ1_0, TQ2_0, TQ2T, TQK6, TQK7, Q4_1, Q5_1, Q4_0, Q5_0, NVFP4] }; -pub(crate) const KERNELS: [&str; 89] = [ +pub(crate) const KERNELS: [&str; 91] = [ "ds_rope", "rope_freq", "rope_cs", "qsa_pool", "qsa_score", "qsa_select", "rms_norm", "quant_xq", "argmax_part", "argmax_rows", "l2_norm", "rope_neox", "rms_norm_rope", "add", "swiglu", "swiglu_clamp", "situ", "situ_q", "softcap", "swiglu_q", "ssm_gates", "conv_silu", "deltanet_seq", "norm_gate", "hc_mix_q", "hc_write_norm", "kv_store", "kv_store_turbo", "attn_merge", "ha_post", "ha_wait", "router_topk", "moe_combine", "moe_route", "conv_seq", "conv_state", "moe_combine_seq", "moe_prefetch", "attn_prefill_64", "attn_prefill_128", "attn_prefill_256", "quant_q8", "gemm_splitk_sum", "x_to_f16", "hc_silu", "hc_mix", "hc_write", "ple_gate", "ple_conv", "dflash2_conv", "hadamard", - "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_ctrl_gate_b", "ink_ctrl_out_b", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_128", "ink_attn_128_q4", "ink_attn_merge", - "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_attn_prefill_128_old", "ink_attn_prefill_128_kp", "ink_attn_prefill_128_kp16", "ink_attn_prefill_128_tc", "ink_attn_prefill_sh_32", "ink_attn_prefill_sh_64", "ink_attn_prefill_sh_128", "ink_ffn_sum", "ink_ffn_sum_mb", "ink_slots", "ink_route", "attn_sel", "mla_attn", "mla_attn_tc", "mla_combine", "idx_score", "idx_score_dec", "vit_attn", "vit_norm", "vit_bias", "vit_rope", "vit_attn_tc_80", "vit_attn_tc_128", + "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_ctrl_gate_b", "ink_ctrl_out_b", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_128", "ink_attn_128_g3", "ink_attn_128_q4", "ink_attn_merge", + "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_attn_prefill_128_old", "ink_attn_prefill_128_kp", "ink_attn_prefill_128_kp16", "ink_attn_prefill_128_tc", "ink_attn_prefill_128_wm", "ink_attn_prefill_sh_32", "ink_attn_prefill_sh_64", "ink_attn_prefill_sh_128", "ink_ffn_sum", "ink_ffn_sum_mb", "ink_slots", "ink_route", "attn_sel", "mla_attn", "mla_attn_tc", "mla_combine", "idx_score", "idx_score_dec", "vit_attn", "vit_norm", "vit_bias", "vit_rope", "vit_attn_tc_80", "vit_attn_tc_128", ]; pub use crate::backend::{ATT_GQA_MIN, ATT_SPLITS, GEMM_BM, GpuTensor}; @@ -51,17 +51,25 @@ pub(crate) struct InkFlags { attn_q8_shared: bool, /// `STRATA_DS_ATTN_Q8_HD128=0` disables specialized Q8 decode. attn_q8_hd128: bool, + /// GQA-combined decode attention (`ink_attn_128_g3`) when `nh == 3 nkv`; `STRATA_DS_ATTN_G3=0` keeps the + /// per-head kernel. HIP only today (see `hip::ink_attn`), so this default is true everywhere. + pub(crate) attn_g3: bool, + /// Flash-style WMMA prefill attention (`ink_attn_prefill_128_wm`) on the f16 cache; `STRATA_DS_ATTN_WM=0` + /// keeps `ink_attn_prefill_128_kp16`. HIP only today (see `hip::ink_attn_prefill`), default true. + pub(crate) attn_wm: bool, } impl InkFlags { - pub(crate) fn from_parts(fast: Option<&str>, multi: bool, ctrl: Option<&str>, attn_old: Option<&str>, attn_kp4: Option<&str>) -> Self { + pub(crate) fn from_parts(fast: Option<&str>, multi: bool, ctrl: Option<&str>, attn_old: Option<&str>, + attn_kp4: Option<&str>, attn_g3: Option<&str>, attn_wm: Option<&str>) -> Self { let on = |v: Option<&str>, default: bool| v.map_or(default, |v| v != "0"); let fast = match fast { None | Some("auto") => multi, Some("0") => false, Some(_) => true, }; - Self { fast, ctrl_tile: on(ctrl, fast), attn_old: on(attn_old, false), attn_kp4: on(attn_kp4, false), attn_tc: std::env::var_os("STRATA_DS_ATTN_TC").is_some_and(|v| v != "0"), attn_q8_shared: false, attn_q8_hd128: false } + Self { fast, ctrl_tile: on(ctrl, fast), attn_old: on(attn_old, false), attn_kp4: on(attn_kp4, false), attn_tc: std::env::var_os("STRATA_DS_ATTN_TC").is_some_and(|v| v != "0"), attn_q8_shared: false, attn_q8_hd128: false, + attn_g3: on(attn_g3, true), attn_wm: on(attn_wm, true) } } fn with_cuda_q8(mut self, shared: Option<&str>, decode: Option<&str>) -> Self { self.attn_q8_shared = shared != Some("0"); @@ -78,6 +86,8 @@ impl InkFlags { std::env::var("STRATA_CTRL_TILE").ok().as_deref(), std::env::var("STRATA_DS_ATTN_OLD").ok().as_deref(), std::env::var("STRATA_DS_ATTN_KP4").ok().as_deref(), + std::env::var("STRATA_DS_ATTN_G3").ok().as_deref(), + std::env::var("STRATA_DS_ATTN_WM").ok().as_deref(), ); flags.with_cuda_q8( std::env::var("STRATA_DS_ATTN_Q8_SHARED").ok().as_deref(), @@ -170,6 +180,8 @@ pub struct Gpu { am: CudaSlice<[i32; 2]>, /// Recorded graphs by `Backend::graph` key. graphs: std::sync::Mutex>, + /// Set while `graph` is recording `f` on the stream. + capturing: AtomicBool, /// Pinned staging for large `htod`, used as a ring: the copy returns before its DMA, so the host fills the next /// one while the GPU works (expert streaming in prefill). Head offset and the regions queued copies still read. ring: std::sync::Mutex<(PinnedHostSlice, usize, VecDeque<(usize, usize, CudaEvent)>)>, @@ -229,9 +241,9 @@ pub fn llama_numerics() -> bool { std::env::var_os("STRATA_LLAMA_NUMERICS").is_s fn parse_kv_mode(s: &str) -> u32 { match s { "q2" => 3, "q4" => 2, "q8" => 1, - "turbo4" | "turboquant" => 4, - "turbo3" => 5, - "turbo2" => 6, + "turbo4" | "turboquant" | "4" => 4, + "turbo3" | "3" => 5, + "turbo2" | "2" => 6, _ => 0, } } @@ -240,9 +252,9 @@ pub fn kv_k_mode() -> u32 { if let Ok(s) = std::env::var("STRATA_KV_K") { return parse_kv_mode(&s); } if let Ok(s) = std::env::var("STRATA_KV") { return match s.as_str() { - "turbo4-3" | "turbo4v3" => 4, "turbo4-2" | "turbo4v2" => 4, - "turbo3-2" | "turbo3v2" => 5, - other => parse_kv_mode(other), + "turbo4v3" | "turbo4v2" => 4, "turbo3v2" => 5, + // "a-b" is a K/V pair ("f16-q8", the legacy "turbo4-3"): each side through the name table. + other => match other.split_once('-') { Some((k, _)) => parse_kv_mode(k), None => parse_kv_mode(other) }, }; } u32::from(std::env::var_os("STRATA_KV_Q8").is_some()) @@ -252,9 +264,8 @@ pub fn kv_v_mode() -> u32 { if let Ok(s) = std::env::var("STRATA_KV_V") { return parse_kv_mode(&s); } if let Ok(s) = std::env::var("STRATA_KV") { return match s.as_str() { - "turbo4-3" | "turbo4v3" => 5, "turbo4-2" | "turbo4v2" => 6, - "turbo3-2" | "turbo3v2" => 6, - other => parse_kv_mode(other), + "turbo4v3" | "turbo3v2" => 5, "turbo4v2" => 6, + other => match other.split_once('-') { Some((_, v)) => parse_kv_mode(v), None => parse_kv_mode(other) }, }; } u32::from(std::env::var_os("STRATA_KV_Q8").is_some()) @@ -401,11 +412,15 @@ fn source_with(k_mode: u32, v_mode: u32, gemm_tc: bool, tune: Tune) -> String { fn attn_prefill_smem(hd: usize) -> usize { attn_prefill_smem_bk(hd, FA_BK) } /// `attn_prefill_smem` for a K/V tile depth of `bk` keys (16 on Turing at head_dim 256, else `FA_BK`). -pub(crate) fn attn_prefill_smem_bk(hd: usize, bk: usize) -> usize { +pub(crate) const fn attn_prefill_smem_bk(hd: usize, bk: usize) -> usize { let pq = hd + ATTN_SMEM_PAD; 2 * (FA_BQ + 2 * bk) * pq + 2 * FA_BQ * (bk + ATTN_SMEM_PAD) } +/// Shared memory one `ink_attn_prefill_128_wm` launch requests: the FA tile at its fixed shapes (64 queries, +/// 32 keys, head_dim 128) plus the f32 score staging and the 64 x 32 relative-bias rows. +pub(crate) const INK_WM_SMEM: usize = attn_prefill_smem_bk(128, FA_BK) + 4 * FA_BQ * (FA_BK + ATTN_SMEM_PAD) + 4 * 64 * 32; + /// The user-facing error for a device `cc` with an NVRTC that cannot target it, `None` when the pair is fine. /// CUDA 13 dropped Volta (and older), not Turing, so an sm_70 device must be compiled by NVRTC 12.x; saying it here keeps NVRTC's own /// `invalid value for --gpu-architecture` from being the first thing the user sees. @@ -478,9 +493,11 @@ pub(crate) fn dyn_shmem_need(name: &str) -> Option<(&'static str, usize)> { else if name.starts_with("attn_decode_gqa") { "attn_decode_gqa*" } else if name.starts_with("gemvn") { "gemvn_*" } else if name.starts_with("mla_attn") { "mla_attn*" } + else if name.starts_with("ink_attn_prefill_128_wm") { "ink_attn_prefill_128_wm" } else { return None }; let need = match family { "attn_prefill_*" => attn_prefill_smem(name["attn_prefill_".len()..].parse::().ok()?), + "ink_attn_prefill_128_wm" => INK_WM_SMEM, "attn_decode_gqa*" => { let hd = name["attn_decode_gqa".len()..].trim_start_matches('4'); let hd = hd.strip_prefix('_')?.parse::().ok()?; @@ -768,7 +785,7 @@ impl Gpu { let ring = std::sync::Mutex::new((unsafe { ctx.alloc_pinned::(RING)? }, 0, VecDeque::new())); let done = ctx.new_event(None)?; let sms = ctx.attribute(sys::CUdevice_attribute::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT)? as usize; - Ok(Gpu { ctx, side: stream.fork()?, copy: stream.fork()?, in_copy: Default::default(), copy_ev: Default::default(), stream, nb: AtomicUsize::new(usize::MAX), fns, i8_gemm, dp4a_gemm, q8, prefill_input: Default::default(), moe_gate_q8: Default::default(), gd: Default::default(), sk: Default::default(), xh: Default::default(), xk: Default::default(), skc: Default::default(), sms, kv_mode: if kv_k_mode == kv_v_mode { kv_k_mode } else { 10 }, kv_k_mode, kv_v_mode, flags, int8_mma, turing, max_smem: max_optin, am, graphs: Default::default(), ring, marks: Default::default(), done, lag: Default::default(), fr: Default::default(), cs: Default::default(), mla_part: Default::default(), pinned: Default::default() }) + Ok(Gpu { ctx, side: stream.fork()?, copy: stream.fork()?, in_copy: Default::default(), copy_ev: Default::default(), stream, nb: AtomicUsize::new(usize::MAX), fns, i8_gemm, dp4a_gemm, q8, prefill_input: Default::default(), moe_gate_q8: Default::default(), gd: Default::default(), sk: Default::default(), xh: Default::default(), xk: Default::default(), skc: Default::default(), sms, kv_mode: if kv_k_mode == kv_v_mode { kv_k_mode } else { 10 }, kv_k_mode, kv_v_mode, flags, int8_mma, turing, max_smem: max_optin, am, graphs: Default::default(), capturing: Default::default(), ring, marks: Default::default(), done, lag: Default::default(), fr: Default::default(), cs: Default::default(), mla_part: Default::default(), pinned: Default::default() }) } fn f(&self, name: &str) -> &CudaFunction { &self.fns[name] } @@ -1305,6 +1322,7 @@ impl Backend for Gpu { max_smem: self.max_smem, am, graphs: Default::default(), + capturing: Default::default(), ring, marks: Default::default(), done, @@ -1466,7 +1484,9 @@ impl Backend for Gpu { // ponytail: a fixed cap; key the graphs without slot numbers if many slots need the graphs' speed. if *SYNC_EACH || std::env::var_os("STRATA_NO_GRAPH").is_some() || self.graphs.lock().unwrap().len() >= GRAPHS_MAX { return f(); } self.stream.begin_capture(sys::CUstreamCaptureMode::CU_STREAM_CAPTURE_MODE_THREAD_LOCAL)?; + self.capturing.store(true, Relaxed); let r = f(); + self.capturing.store(false, Relaxed); let g = self.stream.end_capture(sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH)?; r?; let g = g.ok_or_else(|| anyhow::anyhow!("empty CUDA graph"))?; @@ -1480,6 +1500,7 @@ impl Backend for Gpu { self.graphs.lock().unwrap().insert(key, Graph(g)); Ok(()) } + fn capturing(&self) -> bool { self.capturing.load(Relaxed) } fn graph_drop(&self, key: u64) -> anyhow::Result<()> { self.graphs.lock().unwrap().remove(&key); Ok(()) @@ -2411,12 +2432,12 @@ mod tests { } /// M1-T5, CPU-only: the loaded name list drops `gemmi_*`/`gemmis_*` only on a device where kernels.cu compiles - /// them out. 469 names today (sm_80), 397 on sm_70. + /// them out. 472 names today (sm_80), 400 on sm_70. #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 470); - assert_eq!(sm70.len(), 398); + assert_eq!(sm80.len(), 472); + assert_eq!(sm70.len(), 400); assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmd")), "sm_70 must not load the int8 prefill GEMM: {:?}", sm70.iter().filter(|n| n.starts_with("gemmi")).collect::>()); @@ -2427,7 +2448,7 @@ mod tests { #[test] fn kernel_names_tu11x_dp4a() { let tu11x = super::kernel_names_with(false, true); - assert_eq!(tu11x.len(), 446); + assert_eq!(tu11x.len(), 448); assert!(tu11x.contains(&"gemmi_q4_k".to_string())); assert!(tu11x.contains(&"gemmis_q8_0".to_string())); assert!(tu11x.iter().all(|n| !n.starts_with("gemmd")), @@ -2442,6 +2463,7 @@ mod tests { assert_eq!(super::dyn_shmem_need("attn_prefill_64"), Some(("attn_prefill_*", super::attn_prefill_smem(64)))); assert_eq!(super::dyn_shmem_need("attn_prefill_128"), Some(("attn_prefill_*", super::attn_prefill_smem(128)))); assert_eq!(super::dyn_shmem_need("attn_prefill_256"), Some(("attn_prefill_*", super::attn_prefill_smem(256)))); + assert_eq!(super::dyn_shmem_need("ink_attn_prefill_128_wm"), Some(("ink_attn_prefill_128_wm", super::INK_WM_SMEM))); // attn_decode_gqa: 8 query slices per head group, plus 2 chunks of 32 K and V positions at head_dim 128/256. assert_eq!(super::dyn_shmem_need("attn_decode_gqa_64"), Some(("attn_decode_gqa*", 2048))); assert_eq!(super::dyn_shmem_need("attn_decode_gqa_128"), Some(("attn_decode_gqa*", 36864))); @@ -2612,26 +2634,28 @@ mod tests { #[test] fn ink_flags_parse_ctrl_tile() { // One card: the default is the old kernels (greedy output must match main). - let one = super::InkFlags::from_parts(None, false, None, None, None); - assert!(!one.fast && !one.ctrl_tile && !one.attn_old && !one.attn_kp4); + let one = super::InkFlags::from_parts(None, false, None, None, None, None, None); + assert!(!one.fast && !one.ctrl_tile && !one.attn_old && !one.attn_kp4 && one.attn_g3 && one.attn_wm); // Two cards: `auto` turns the fast kernels on. - let two = super::InkFlags::from_parts(None, true, None, None, None); + let two = super::InkFlags::from_parts(None, true, None, None, None, None, None); assert!(two.fast && two.ctrl_tile && !two.attn_old && !two.attn_kp4); // Explicit opt-in/opt-out and per-kernel overrides. - assert!(super::InkFlags::from_parts(Some("1"), false, None, None, None).fast); - assert!(!super::InkFlags::from_parts(Some("0"), true, None, None, None).fast); - assert!(!super::InkFlags::from_parts(None, true, Some("0"), None, None).ctrl_tile); - let old = super::InkFlags::from_parts(None, true, None, Some("1"), None); + assert!(super::InkFlags::from_parts(Some("1"), false, None, None, None, None, None).fast); + assert!(!super::InkFlags::from_parts(Some("0"), true, None, None, None, None, None).fast); + assert!(!super::InkFlags::from_parts(None, true, Some("0"), None, None, None, None).ctrl_tile); + let old = super::InkFlags::from_parts(None, true, None, Some("1"), None, None, None); assert!(old.attn_old && !old.attn_kp4); - let kp4 = super::InkFlags::from_parts(None, true, None, None, Some("1")); + let kp4 = super::InkFlags::from_parts(None, true, None, None, Some("1"), None, None); assert!(kp4.attn_kp4 && !kp4.attn_old); - let off = super::InkFlags::from_parts(None, true, Some("0"), Some("0"), Some("0")); + assert!(!super::InkFlags::from_parts(None, true, None, None, None, Some("0"), None).attn_g3); + assert!(!super::InkFlags::from_parts(None, true, None, None, None, None, Some("0")).attn_wm); + let off = super::InkFlags::from_parts(None, true, Some("0"), Some("0"), Some("0"), None, None); assert!(!off.ctrl_tile && !off.attn_old && !off.attn_kp4); } #[test] fn ink_q8_dispatch_respects_formats_shapes_and_precedence() { use super::{InkFlags, InkPrefillKernel as P}; - let mut flags = InkFlags::from_parts(None, false, None, None, None); + let mut flags = InkFlags::from_parts(None, false, None, None, None, None, None); assert!(!flags.attn_q8_shared && !flags.attn_q8_hd128); for (shared, decode, want_shared, want_decode) in [ (None, None, true, true), (Some("1"), Some("1"), true, true), diff --git a/src/hip/mod.rs b/src/hip/mod.rs index cfa7119b..4bbd56f9 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -27,6 +27,11 @@ static NO_GRAPH: LazyLock = LazyLock::new(|| { }); /// `STRATA_HIP_TRACE`: name every launch before it goes out, so a fault that kills the process names the kernel. static TRACE: LazyLock = LazyLock::new(|| std::env::var_os("STRATA_HIP_TRACE").is_some()); +// The device the calling thread has selected: `hipSetDevice` is per-thread, so a worker thread that never selected +// the card runs its calls against device 0, where this card's streams, buffers and graphs are unknown. +thread_local! { + static CURRENT_DEV: std::cell::Cell = const { std::cell::Cell::new(-1) }; +} mod ffi; @@ -190,6 +195,7 @@ impl Gpu { }; anyhow::ensure!(device < n, "HIP device {device}: {n} device(s) present"); hip.check(unsafe { (hip.set_device)(device as i32) }, "hipSetDevice")?; + CURRENT_DEV.with(|c| c.set(device as i32)); let arch = hip.arch(device as i32)?; let warp = hip.attribute(ffi::ATTR_WARP_SIZE, device as i32)?; let wave = if warp != 32 && arch.starts_with("gfx10") { 32 } else { warp }; @@ -257,8 +263,19 @@ impl Gpu { pub fn arch(&self) -> &str { &self.arch } + /// Select this card on the calling thread: `Gpu::new` selected it only on its own, and every other thread + /// (the rayon workers among them) starts on device 0. A thread-local read on the hot path, one runtime call + /// per thread. + fn use_dev(&self) { + CURRENT_DEV.with(|c| { + let d = self.device as i32; + if c.get() != d && unsafe { (self.hip.set_device)(d) } == ffi::HIP_SUCCESS { c.set(d); } + }); + } + /// Launch kernel `name` with `cfg`; `args` are the kernel parameters, in order, read from the given addresses. pub fn launch(&self, name: &str, c: LaunchConfig, args: &mut [&mut dyn Any]) -> anyhow::Result<()> { + self.use_dev(); let f = *self.fns.get(name).ok_or_else(|| anyhow::anyhow!("HIP kernel {name} is not loaded"))?; if *TRACE { eprintln!("hip launch {name} grid {:?} block {:?} smem {}", c.grid_dim, c.block_dim, c.shared_mem_bytes); } let mut params: Vec<*mut c_void> = args.iter_mut().map(|a| (*a as *mut dyn Any).cast::()).collect(); @@ -276,6 +293,7 @@ impl Gpu { } fn wait(&self) -> anyhow::Result<()> { + self.use_dev(); self.hip.check(unsafe { (self.hip.stream_sync)(self.side) }, "hipStreamSynchronize(side)")?; self.hip.check(unsafe { (self.hip.stream_sync)(self.stream) }, "hipStreamSynchronize") } @@ -286,6 +304,7 @@ impl Gpu { /// waited on. That over-synchronises, which is safe: the marks exist to save a wait between the two streams, /// never to stand in for one, and no caller may depend on a mark being exactly the point it recorded. fn mark(&self, stream: ffi::Stream) -> anyhow::Result { + self.use_dev(); let i = self.next_mark.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % MARKS; self.marks[i].record(stream)?; Ok(i) @@ -295,6 +314,7 @@ impl Gpu { /// stages the buffer inside the call, and large copies go through the pinned ring so the DMA does not stop the /// host (expert streaming during prefill). fn htod_on(&self, stream: ffi::Stream, src: &[u8], dst: &Buf, off: usize) -> anyhow::Result<()> { + self.use_dev(); anyhow::ensure!(off + src.len() <= dst.len(), "htod: {} bytes at {off} into {}", src.len(), dst.len()); // From a range `pin_host` registered the DMA reads `src` itself: no host copy through the ring, which runs // at ~9 GB/s on one thread where the link takes 14 GB/s (prefill's expert staging). @@ -332,6 +352,7 @@ impl Gpu { /// point, which is past the one asked for. Over-synchronising is safe and costs only a longer wait, where a host /// `hipStreamSynchronize` here would stall the CPU on every layer run of a long prompt. fn wait_mark(&self, stream: ffi::Stream, n: usize) -> anyhow::Result<()> { + self.use_dev(); self.hip.check(unsafe { (self.hip.stream_wait_event)(stream, self.marks[n % MARKS].ev, 0) }, "hipStreamWaitEvent") } @@ -377,6 +398,7 @@ impl Gpu { /// Whether the stream is capturing a graph: no allocation and no synchronous copy may be issued inside one. fn capturing(&self) -> bool { + self.use_dev(); let mut status = 0; unsafe { (self.hip.stream_is_capturing)(self.stream, &mut status) }; status != 0 @@ -386,6 +408,7 @@ impl Gpu { /// While a graph is captured a missing table gives 0 (the kernel computes the frequencies itself) and is made /// after the capture, which `graph` then repeats. fn rope_fr(&self, base: f32, n_rot: usize) -> anyhow::Result { + self.use_dev(); let mut fr = self.fr.lock().unwrap(); if let Some(b) = fr.0.get(&(base.to_bits(), n_rot)) { return Ok(b.addr()) } if self.capturing() { @@ -489,8 +512,17 @@ impl Gpu { fn grid(n: usize) -> LaunchConfig { cfg((n.div_ceil(256) as u32, 1), 256, 0) } /// The decode attention kernel and its key positions per block, chosen as on CUDA (`cuda::Gpu::ink_attn_kernel`). - fn ink_attn_kernel(&self, hd: usize, nr: usize) -> (&'static str, usize) { - crate::cuda::ink_attn_pick(self.kv_mode, self.flags.fast && !self.flags.attn_old, hd, nr) + /// The f16/q8 cache combos CUDA's pick has no kernel for go to `ink_attn_128_g3` too: the kernel handles K and V + /// modes 0/1 natively, but only when the GQA shape and the g3 flag fit (else the scalar kernel, which also reads + /// quantized caches, stays). + fn ink_attn_kernel(&self, hd: usize, nr: usize, nh: usize, nkv: usize) -> (&'static str, usize) { + let (kn, ck) = crate::cuda::ink_attn_pick(self.kv_mode, self.flags.fast && !self.flags.attn_old, hd, nr); + if kn == "ink_attn" && self.kv_mode != 0 && self.kv_k_mode <= 1 && self.kv_v_mode <= 1 + && self.flags.fast && !self.flags.attn_old && self.flags.attn_g3 && hd == 128 && nr <= 32 && nh == 3 * nkv + { + return ("ink_attn_128_g3", 128); + } + (kn, ck) } } @@ -505,7 +537,8 @@ fn ink_flags_from(fast: Option<&str>, fixed: bool, ctrl: Option<&str>, attn_old: Some(_) => true, }; // The tiled pair follows `fast` when `STRATA_CTRL_TILE` is unset, as on CUDA. - crate::cuda::InkFlags::from_parts(Some(if fast { "1" } else { "0" }), false, ctrl, attn_old, attn_kp4) + crate::cuda::InkFlags::from_parts(Some(if fast { "1" } else { "0" }), false, ctrl, attn_old, attn_kp4, + std::env::var("STRATA_DS_ATTN_G3").ok().as_deref(), std::env::var("STRATA_DS_ATTN_WM").ok().as_deref()) } fn ink_flags() -> crate::cuda::InkFlags { @@ -518,6 +551,13 @@ fn ink_flags() -> crate::cuda::InkFlags { ) } +/// Whether the compiled source has the WMMA matrix-core path (see `compat.h`'s `STRATA_WMMA` and the `GEMM_WMMA` +/// line in `source`): only gfx11/gfx12, and off with `STRATA_HIP_WMMA=0`. +fn wmma_on(arch: &str) -> bool { + (arch.starts_with("gfx11") || arch.starts_with("gfx12")) + && std::env::var("STRATA_HIP_WMMA").map_or(true, |v| v != "0") +} + /// Pinned host allocation freed with the runtime that made it. struct PinnedHost { hip: Arc, p: *mut c_void } @@ -647,6 +687,7 @@ impl Backend for Gpu { fn device(&self) -> String { self.hip.device_name(self.device as i32) } fn alloc(&self, bytes: usize) -> anyhow::Result { + self.use_dev(); let b = alloc_raw(&self.hip, bytes)?; self.memset(&b)?; Ok(b) @@ -663,6 +704,7 @@ impl Backend for Gpu { /// `hipHostRegister` of the pages under `data`, read-only when the runtime takes that flag (the model file is /// mapped read-only). fn pin_host(&self, data: &[u8]) -> anyhow::Result { + self.use_dev(); const PAGE: usize = 4096; let (a, b) = (data.as_ptr() as usize, data.as_ptr() as usize + data.len()); if self.pinned.read().unwrap().iter().any(|&(s, e, _)| s <= a && b <= e) { return Ok(true); } @@ -707,6 +749,7 @@ impl Backend for Gpu { } fn dtod(&self, src: &Buf, src_off: usize, dst: &Buf, dst_off: usize, bytes: usize) -> anyhow::Result<()> { + self.use_dev(); anyhow::ensure!(src_off + bytes <= src.len() && dst_off + bytes <= dst.len(), "dtod: {bytes} bytes out of range"); let r = unsafe { (self.hip.memcpy_async)((dst.addr() + dst_off as u64) as *mut c_void, (src.addr() + src_off as u64) as *const c_void, bytes, ffi::MEMCPY_D2D, self.stream) }; @@ -716,10 +759,12 @@ impl Backend for Gpu { /// On the stream, so it is ordered against the copies and launches around it (the plain `hipMemset` goes to the /// null stream and can land after a copy that was queued for the same buffer). fn memset(&self, dst: &Buf) -> anyhow::Result<()> { + self.use_dev(); self.hip.check(unsafe { (self.hip.memset_async)(dst.addr() as *mut c_void, 0, dst.len(), self.stream) }, "hipMemsetAsync") } fn mem_info(&self) -> anyhow::Result<(usize, usize)> { + self.use_dev(); let (mut free, mut total) = (0usize, 0usize); self.hip.check(unsafe { (self.hip.mem_get_info)(&mut free, &mut total) }, "hipMemGetInfo")?; Ok((free.min(drm_free(total, self.pci.as_deref()).unwrap_or(usize::MAX)), total)) @@ -756,8 +801,10 @@ impl Backend for Gpu { /// HIP refuses an allocation on a capturing stream ("operation not permitted when stream is capturing"), where /// CUDA's stream-ordered allocator allows it, so anything a step allocates has to be made before the capture (the /// rope table defers itself, see `rope_fr`). `STRATA_HIP_GRAPH=0` turns capture off. + fn capturing(&self) -> bool { self.capturing() } fn graph(&self, key: u64, f: &mut dyn FnMut() -> anyhow::Result<()>) -> anyhow::Result<()> { use std::sync::atomic::Ordering; + self.use_dev(); if *NO_GRAPH || self.graph_failed.load(Ordering::Relaxed) { return f() } if let Some(g) = self.graphs.lock().unwrap().get(&key) { let r = unsafe { (self.hip.graph_launch)(g.exec, self.stream) }; @@ -809,6 +856,7 @@ impl Backend for Gpu { /// Pinned host memory mapped into the device address space (the CPU expert worker's mailbox). fn host_mailbox(&self, words: usize) -> anyhow::Result<(Buf, *mut u32)> { + self.use_dev(); let n = words.max(1); let mut host: *mut c_void = std::ptr::null_mut(); self.hip.check(unsafe { (self.hip.host_malloc)(&mut host, 4 * n, ffi::HOST_MALLOC_PORTABLE | ffi::HOST_MALLOC_MAPPED) }, "hipHostMalloc")?; @@ -1095,17 +1143,27 @@ impl Backend for Gpu { } fn ink_attn(&self, q: u64, r: u64, sink: u64, gate: u64, k: u64, v: u64, bias: u64, sc: u64, out: u64, rows: usize, at: usize, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize) -> anyhow::Result<()> { - let (kn, ck) = self.ink_attn_kernel(hd, nr); + let (kn, ck) = self.ink_attn_kernel(hd, nr, nh, nkv); let chunks = rows.div_ceil(ck) as u32; - launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, rows as i32, at as i32, 1i32, nkv as i32, hd as i32, nr as i32, ext as i32, 0u64); + let g3 = (kn == "ink_attn_128" || kn == "ink_attn_128_g3") && nh == 3 * nkv && self.flags.attn_g3; + if g3 { + launch!(self, "ink_attn_128_g3", cfg((nkv as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, rows as i32, at as i32, 1i32, nkv as i32, hd as i32, nr as i32, ext as i32, 0u64); + } else { + launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, rows as i32, at as i32, 1i32, nkv as i32, hd as i32, nr as i32, ext as i32, 0u64); + } launch!(self, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), sc, gate, out, chunks as i32, hd as i32); Ok(()) } fn ink_attn_pos(&self, q: u64, r: u64, sink: u64, gate: u64, k: u64, v: u64, bias: u64, sc: u64, out: u64, max_rows: usize, ring: usize, pos_ptr: u64, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize) -> anyhow::Result<()> { - let (kn, ck) = self.ink_attn_kernel(hd, nr); + let (kn, ck) = self.ink_attn_kernel(hd, nr, nh, nkv); let chunks = max_rows.div_ceil(ck) as u32; - launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, 0i32, 0i32, ring.max(1) as i32, nkv as i32, hd as i32, nr as i32, ext as i32, pos_ptr); + let g3 = (kn == "ink_attn_128" || kn == "ink_attn_128_g3") && nh == 3 * nkv && self.flags.attn_g3; + if g3 { + launch!(self, "ink_attn_128_g3", cfg((nkv as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, 0i32, 0i32, ring.max(1) as i32, nkv as i32, hd as i32, nr as i32, ext as i32, pos_ptr); + } else { + launch!(self, kn, cfg((nh as u32, chunks), 128, 0), q, r, sink, k, v, bias, sc, 0i32, 0i32, ring.max(1) as i32, nkv as i32, hd as i32, nr as i32, ext as i32, pos_ptr); + } launch!(self, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), sc, gate, out, chunks as i32, hd as i32); Ok(()) } @@ -1114,6 +1172,16 @@ impl Backend for Gpu { pos: usize, nt: usize, nh: usize, nkv: usize, hd: usize, nr: usize, ext: usize, ring: usize, win: usize) -> anyhow::Result<()> { // The key-parallel kernels are the same choice as CUDA's; they need the f16 cache (kp16/kp are compiled // for KV_MODE 0 only). `win` rides in the kernel's `ring` argument as on CUDA's old path. + // The WMMA flash kernel takes the same shapes on cards with matrix cores; `attn_kp4` is an explicit kp A/B + // and keeps kp16/kp. The kernel reads the bias row tile of at most 32, and handles f16 and q8 cache rows + // on either side (K_MODE/V_MODE 0/1). + if hd == 128 && self.kv_k_mode <= 1 && self.kv_v_mode <= 1 && self.flags.fast && !self.flags.attn_kp4 && !self.flags.attn_old + && self.flags.attn_wm && nr <= 32 && nkv > 0 && nh % nkv == 0 && wmma_on(&self.arch) { + launch!(self, "ink_attn_prefill_128_wm", cfg((nt.div_ceil(64) as u32, nh as u32), 128, crate::cuda::INK_WM_SMEM as u32), + q, r, sink, gate, kc, vc, kc_new, vc_new, bias, out, + pos as i32, nt as i32, nh as i32, nkv as i32, nr as i32, ext as i32, ring.max(1) as i32, win as i32); + return Ok(()); + } if hd == 128 && self.kv_mode == 0 && (self.flags.fast || self.flags.attn_kp4) && !self.flags.attn_old { let (kn, qb) = if self.flags.attn_kp4 { ("ink_attn_prefill_128_kp", 4) } else { ("ink_attn_prefill_128_kp16", 16) }; launch!(self, kn, cfg((nt.div_ceil(qb) as u32, nh as u32), 128, 0), @@ -1512,6 +1580,33 @@ mod tests { } } + /// The q8_0 cache row layout shared by the quantized-KV tests: `hd` int8 values plus one f16 scale per 32 + /// values, quantized like `kv_put`: d = max|x|/127 per block, value round(x/d). + fn q8_rows(vals: &[f32], hd: usize) -> Vec { + let words = hd / 2 + hd / 32; + let mut c = vec![0u16; vals.len() / hd * words]; + for (r, row) in vals.chunks(hd).enumerate() { + for b in 0..hd / 32 { + let blk = &row[b * 32..b * 32 + 32]; + let d = blk.iter().fold(0f32, |m, x| m.max(x.abs())) / 127.0; + c[r * words + hd / 2 + b] = half::f16::from_f32(d).to_bits(); + for (i, &x) in blk.iter().enumerate() { + let q = if d == 0.0 { 0i8 } else { (x / d).round().clamp(-127.0, 127.0) as i8 }; + let v = b * 32 + i; + c[r * words + v / 2] |= (q as u8 as u16) << ((v & 1) * 8); + } + } + } + c + } + + /// The value `ldkv1_at` puts back on a q8_0 row: f16 of the int8 times the block scale. + fn q8_at(c: &[u16], row: usize, w: usize, hd: usize) -> f32 { + let words = hd / 2 + hd / 32; + let byte = ((c[row * words + w / 2] >> ((w & 1) * 8)) as u8) as i8; + half::f16::from_f32(byte as f32 * half::f16::from_bits(c[row * words + hd / 2 + w / 32]).to_f32()).to_f32() + } + /// `attn_prefill_t` end to end (score product, causal softmax, P·V, the epilogue) against a CPU reference, at /// head_dim 128 with three query tiles and five key tiles and at head_dim 256 (the HIP build's 16-key tiles). /// A wrong lane/lane-staging mapping, a lost half of a fragment or a missing key shows up as a large per-element @@ -1523,14 +1618,20 @@ mod tests { let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; let g: &dyn Backend = &gpu; let (nh, nkv) = (4usize, 2usize); + let (km, vm) = (gpu.kv_k_mode, gpu.kv_v_mode); + if km > 1 || vm > 1 { eprintln!("skipping: attn_prefill parity covers f16 and q8 caches"); return; } for (hd, t) in [(128usize, 130usize), (256, 70)] { let scale = 1.0 / (hd as f32).sqrt(); let mut st = 99u32; let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; let q: Vec = (0..t * nh * hd).map(|_| rnd()).collect(); - let kh: Vec = (0..t * nkv * hd).map(|_| f16::from_f32(rnd()).to_bits()).collect(); - let vh: Vec = (0..t * nkv * hd).map(|_| f16::from_f32(rnd()).to_bits()).collect(); + let kvals: Vec = (0..t * nkv * hd).map(|_| rnd()).collect(); + let vvals: Vec = (0..t * nkv * hd).map(|_| rnd()).collect(); + let kh: Vec = if km == 1 { q8_rows(&kvals, hd) } else { kvals.iter().map(|x| f16::from_f32(*x).to_bits()).collect() }; + let vh: Vec = if vm == 1 { q8_rows(&vvals, hd) } else { vvals.iter().map(|x| f16::from_f32(*x).to_bits()).collect() }; let half = |h: u16| f16::from_bits(h).to_f32(); + let kref = |j: usize, kvh: usize, d: usize| if km == 1 { q8_at(&kh, j * nkv + kvh, d, hd) } else { half(kh[(j * nkv + kvh) * hd + d]) }; + let vref = |j: usize, kvh: usize, d: usize| if vm == 1 { q8_at(&vh, j * nkv + kvh, d, hd) } else { half(vh[(j * nkv + kvh) * hd + d]) }; // Reference: the kernel scales Q before rounding it to f16, sums in f32, rounds the weights to f16 to // feed P·V, and divides by the row sum at the end (`out = o * inv` with `inv = sc / den`). let mut want = vec![0f32; t * nh * hd]; @@ -1542,7 +1643,7 @@ mod tests { let mut a = 0f32; for d in 0..hd { a += half(f16::from_f32(q[ti * nh * hd + h * hd + d] * scale).to_bits()) - * half(kh[(j * nkv + kvh) * hd + d]); + * kref(j, kvh, d); } *s = a; } @@ -1552,7 +1653,7 @@ mod tests { for d in 0..hd { let mut a = 0f32; for (j, w) in e.iter().enumerate() { - a += half(f16::from_f32(w / den).to_bits()) * half(vh[(j * nkv + kvh) * hd + d]); + a += half(f16::from_f32(w / den).to_bits()) * vref(j, kvh, d); } want[ti * nh * hd + h * hd + d] = a; } @@ -1578,7 +1679,7 @@ mod tests { } eprintln!("hd {hd} T {t}: max |diff| = {worst:e} at {at} (row {}, head {}, d {}): got {gv_} want {}", at / (nh * hd), (at / hd) % nh, at % hd, want[at]); - assert!(worst < 5e-3, "hd {hd}: max |diff| = {worst} at {at}"); + assert!(worst < if km == 0 && vm == 0 { 5e-3 } else { 5e-2 }, "hd {hd}: max |diff| = {worst} at {at}"); } } @@ -1697,6 +1798,7 @@ mod tests { fn attn_prefill_mask_matches_dense_on_kept_keys() { use half::f16; let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + if gpu.kv_k_mode != 0 || gpu.kv_v_mode != 0 { eprintln!("skipping: the mask test stages f16-shaped KV rows"); return; } let g: &dyn Backend = &gpu; let (nh, nkv, t) = (4usize, 2usize, 200usize); // Blocks 8 (keys 32..35, an even 16-key tile), 13 (keys 52..55, odd tile k0 48) and 37 (keys 148..151, odd @@ -1872,4 +1974,488 @@ mod tests { }; rtc.compile(&source(0, 0, true), "kernels.cu", "gfx1100", &[]).expect("hiprtc compiles kernels.cu for gfx1100"); } + + /// Inkling 2 mini expert GEMV shapes (gate/up IQ2_XS 2304x2304, down IQ4_NL 2304x1152, 8 experts a token), + /// queued back to back, plus a dtod reference. `STRATA_BENCH_DEVICE` picks the card (default 0); + /// `STRATA_RPW_MOE` / `STRATA_GEMV_BLOCK_MOE` apply as in serve. + #[test] + #[ignore] + fn bench_moe_gemv_shapes() { + let dev: usize = std::env::var("STRATA_BENCH_DEVICE").ok().and_then(|v| v.parse().ok()).unwrap_or(0); + let Ok(g) = Gpu::new(dev) else { eprintln!("skipping: no HIP device {dev}"); return }; + let b: &dyn Backend = &g; + let mut st = 12345u32; + let mut rnd = move || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 13) as u8 }; + let a = g.alloc(256 << 20).unwrap(); + let bb = g.alloc(256 << 20).unwrap(); + for _ in 0..3 { b.dtod(&a, 0, &bb, 0, 256 << 20).unwrap(); } + g.sync().unwrap(); + let t = std::time::Instant::now(); + for _ in 0..8 { b.dtod(&a, 0, &bb, 0, 256 << 20).unwrap(); } + g.sync().unwrap(); + eprintln!("dtod reference: {:.1} GB/s", 2.0 * (256 << 20) as f64 * 8.0 / t.elapsed().as_secs_f64() / 1e9); + let k = 8usize; + for (ty, cols, experts) in [(GgmlType::IQ2XS, 2304usize, 16usize), (GgmlType::IQ2XS, 2304, 64), + (GgmlType::IQ4NL, 1152, 16), (GgmlType::IQ4NL, 1152, 64)] { + let (rows, launches) = (2304usize, 300usize); + let stride = ty.row_bytes(cols as u64) * rows; + let gw = g.alloc(stride * experts).unwrap(); + let bytes: Vec = (0..stride * experts).map(|_| rnd()).collect(); + b.htod(&bytes, &gw, 0).unwrap(); + let ids: Vec = (0..k).map(|i| ((i * 5 + 1) % experts) as i32).collect(); + let x: Vec = (0..k * cols).map(|_| (rnd() as f32) / 255.0 - 0.5).collect(); + let gi = g.alloc(4 * k).unwrap(); + let gx = g.alloc(4 * k * cols).unwrap(); + let gy = g.alloc(4 * k * rows).unwrap(); + b.put(&ids, &gi, 0).unwrap(); + b.put(&x, &gx, 0).unwrap(); + let go = || b.moe_gemv(ty, rows, cols, gw.addr(), stride, gi.addr(), k, gx.addr(), cols, k, gy.addr(), None, 0).unwrap(); + for _ in 0..10 { go(); } + g.sync().unwrap(); + let t = std::time::Instant::now(); + for _ in 0..launches { go(); } + g.sync().unwrap(); + let secs = t.elapsed().as_secs_f64(); + eprintln!("moe_gemv {} {}x{} k={} experts={}: {:.0} us a launch, {:.1} GB/s effective", + ty.name(), rows, cols, k, experts, 1e6 * secs / launches as f64, + k as f64 * stride as f64 * launches as f64 / secs / 1e9); + } + let (rows, cols, launches) = (3072usize, 2304usize, 1000usize); + let rb = GgmlType::IQ3S.row_bytes(cols as u64); + let gw = g.alloc(rb * rows).unwrap(); + let bytes: Vec = (0..rb * rows).map(|_| rnd()).collect(); + b.htod(&bytes, &gw, 0).unwrap(); + let x: Vec = (0..cols).map(|_| (rnd() as f32) / 255.0 - 0.5).collect(); + let gx = g.alloc(4 * cols).unwrap(); + let gy = g.alloc(4 * rows).unwrap(); + b.put(&x, &gx, 0).unwrap(); + let w = GpuTensor::new(GgmlType::IQ3S, rows, cols, gw); + for _ in 0..20 { b.gemv(&w, gx.addr(), gy.addr()).unwrap(); } + g.sync().unwrap(); + let t = std::time::Instant::now(); + for _ in 0..launches { b.gemv(&w, gx.addr(), gy.addr()).unwrap(); } + g.sync().unwrap(); + let secs = t.elapsed().as_secs_f64(); + eprintln!("gemv IQ3_S {}x{}: {:.0} us a launch, {:.1} GB/s effective", + rows, cols, 1e6 * secs / launches as f64, rows as f64 * rb as f64 * launches as f64 / secs / 1e9); + for _ in 0..20 { b.rms_norm(gx.addr(), cols, gy.addr(), gy.addr(), cols, cols, 1, 1e-5).unwrap(); } + g.sync().unwrap(); + let t = std::time::Instant::now(); + for _ in 0..launches { b.rms_norm(gx.addr(), cols, gy.addr(), gy.addr(), cols, cols, 1, 1e-5).unwrap(); } + g.sync().unwrap(); + eprintln!("rms_norm n=2304 rows=1: {:.0} us a launch", 1e6 * t.elapsed().as_secs_f64() / launches as f64); + } + + /// `ink_attn_128_g3` (selected by `ink_attn` for nh = 3 nkv) against a CPU copy of the chunked softmax and + /// the merge combination (virtual sink logit 0; `gate` zero makes the sigmoid 0.5). + #[test] + fn ink_attn_decode_g3_matches_cpu() { + use half::f16; + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + let (km, vm) = (gpu.kv_k_mode, gpu.kv_v_mode); + if km > 1 || vm > 1 { eprintln!("skipping: g3 does not run for KV modes K={km} V={vm}"); return; } + let g: &dyn Backend = &gpu; + let (nh, nkv, hd, nr, ext, rows) = (24usize, 8usize, 128usize, 8usize, 64usize, 300usize); + let at = rows - 1; + let chunks = rows.div_ceil(128); + let mut st = 7u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + let q: Vec = (0..nh * hd).map(|_| rnd()).collect(); + let r: Vec = (0..nh * nr).map(|_| rnd() * 0.1).collect(); + let sink: Vec = (0..nh).map(|_| rnd()).collect(); + let gate = vec![0f32; nh * hd]; + let bias: Vec = (0..ext * nr).map(|_| rnd() * 0.2).collect(); + let kvals: Vec = (0..rows * nkv * hd).map(|_| rnd()).collect(); + let vvals: Vec = (0..rows * nkv * hd).map(|_| rnd()).collect(); + let half = |x: u16| f16::from_bits(x).to_f32(); + // The cache as the kernels see it: f16 rows, or q8 rows (see `q8_rows`). + let kc = if km == 1 { q8_rows(&kvals, hd) } else { kvals.iter().map(|x| f16::from_f32(*x).to_bits()).collect() }; + let vc = if vm == 1 { q8_rows(&vvals, hd) } else { vvals.iter().map(|x| f16::from_f32(*x).to_bits()).collect() }; + let kref = |i: usize, kv: usize, d: usize| if km == 1 { q8_at(&kc, i * nkv + kv, d, hd) } else { half(kc[(i * nkv + kv) * hd + d]) }; + let vref = |i: usize, kv: usize, d: usize| if vm == 1 { q8_at(&vc, i * nkv + kv, d, hd) } else { half(vc[(i * nkv + kv) * hd + d]) }; + let scale = 1.0 / (hd as f32).sqrt(); + let mut want = vec![0f32; nh * hd]; + for h in 0..nh { + let kv = h / (nh / nkv); + let qs: Vec = (0..hd).map(|d| q[h * hd + d] * scale).collect(); + let mut parts: Vec<(f32, f32, Vec)> = vec![]; + for c in 0..chunks { + let i0 = c * 128; + let n = 128.min(rows - i0); + let mut l = vec![-3.0e38f32; 128]; + for ii in 0..n { + let i = i0 + ii; + let mut d = 0f32; + for dd in 0..hd { d += qs[dd] * kref(i, kv, dd); } + let dist = at - i; + if dist < ext { for cc in 0..nr { d += r[h * nr + cc] * bias[dist * nr + cc]; } } + l[ii] = d - sink[h]; + } + let mx = l.iter().cloned().fold(f32::NEG_INFINITY, f32::max); + let p: Vec = l.iter().map(|x| (x - mx).exp()).collect(); + let z: f32 = p.iter().sum(); + let mut o = vec![0f32; hd]; + for ii in 0..n { + let i = i0 + ii; + for dd in 0..hd { o[dd] += p[ii] * vref(i, kv, dd); } + } + parts.push((mx, z, o)); + } + let mxc = parts.iter().map(|x| x.0).fold(0f32, f32::max); + let mut z = (-mxc).exp(); + let mut o = vec![0f32; hd]; + for (mx, zc, oc) in &parts { + let e = (mx - mxc).exp(); + z += zc * e; + for dd in 0..hd { o[dd] += oc[dd] * e; } + } + for dd in 0..hd { want[h * hd + dd] = o[dd] / z * 0.5; } + } + let gq = g.alloc(4 * q.len()).unwrap(); + let gr = g.alloc(4 * r.len()).unwrap(); + let gs = g.alloc(4 * sink.len()).unwrap(); + let gg = g.alloc(4 * gate.len()).unwrap(); + let gb = g.alloc(4 * bias.len()).unwrap(); + let gk = g.alloc(2 * kc.len()).unwrap(); + let gv = g.alloc(2 * vc.len()).unwrap(); + let gsc = g.alloc(4 * nh * chunks * (hd + 2)).unwrap(); + let go = g.alloc(4 * want.len()).unwrap(); + g.put(&q, &gq, 0).unwrap(); + g.put(&r, &gr, 0).unwrap(); + g.put(&sink, &gs, 0).unwrap(); + g.put(&gate, &gg, 0).unwrap(); + g.put(&bias, &gb, 0).unwrap(); + g.put(&kc, &gk, 0).unwrap(); + g.put(&vc, &gv, 0).unwrap(); + let (kn0, _) = crate::cuda::ink_attn_pick(gpu.kv_mode, gpu.flags.fast && !gpu.flags.attn_old, hd, nr); + let chosen = if kn0 == "ink_attn" && gpu.kv_mode != 0 && gpu.kv_k_mode <= 1 && gpu.kv_v_mode <= 1 + && gpu.flags.fast && !gpu.flags.attn_old && gpu.flags.attn_g3 && hd == 128 && nr <= 32 && nh == 3 * nkv + { "ink_attn_128_g3" } else { kn0 }; + eprintln!("g3 test launches {chosen}"); + g.ink_attn(gq.addr(), gr.addr(), gs.addr(), gg.addr(), gk.addr(), gv.addr(), gb.addr(), gsc.addr(), + go.addr(), rows, at, nh, nkv, hd, nr, ext).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&go, 0, want.len()).unwrap(); + let mut worst = 0f32; + for i in 0..want.len() { worst = worst.max((got[i] - want[i]).abs()); } + let tol = if km == 0 && vm == 0 { 1e-3 } else { 5e-2 }; + eprintln!("ink_attn_128_g3 (K mode {km}, V mode {vm}): max |diff| = {worst:e}"); + assert!(worst < tol, "g3 decode attention diverges from the CPU reference: {worst}"); + } + + /// Prefill attention at serve chunk shapes (2048-token chunk at pos 20k, nh 24 @ nkv 8): full-attention + /// layers (24576-row ring, no window) and windowed layers (1024-row ring). One launch per layer a chunk. + #[test] + #[ignore] + fn bench_attn_prefill_kp16() { + let dev: usize = std::env::var("STRATA_BENCH_DEVICE").ok().and_then(|v| v.parse().ok()).unwrap_or(0); + let Ok(g) = Gpu::new(dev) else { eprintln!("skipping: no HIP device {dev}"); return }; + let b: &dyn Backend = &g; + let (nh, nkv, hd, nr, ext, nt, pos) = (24usize, 8usize, 128usize, 8usize, 1024usize, 2048usize, 20480usize); + let q: Vec = (0..nt * nh * hd).map(|_| 0.05).collect(); + let r: Vec = (0..nt * nh * nr).map(|_| 0.01).collect(); + let sink: Vec = vec![0f32; nt * nh]; + let gate: Vec = vec![1f32; nt * nh * hd]; + let bias: Vec = vec![0.02f32; ext * nr]; + for (win, ring) in [(0usize, 24576usize), (1024usize, 1024usize)] { + let gq = g.alloc(4 * q.len()).unwrap(); + let gr = g.alloc(4 * r.len()).unwrap(); + let gs = g.alloc(4 * sink.len()).unwrap(); + let gg = g.alloc(4 * gate.len()).unwrap(); + let gb = g.alloc(4 * bias.len()).unwrap(); + let gk = g.alloc(2 * ring * nkv * hd).unwrap(); + let gv = g.alloc(2 * ring * nkv * hd).unwrap(); + let go = g.alloc(4 * q.len()).unwrap(); + b.put(&q, &gq, 0).unwrap(); + b.put(&r, &gr, 0).unwrap(); + b.put(&sink, &gs, 0).unwrap(); + b.put(&gate, &gg, 0).unwrap(); + b.put(&bias, &gb, 0).unwrap(); + let go_ = || b.ink_attn_prefill(gq.addr(), gr.addr(), gs.addr(), gg.addr(), gk.addr(), gv.addr(), 0, 0, + gb.addr(), go.addr(), pos, nt, nh, nkv, hd, nr, ext, ring, win).unwrap(); + for _ in 0..4 { go_(); } + g.sync().unwrap(); + let t = std::time::Instant::now(); + for _ in 0..10 { go_(); } + g.sync().unwrap(); + let us = 1e6 * t.elapsed().as_secs_f64() / 10.0; + eprintln!("attn prefill win {win} ring {ring}: {:.0} us a launch, {:.0} ms for 24 layers a chunk", us, us * 24.0 / 1e3); + } + } + + /// `ink_attn_prefill_128_wm` (selected by `ink_attn_prefill` on WMMA cards) against a two-pass CPU copy: the + /// new-row split (`kc_new` from `pos` on), the ring wrap and the causal/window edge all ride in it. 96 queries + /// start at pos 64, so the first tile is partial and the fresh span crosses a tile boundary. + #[test] + fn ink_attn_prefill_wm_matches_cpu() { + use half::f16; + let Ok(gpu) = Gpu::new(0) else { eprintln!("skipping: no HIP device"); return }; + if !wmma_on(&gpu.arch) { eprintln!("skipping: no WMMA path on {}", gpu.arch); return; } + let (km, vm) = (gpu.kv_k_mode, gpu.kv_v_mode); + if km > 1 || vm > 1 { eprintln!("skipping: the WMMA prefill kernel covers f16 and q8 caches"); return; } + let g: &dyn Backend = &gpu; + let (nh, nkv, hd, nr, ext, nt, pos) = (6usize, 2usize, 128usize, 8usize, 48usize, 96usize, 64usize); + let mut st = 11u32; + let mut rnd = || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + let q: Vec = (0..nt * nh * hd).map(|_| rnd()).collect(); + let r: Vec = (0..nt * nh * nr).map(|_| rnd() * 0.1).collect(); + let sink: Vec = (0..nt * nh).map(|_| rnd()).collect(); + let gate: Vec = (0..nt * nh * hd).map(|_| rnd()).collect(); + let bias: Vec = (0..ext * nr).map(|_| rnd() * 0.2).collect(); + let scale = 1.0 / (hd as f32).sqrt(); + let hb = |x: u16| f16::from_bits(x).to_f32(); + for (win, ring) in [(0usize, 192usize), (64usize, 64usize)] { + let kvals: Vec = (0..ring * nkv * hd).map(|_| rnd()).collect(); + let vvals: Vec = (0..ring * nkv * hd).map(|_| rnd()).collect(); + let knvals: Vec = (0..nt * nkv * hd).map(|_| rnd()).collect(); + let vnvals: Vec = (0..nt * nkv * hd).map(|_| rnd()).collect(); + let kh: Vec = if km == 1 { q8_rows(&kvals, hd) } else { kvals.iter().map(|x| f16::from_f32(*x).to_bits()).collect() }; + let vh: Vec = if vm == 1 { q8_rows(&vvals, hd) } else { vvals.iter().map(|x| f16::from_f32(*x).to_bits()).collect() }; + let kn: Vec = if km == 1 { q8_rows(&knvals, hd) } else { knvals.iter().map(|x| f16::from_f32(*x).to_bits()).collect() }; + let vn: Vec = if vm == 1 { q8_rows(&vnvals, hd) } else { vnvals.iter().map(|x| f16::from_f32(*x).to_bits()).collect() }; + let kval = |src: &Vec, ridx: usize, dd: usize| if km == 1 { q8_at(src, ridx, dd, hd) } else { hb(src[ridx * hd + dd]) }; + let vval = |src: &Vec, ridx: usize, dd: usize| if vm == 1 { q8_at(src, ridx, dd, hd) } else { hb(src[ridx * hd + dd]) }; + let (gq, gr, gs, gg, gb) = (g.alloc(4 * q.len()).unwrap(), g.alloc(4 * r.len()).unwrap(), + g.alloc(4 * sink.len()).unwrap(), g.alloc(4 * gate.len()).unwrap(), g.alloc(4 * bias.len()).unwrap()); + let (gk, gv, gkn, gvn, go) = (g.alloc(2 * kh.len()).unwrap(), g.alloc(2 * vh.len()).unwrap(), + g.alloc(2 * kn.len()).unwrap(), g.alloc(2 * vn.len()).unwrap(), g.alloc(4 * q.len()).unwrap()); + g.put(&q, &gq, 0).unwrap(); + g.put(&r, &gr, 0).unwrap(); + g.put(&sink, &gs, 0).unwrap(); + g.put(&gate, &gg, 0).unwrap(); + g.put(&bias, &gb, 0).unwrap(); + g.put(&kh, &gk, 0).unwrap(); + g.put(&vh, &gv, 0).unwrap(); + g.put(&kn, &gkn, 0).unwrap(); + g.put(&vn, &gvn, 0).unwrap(); + g.ink_attn_prefill(gq.addr(), gr.addr(), gs.addr(), gg.addr(), gk.addr(), gv.addr(), + gkn.addr(), gvn.addr(), gb.addr(), go.addr(), + pos, nt, nh, nkv, hd, nr, ext, ring, win).unwrap(); + g.sync().unwrap(); + let got: Vec = g.get(&go, 0, q.len()).unwrap(); + let mut worst = 0f32; + for t in 0..nt { + for h in 0..nh { + let (kv, idx) = (h / (nh / nkv), t * nh + h); + let qp = pos + t; + let start = if win > 0 && qp + 1 > win { qp + 1 - win } else { 0 }; + let row = |kp: usize| -> usize { if kp >= pos { kp - pos } else if win > 0 { kp % ring } else { kp } }; + let mut m = sink[idx]; + let mut keys = vec![]; + for kp in start..=qp { + let src = if kp >= pos { &kn } else { &kh }; + let ridx = row(kp) * nkv + kv; + let mut d = 0f32; + for dd in 0..hd { d += q[idx * hd + dd] * scale * kval(src, ridx, dd); } + if qp - kp < ext { for c in 0..nr { d += r[idx * nr + c] * bias[(qp - kp) * nr + c]; } } + keys.push((kp, d)); + if d > m { m = d; } + } + let mut l = (sink[idx] - m).exp(); + let mut o = vec![0f32; hd]; + for (kp, d) in &keys { + let p = (d - m).exp(); + l += p; + let src = if *kp >= pos { &vn } else { &vh }; + let ridx = row(*kp) * nkv + kv; + for dd in 0..hd { o[dd] += p * vval(src, ridx, dd); } + } + for dd in 0..hd { + let want = o[dd] / l / (1.0 + (-gate[idx * hd + dd]).exp()); + worst = worst.max((got[idx * hd + dd] - want).abs()); + } + } + } + eprintln!("ink_attn_prefill_128_wm win {win} (K mode {km}, V mode {vm}): max |diff| = {worst:e}"); + assert!(worst < 2e-2, "WMMA prefill attention diverges from the CPU reference (win {win}): {worst}"); + } + } + + /// Decode attention at serve shapes (24 heads on 8 kv, 128-key chunks): the chunk-kernel + merge pair per + /// layer exec at 22.5k rows (full-attention layers) and at 1024 rows (windowed layers). `STRATA_DS_ATTN_G3=0` + /// runs the per-head kernel through the same trait call for the A/B. + #[test] + #[ignore] + fn bench_attn_decode_shapes() { + let dev: usize = std::env::var("STRATA_BENCH_DEVICE").ok().and_then(|v| v.parse().ok()).unwrap_or(0); + let Ok(g) = Gpu::new(dev) else { eprintln!("skipping: no HIP device {dev}"); return }; + let b: &dyn Backend = &g; + let (nh, nkv, hd, nr, ext) = (24usize, 8usize, 128usize, 8usize, 2048usize); + let q: Vec = (0..nh * hd).map(|_| 0.05).collect(); + let r: Vec = (0..nh * nr).map(|_| 0.01).collect(); + let sink = vec![0f32; nh]; + let gate = vec![1f32; nh * hd]; + let bias: Vec = (0..ext * nr).map(|_| 0.02).collect(); + let ring = 24576usize; + let gq = g.alloc(4 * q.len()).unwrap(); + let gr = g.alloc(4 * r.len()).unwrap(); + let gs = g.alloc(4 * sink.len()).unwrap(); + let gg = g.alloc(4 * gate.len()).unwrap(); + let gb = g.alloc(4 * bias.len()).unwrap(); + let gk = g.alloc(2 * ring * nkv * hd).unwrap(); + let gv = g.alloc(2 * ring * nkv * hd).unwrap(); + let go = g.alloc(4 * nh * hd).unwrap(); + b.put(&q, &gq, 0).unwrap(); + b.put(&r, &gr, 0).unwrap(); + b.put(&sink, &gs, 0).unwrap(); + b.put(&gate, &gg, 0).unwrap(); + b.put(&bias, &gb, 0).unwrap(); + for (rows, at) in [(1usize, 0usize), (128usize, 127usize), (1024usize, 1023usize), (11264usize, 11263usize), (22592usize, 22591usize)] { + let chunks = rows.div_ceil(128); + let gsc = g.alloc(4 * nh * chunks * (hd + 2)).unwrap(); + let go_ = || b.ink_attn(gq.addr(), gr.addr(), gs.addr(), gg.addr(), gk.addr(), gv.addr(), + gb.addr(), gsc.addr(), go.addr(), rows, at, nh, nkv, hd, nr, ext).unwrap(); + for _ in 0..4 { go_(); } + g.sync().unwrap(); + let t = std::time::Instant::now(); + for _ in 0..20 { go_(); } + g.sync().unwrap(); + let us = 1e6 * t.elapsed().as_secs_f64() / 20.0; + let g3 = std::env::var("STRATA_DS_ATTN_G3").map_or(true, |v| v != "0"); + // A kv row is 2 x hd halves or 136 B on q8; g3 reads K once and V once, the per-head kernels a K and + // a V walk per query head. + let rowb = |m: u32| if m == 1 { hd + hd / 16 } else { 2 * hd }; + let kb = rows * nkv * (rowb(g.kv_k_mode) + rowb(g.kv_v_mode)) * (if g3 { 1 } else { 3 }); + eprintln!("attn decode rows {rows}: {:.0} us a launch (chunk+merge), {:.0} MB read, {:.1} GB/s effective", + us, kb as f64 / 1e6, kb as f64 / (us * 1e3)); + } + } + + /// The chunk kernel and the merge split apart at large row counts: which half owns the 580 us at 22.5k rows? + #[test] + #[ignore] + fn bench_attn_decode_parts() { + let dev: usize = std::env::var("STRATA_BENCH_DEVICE").ok().and_then(|v| v.parse().ok()).unwrap_or(0); + let Ok(g) = Gpu::new(dev) else { eprintln!("skipping: no HIP device {dev}"); return }; + let b: &dyn Backend = &g; + let (nh, nkv, hd, nr, ext) = (24usize, 8usize, 128usize, 8usize, 2048usize); + let q: Vec = (0..nh * hd).map(|_| 0.05).collect(); + let r: Vec = (0..nh * nr).map(|_| 0.01).collect(); + let sink = vec![0f32; nh]; + let gate = vec![1f32; nh * hd]; + let bias: Vec = (0..ext * nr).map(|_| 0.02).collect(); + let ring = 24576usize; + let gq = g.alloc(4 * q.len()).unwrap(); + let gr = g.alloc(4 * r.len()).unwrap(); + let gs = g.alloc(4 * sink.len()).unwrap(); + let gg = g.alloc(4 * gate.len()).unwrap(); + let gb = g.alloc(4 * bias.len()).unwrap(); + let gk = g.alloc(2 * ring * nkv * hd).unwrap(); + let gv = g.alloc(2 * ring * nkv * hd).unwrap(); + let go = g.alloc(4 * nh * hd).unwrap(); + b.put(&q, &gq, 0).unwrap(); + b.put(&r, &gr, 0).unwrap(); + b.put(&sink, &gs, 0).unwrap(); + b.put(&gate, &gg, 0).unwrap(); + b.put(&bias, &gb, 0).unwrap(); + for (rows, at) in [(1024usize, 1023usize), (11264usize, 11263usize), (22592usize, 22591usize)] { + let chunks = rows.div_ceil(128) as u32; + let gsc = g.alloc(4 * nh * chunks as usize * (hd + 2)).unwrap(); + let chunk = || -> anyhow::Result<()> { + launch!(&g, "ink_attn_128_g3", cfg((nkv as u32, chunks), 128, 0), + gq.addr(), gr.addr(), gs.addr(), gk.addr(), gv.addr(), gb.addr(), gsc.addr(), + rows as i32, at as i32, 1i32, nkv as i32, hd as i32, nr as i32, ext as i32, 0u64); + Ok(()) + }; + let merge = || -> anyhow::Result<()> { + launch!(&g, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), + gsc.addr(), gg.addr(), go.addr(), chunks as i32, hd as i32); + Ok(()) + }; + let pair = || -> anyhow::Result<()> { chunk()?; merge() }; + let runs: [(&str, &dyn Fn() -> anyhow::Result<()>); 3] = + [("chunk", &chunk), ("merge", &merge), ("pair", &pair)]; + for (label, run) in runs { + for _ in 0..4 { run().unwrap(); } + g.sync().unwrap(); + let t = std::time::Instant::now(); + for _ in 0..20 { run().unwrap(); } + g.sync().unwrap(); + eprintln!("attn decode parts rows {rows} {label}: {:.0} us", 1e6 * t.elapsed().as_secs_f64() / 20.0); + } + if rows == 22592 { + // The same launch with the relative-bias read skipped (`ext` 0), and with 200 back-to-back launches. + let chunk0 = || -> anyhow::Result<()> { + launch!(&g, "ink_attn_128_g3", cfg((nkv as u32, chunks), 128, 0), + gq.addr(), gr.addr(), gs.addr(), gk.addr(), gv.addr(), gb.addr(), gsc.addr(), + rows as i32, at as i32, 1i32, nkv as i32, hd as i32, nr as i32, 0i32, 0u64); + Ok(()) + }; + let run = |label: &str, f: &dyn Fn() -> anyhow::Result<()>, n: u32| { + for _ in 0..4 { f().unwrap(); } + g.sync().unwrap(); + let t = std::time::Instant::now(); + for _ in 0..n { f().unwrap(); } + g.sync().unwrap(); + eprintln!("attn decode parts rows {rows} {label}: {:.0} us", 1e6 * t.elapsed().as_secs_f64() / n as f64); + }; + run("chunk ext0", &chunk0, 20); + run("chunk x200", &chunk, 200); + } + } + } + + /// Inkling 2 decode attention projection GEMVs (IQ3_S): gemvq2 Q+gate (3072+3072x2304), gemvq2 K+V (1024+1024), + /// gemv out-proj (2304x3072), gemvq conv-proj (4096+4096x2304). xq is pre-quantized by rms_norm_q as in serve. + /// `STRATA_BENCH_DEVICE` picks the card. + #[test] + #[ignore] + fn bench_attn_gemv_shapes() { + let dev: usize = std::env::var("STRATA_BENCH_DEVICE").ok().and_then(|v| v.parse().ok()).unwrap_or(0); + let Ok(g) = Gpu::new(dev) else { eprintln!("skipping: no HIP device {dev}"); return }; + let b: &dyn Backend = &g; + let mut st = 777u32; + let mut rnd = move || { st = st.wrapping_mul(1664525).wrapping_add(1013904223); (st >> 9) as f32 / 8388608.0 - 0.5 }; + let (n, launches) = (2304usize, 300usize); + let x: Vec = (0..n).map(|_| rnd()).collect(); + let w1: Vec = vec![1.0f32; n]; + let gx = g.alloc(4 * n).unwrap(); + let gw1 = g.alloc(4 * n).unwrap(); + let gxq = g.alloc(16 << 10).unwrap(); + let gy = g.alloc(4 * 8192).unwrap(); + b.put(&x, &gx, 0).unwrap(); + b.put(&w1, &gw1, 0).unwrap(); + b.rms_norm_q(gx.addr(), n, gw1.addr(), gy.addr(), n, n, 1, 1e-5, gxq.addr(), 0).unwrap(); + g.sync().unwrap(); + let mut mk = |rows: usize, cols: usize| -> GpuTensor { + let rb = GgmlType::IQ3S.row_bytes(cols as u64); + let gw = g.alloc(rb * rows).unwrap(); + let bytes: Vec = (0..rb * rows).map(|_| (rnd() * 254.0) as u8).collect(); + b.htod(&bytes, &gw, 0).unwrap(); + GpuTensor::new(GgmlType::IQ3S, rows, cols, gw) + }; + let mut token = 0f64; + for (label, rows_a, rows_b, cols) in [("q+gate", 3072usize, 3072usize, 2304usize), + ("k+v", 1024, 1024, 2304), + ("conv-proj", 4096, 4096, 2304)] { + let (a, bb) = (mk(rows_a, cols), mk(rows_b, cols)); + let bytes = (a.rows + bb.rows) as f64 * GgmlType::IQ3S.row_bytes(cols as u64) as f64; + let go = || b.gemvq2(&a, &bb, gx.addr(), n, gxq.addr(), gy.addr(), gy.addr() + 4 * a.rows as u64, 1).unwrap(); + for _ in 0..10 { go(); } + g.sync().unwrap(); + let t = std::time::Instant::now(); + for _ in 0..launches { go(); } + g.sync().unwrap(); + let secs = t.elapsed().as_secs_f64(); + token += 1e6 * secs / launches as f64; + eprintln!("attn gemv {label} {}+{}x{}: {:.0} us a launch, {:.1} GB/s", + a.rows, bb.rows, cols, 1e6 * secs / launches as f64, bytes * launches as f64 / secs / 1e9); + } + for (label, rows, cols) in [("out-proj", 2304usize, 3072usize), ("rel", 192, 2304), ("sink", 24, 2304)] { + let w = mk(rows, cols); + let bytes = rows as f64 * GgmlType::IQ3S.row_bytes(cols as u64) as f64; + let go = || if label == "out-proj" { b.gemv(&w, gx.addr(), gy.addr()).unwrap() } + else { b.gemvq(&w, gx.addr(), n, gxq.addr(), gy.addr(), rows, 1).unwrap() }; + for _ in 0..10 { go(); } + g.sync().unwrap(); + let t = std::time::Instant::now(); + for _ in 0..launches { go(); } + g.sync().unwrap(); + let secs = t.elapsed().as_secs_f64(); + token += 1e6 * secs / launches as f64; + eprintln!("attn gemv {label} {rows}x{cols}: {:.0} us a launch, {:.1} GB/s", + 1e6 * secs / launches as f64, bytes * launches as f64 / secs / 1e9); + } + eprintln!("attn gemv per instance: {:.0} us, x48 instances a token: {:.1} ms", token, token * 48.0 / 1e3); + } } diff --git a/src/inkling2/forward.rs b/src/inkling2/forward.rs index 06b944f5..cd6986b1 100644 --- a/src/inkling2/forward.rs +++ b/src/inkling2/forward.rs @@ -156,7 +156,7 @@ impl DraftGate { /// use, GPU experts; and the experts `Dev::admit` moved into VRAM. static ADMITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); static HYB: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; -const PROF: [&str; 8] = ["mix", "proj", "scores", "out-proj", "route", "experts-gpu", "experts-cpu", "logits"]; +const PROF: [&str; 11] = ["mix", "proj", "scores", "out-proj", "route", "experts-gpu", "experts-cpu", "logits", "attn", "ffn", "step"]; /// A tensor read from the mapped file only: never uploaded. fn host_mat<'a>(g: &'a Gguf, name: &str) -> Result> { @@ -501,6 +501,9 @@ impl<'a> Inkling2Model<'a> { unsafe { std::env::set_var("STRATA_DS_GPU_FRACTION", "0.6,0.9"); } } let cfg = Inkling2Config::from_gguf(g)?; + crate::say!("inkling2: {} layers (core {}..{} x{}), n_embd {}, n_head {} @ head_dim {}, n_head_kv {}, n_expert {}, used {}, n_ff_exp {}, n_conv {}, window {}", + cfg.n_layer, cfg.loop_start, cfg.loop_end, cfg.loop_count, cfg.n_embd, cfg.n_head, cfg.head_dim, + cfg.n_head_kv, cfg.n_expert, cfg.n_used, cfg.n_ff_exp, cfg.n_conv, cfg.n_swa); let has = |n: &str| g.tensors.contains_key(n); let mut layers = vec![]; for il in 0..cfg.n_layer { diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index d39c75a7..c354eb8b 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -339,19 +339,30 @@ impl Device { pub(super) fn new(m: &Inkling2Model) -> Option { let (c, pos) = (&m.cfg, m.toks.len()); let off = std::env::var("STRATA_DS_DEVICE").is_ok_and(|v| v == "0") || m.trace || std::env::var_os("STRATA_DS_DUMP").is_some(); - if off || c.n_conv > 8 || 128 % c.head_dim != 0 || m.loops.is_empty() { return None; } + let decline = |why: &str| crate::say!("inkling2: device path declined ({why}); the tokens run as prompt chunks do"); + if off { return None; } + if c.n_conv > 8 { decline(&format!("n_conv {}", c.n_conv)); return None; } + if 128 % c.head_dim != 0 { decline(&format!("head_dim {}", c.head_dim)); return None; } + if m.loops.is_empty() { decline("no core loop"); return None; } let rank = m.loops[0].down[0].len() / (2 * c.n_embd); - if !shapes_fit(m, rank) { return None; } + if !shapes_fit(m, rank) { decline("shapes the kernels do not take"); return None; } let (kw, nr, ext) = (c.n_head_kv * c.head_dim, c.n_rel, c.rel_extent); let full = (2 * (pos + 1)).clamp(4096.min(m.max_ctx), m.max_ctx); { - let mut d = dev::get()?.lock().unwrap(); + let Some(g) = dev::get() else { decline("no GPU pool (STRATA_DS_GPU=0?)"); return None }; + let mut d = g.lock().unwrap(); // Local patch: several GPUs are fine as long as the plain weights are on GPU 0 (see STRATA_DS_PLAIN_FIRST); the // experts that live on another GPU run as a third share in `layer`. let dense = |x: &Mat| !x.host_only() && d.on_first(x); - if !dense(&m.output) || !m.layers.iter().all(|l| { - [l.wq, l.wk, l.wv, l.wo, l.gate, l.rel, l.sink].iter().chain(l.conv_proj.iter().flatten()).all(dense) - }) { return None; } + if !dense(&m.output) { decline("the output head is not in VRAM"); return None; } + if let Some((ip, name)) = m.layers.iter().enumerate().find_map(|(ip, l)| { + let bad = [("wq", &l.wq), ("wk", &l.wk), ("wv", &l.wv), ("wo", &l.wo), ("gate", &l.gate), ("rel", &l.rel), ("sink", &l.sink)] + .into_iter().find(|(_, x)| !dense(x)).map(|(n, _)| n) + .or(l.conv_proj.iter().flatten().find(|x| !dense(x)).map(|_| "conv_proj")); + bad.map(|n| (ip, n)) + }) { + decline(&format!("layer {ip} weight {name} is not in VRAM")); return None; + } let rows: usize = (0..c.n_slot()).map(|il| if c.swa[layer_of(c, il)] { c.n_swa } else { full }).sum(); let kv_bytes = 2 * rows * d.parts[0].be.kv_row_words(kw); room(&mut d, kv_bytes + sc_bytes(c, full) + Scratch::at(0, c, rank, m.output.rows).end as usize + (512 << 20)); @@ -505,6 +516,7 @@ impl Device { d.parts[0].budget = d.parts[0].budget.saturating_sub(over); } let all_full = rem.is_none() && (0..c.n_layer).all(|ip| layers[ip].full_exps.is_some() || pool.as_ref().is_some_and(|p| p.layer(ip).is_some())); + crate::say!("inkling2: device path on: expert slabs {n_full}/{}, pool {}, everything on device: {}", n_full, pool.is_some(), all_full); let core = c.loop_end - c.loop_start; let seg_graph = rem.is_some() && std::env::var_os("STRATA_DS_NO_SEG_GRAPH").is_none() && layers.iter().all(|l| l.full_exps.is_some()) @@ -728,11 +740,16 @@ impl Device { if last != 0 && last != key { be.graph_drop(last)?; } if !self.seg_graph { be.graph(key, &mut || { + let prof = std::env::var_os("STRATA_DS_PROF").is_some() && !be.capturing(); + let mut tt = std::time::Instant::now(); let mut nb = 0usize; for il in 0..c.loop_start { self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; + if prof { be.sync()?; m.lap(8, tt); tt = std::time::Instant::now(); } self.layer_ffn_gpu(be, m, il, il)?; + if prof { be.sync()?; m.lap(9, tt); tt = std::time::Instant::now(); } } + if prof { be.sync()?; m.lap(0, tt); tt = std::time::Instant::now(); } be.dtod(&self.scr, (self.s.cur - o) as usize, &self.scr, (self.s.prelude - o) as usize, 4 * n)?; let n_pre = nb; for pass in 0..c.loop_count { @@ -746,6 +763,7 @@ impl Device { be.dtod(&self.scr, (s.prelude - o) as usize, &self.scr, (s.cur - o) as usize, 4 * n)?; nb = n_pre; } + let pt = tt; for ip in c.loop_start..c.loop_end { let il = if pass == 0 { ip } else { c.n_layer + (pass - 1) * core + ip - c.loop_start }; if pass > 0 { @@ -753,17 +771,24 @@ impl Device { be.ink_mix(s.bank, n_bank, s.outb, self.loops[ip - c.loop_start].msg_query.addr(), 4, s.msg, n)?; } self.layer_attn(be, &d, m, il, ip, pass > 0, pos, true, &mut nb)?; + if prof { be.sync()?; m.lap(8, tt); tt = std::time::Instant::now(); } self.layer_ffn_gpu(be, m, il, ip)?; + if prof { be.sync()?; m.lap(9, tt); tt = std::time::Instant::now(); } } + if prof { m.lap(1 + pass, pt); } } for il in c.loop_end..c.n_layer { self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; + if prof { be.sync()?; m.lap(8, tt); tt = std::time::Instant::now(); } self.layer_ffn_gpu(be, m, il, il)?; + if prof { be.sync()?; m.lap(9, tt); tt = std::time::Instant::now(); } } + if prof { be.sync()?; m.lap(4, tt); tt = std::time::Instant::now(); } self.finish_logits(be, &d, m, nb)?; if argmax { be.argmax_rows(self.s.logits, c.n_vocab, 1, self.s.amax)?; } + if prof { be.sync()?; m.lap(7, tt); } Ok(()) })?; } else { @@ -968,7 +993,7 @@ impl Device { if self.all_full || self.seg_graph { let t = std::time::Instant::now(); let (logits, _) = self.step_fast(m, tok, false); - m.lap(7, t); + m.lap(10, t); return logits; } let nb = self.step_layers(m, tok); @@ -992,7 +1017,7 @@ impl Device { if self.all_full || self.seg_graph { let t = std::time::Instant::now(); let (_, id) = self.step_fast(m, tok, true); - m.lap(7, t); + m.lap(10, t); return id; } let nb = self.step_layers(m, tok); diff --git a/src/main.rs b/src/main.rs index 22b01b69..53babbaa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -211,8 +211,9 @@ struct Engine { #[arg(long, value_parser = parse_effort)] reasoning_effort: Option, /// KV cache format (GPU): f16, q8 (q8_0, half KV memory), q4 (q4_0, quarter KV memory), or q2 (2-bit affine, - /// 5.3x smaller KV memory for 512k-1M ctx; numerics differ from f16). - #[arg(long, default_value = "f16", value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo4-3", "turbo4-2", "turbo3", "turbo2", "turbo3-2"])] + /// 5.3x smaller KV memory for 512k-1M ctx; numerics differ from f16). A "K-V" pair like f16-q8 sets the two + /// cache types independently. + #[arg(long, default_value = "f16", value_parser = parse_kv_arg)] kv: String, /// K cache type; overrides the K half of `--kv`. Supported: f16, q8, q4, q2, turbo4, turbo3, turbo2. #[arg(long, value_parser = ["f16", "q8", "q4", "q2", "turbo4", "turbo3", "turbo2"])] @@ -253,13 +254,19 @@ struct Engine { } /// Resolve the independent K and V cache types. `--kv` supplies both unless `--k`/`--v` override a half. +fn parse_kv_arg(s: &str) -> Result { + let valid = |x: &str| matches!(x, "f16" | "q8" | "q4" | "q2" | "turbo4" | "turbo3" | "turbo2" | "4" | "3" | "2"); + if valid(s) || s.split_once('-').is_some_and(|(a, b)| valid(a) && valid(b)) { Ok(s.to_string()) } + else { Err(format!("unsupported --kv {s} (f16, q8, q4, q2, turbo4/3/2 or a pair like f16-q8)")) } +} + fn effective_kv(kv: &str, k: Option<&str>, v: Option<&str>) -> anyhow::Result<(String, String)> { let valid = |s: &str| matches!(s, "f16" | "q8" | "q4" | "q2" | "turbo4" | "turbo3" | "turbo2"); + fn canon(s: &str) -> &str { match s { "4" => "turbo4", "3" => "turbo3", "2" => "turbo2", other => other } } let base = match kv { - "turbo4-3" => ("turbo4", "turbo3"), - "turbo4-2" => ("turbo4", "turbo2"), - "turbo3-2" => ("turbo3", "turbo2"), - other => (other, other), + "turbo4v3" => ("turbo4", "turbo3"), "turbo4v2" => ("turbo4", "turbo2"), "turbo3v2" => ("turbo3", "turbo2"), + // "a-b" is a K/V pair, validated side by side below: "f16-q8", the legacy "turbo4-3" (short V names). + s => match s.split_once('-') { Some((a, b)) => (canon(a), canon(b)), None => (s, s) }, }; let (k, v) = match (k, v) { (None, None) => base, diff --git a/src/model.rs b/src/model.rs index b07822bb..4f530f77 100644 --- a/src/model.rs +++ b/src/model.rs @@ -1866,6 +1866,7 @@ mod tests { #[test] fn sensenova_loop_mhc_cpu_matches_gpu() { + if crate::cuda::kv_mode() != 0 { eprintln!("skipping: quantized KV caches change the numerics"); return; } let dir = std::env::temp_dir().join(format!("strata_snloop_test_{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap();