diff --git a/docs/USAGE.md b/docs/USAGE.md index 6e3033b..deb9c29 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -251,6 +251,39 @@ AMD cards clock down in the gaps while the other card works; `echo high > /sys/class/drm/cardN/device/power_dpm_force_performance_level` (as root, per card) took a two-card split from 44 to 57 tok/s in one report. +### Inkling 2 on several GPUs + +Inkling 2 is the model this work targets, and `--device 0,1` is opt-in: the default is always one card, even on a +machine with two. With two cards the 24 expert layers are placed as whole slabs (the load line says how many and +where), a layer's FFN runs on the card that holds it, and the attention and tail stay on GPU 0. + +`STRATA_DS_FAST_KERNELS` selects the kernels: + +- `auto` (default): the tiled controllers, `ink_attn_128` and the 16-query prefill (`kp16`) only when the run has more + than one device. One card keeps the `main` kernels, so the greedy output does not change. +- `1`: force them on one card (the one-card kernel numbers in the PR). +- `0`: force the old kernels on two cards (the A/B). + +Per-kernel overrides: `STRATA_CTRL_TILE=0` (per-token controllers), `STRATA_DS_ATTN_OLD=1` (scalar decode and +one-query-a-warp prefill), `STRATA_DS_ATTN_KP4=1` (four-query prefill). + +The two-card plan uses these knobs: + +| variable | default | effect | +|---|---|---| +| `STRATA_DS_FAST_KERNELS` | `auto` | as above; one card keeps the old kernels unless forced | +| `STRATA_DS_PLAIN_FIRST` | unset; `chat`/`serve`/`bench` set `1` | keep the plain weights on GPU 0, where the decode state lives | +| `STRATA_DS_PF_TOKENS` | 256 one card, 512 two | tokens of one prompt chunk (at most 2048) | +| `STRATA_DS_KV_TOKENS` | `--ctx` | KV rows GPU 0 must still be able to take before it gives up a slab | +| `STRATA_DS_PROF` | unset | print `inkling2: preloaded N/24 ...` and the per-chunk profile | +| `STRATA_DS_NO_AFFINITY` | unset | pick the GPU per expert instead of per stacked tensor | +| `STRATA_DS_NO_SEG_GRAPH` | unset | do not capture the segmented decode graph | +| `STRATA_CTRL_TILE` | follows `FAST_KERNELS` | `0` forces the per-token controllers | +| `STRATA_DS_ATTN_OLD` | off | `1` keeps the scalar decode and one-query-a-warp prefill | +| `STRATA_DS_ATTN_KP4` | off | `1` selects the four-query 128-key prefill for the A/B | + +`STRATA_INKLING2_MODEL` (path to the GGUF) only selects the model for `tests/inkling2_forward.rs`. + ## Page cache Experts that do not fit in VRAM are read from the GGUF through the page cache. A file system that keeps file data out diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 51ef225..c43547c 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -12,6 +12,7 @@ __device__ __forceinline__ float h2f(u16 h) { return (float)*(const _Float16*)&h __device__ __forceinline__ u16 f2h(float f) { _Float16 x = (_Float16)f; return *(const u16*)&x; } #else __device__ __forceinline__ float h2f(u16 h) { float f; asm("cvt.f32.f16 %0, %1;" : "=f"(f) : "h"(h)); return f; } +__device__ __forceinline__ float2 ink_h2f2(unsigned w) { return make_float2(h2f((u16)(w & 0xFFFFu)), h2f((u16)(w >> 16))); } __device__ __forceinline__ u16 f2h(float f) { u16 h; asm("cvt.rn.f16.f32 %0, %1;" : "=h"(h) : "f"(f)); return h; } #endif __device__ __forceinline__ u32 ld16(const u8* p) { return *(const u16*)p; } // 2-aligned only (every quant field is) @@ -2092,6 +2093,128 @@ extern "C" __global__ void ink_ctrl_out(const u16* gain, const u16* forget, cons out[mo] = x - tanhf(f) * x + tanhf(g) * msg[mo]; } +// The same two controllers for a prompt chunk, tiled over tokens: a block holds 64 tokens of one controller and all +// `rank` rows (a 64 x 64 output tile), so a weight row is read once per 64 tokens where the per-token kernels above +// read it once per token (32x the traffic of the tile, and a block reduction per output). 16 x 16 threads, 4 x 4 +// outputs each; both read and write the layout of the per-token pair, so nothing outside these four kernels changes. +extern "C" __global__ void __launch_bounds__(256) ink_ctrl_gate_b(const u16* down, const float* cur, int nins, + const float* msg, float* gate, int n, int rank, int nt) { + constexpr int BT = 64; + __shared__ __align__(16) float xs[BT][65]; + __shared__ __align__(16) u16 ws[BT][65]; + __shared__ float sc[BT][2]; + const int j = blockIdx.x, t0 = blockIdx.y * BT, tw = 2 * n, count = gridDim.x; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const float* ccur = cur + (size_t)min(j, nins - 1) * nt * n; + const float* cmsg = msg + (size_t)j * nt * n; + // The RMS of both inputs of each token, one warp a token: the per-token kernel folds this into its one dot. + for (int tt = warp; tt < BT; tt += 8) { + const int t = t0 + tt; + float sa = 0.f, sb = 0.f; + if (t < nt) { + const float* c = ccur + (size_t)t * n; + const float* m = cmsg + (size_t)t * n; + for (int i = lane; i < n; i += 32) { sa += c[i] * c[i]; sb += m[i] * m[i]; } + } + sa = warp_sum(sa); sb = warp_sum(sb); + if (lane == 0) { sc[tt][0] = rsqrtf(sa / (float)n + 1e-6f); sc[tt][1] = rsqrtf(sb / (float)n + 1e-6f); } + } + __syncthreads(); + const int ty = tid >> 4, tx = tid & 15; + float acc[4][4]; + for (int i = 0; i < 4; i++) for (int r = 0; r < 4; r++) acc[i][r] = 0.f; + for (int k0 = 0; k0 < tw; k0 += 64) { + for (int i = tid; i < BT * 64; i += 256) { + const int tt = i >> 6, kk = i & 63, t = t0 + tt, k = k0 + kk; + float v = 0.f; + if (t < nt) { + const float* c = ccur + (size_t)t * n; + const float* m = cmsg + (size_t)t * n; + v = k < n ? c[k] * sc[tt][0] : m[k - n] * sc[tt][1]; + } + xs[tt][kk] = v; + } + for (int i = tid; i < 64 * 64; i += 256) { + const int r = i >> 6, kk = i & 63; + ws[r][kk] = r < rank && k0 + kk < tw ? down[((size_t)j * rank + r) * tw + k0 + kk] : (u16)0; + } + __syncthreads(); + for (int k = 0; k < 64; k++) { + float xv[4], wv[4]; +#pragma unroll + for (int i = 0; i < 4; i++) xv[i] = xs[ty * 4 + i][k]; +#pragma unroll + for (int r = 0; r < 4; r++) wv[r] = h2f(ws[tx * 4 + r][k]); +#pragma unroll + for (int i = 0; i < 4; i++) { +#pragma unroll + for (int r = 0; r < 4; r++) acc[i][r] = fmaf(xv[i], wv[r], acc[i][r]); + } + } + __syncthreads(); + } +#pragma unroll + for (int i = 0; i < 4; i++) { + const int t = t0 + ty * 4 + i; + if (t >= nt) break; +#pragma unroll + for (int r = 0; r < 4; r++) { + if (tx * 4 + r < rank) gate[((size_t)t * count + j) * rank + tx * 4 + r] = acc[i][r]; + } + } +} + +extern "C" __global__ void __launch_bounds__(256) ink_ctrl_out_b(const u16* gain, const u16* forget, const float* gate, + const float* cur, int nins, const float* msg, float* out, + int n, int rank, int nt) { + constexpr int BT = 64; + __shared__ __align__(16) float gs[BT][65]; + __shared__ __align__(16) u16 ws[2][BT][65]; + const int j = blockIdx.x, c0 = blockIdx.y * BT, t0 = blockIdx.z * BT, count = gridDim.x; + const int tid = threadIdx.x; + for (int i = tid; i < BT * 64; i += 256) { + const int tt = i >> 6, r = i & 63, t = t0 + tt; + gs[tt][r] = t < nt && r < rank ? gate[((size_t)t * count + j) * rank + r] : 0.f; + } + for (int i = tid; i < BT * 64; i += 256) { + const int r = i >> 6, cc = i & 63, c = c0 + cc; + const bool in = r < rank && c < n; + const size_t at = ((size_t)j * rank + r) * n + c; + ws[0][r][cc] = in ? gain[at] : (u16)0; + ws[1][r][cc] = in ? forget[at] : (u16)0; + } + __syncthreads(); + const int ty = tid >> 4, tx = tid & 15; + float ag[4][4], af[4][4]; + for (int i = 0; i < 4; i++) for (int cc = 0; cc < 4; cc++) { ag[i][cc] = 0.f; af[i][cc] = 0.f; } + for (int r = 0; r < rank; r++) { + float gv[4], wg[4], wf[4]; +#pragma unroll + for (int i = 0; i < 4; i++) gv[i] = gs[ty * 4 + i][r]; +#pragma unroll + for (int cc = 0; cc < 4; cc++) { wg[cc] = h2f(ws[0][r][tx * 4 + cc]); wf[cc] = h2f(ws[1][r][tx * 4 + cc]); } +#pragma unroll + for (int i = 0; i < 4; i++) { +#pragma unroll + for (int cc = 0; cc < 4; cc++) { ag[i][cc] = fmaf(gv[i], wg[cc], ag[i][cc]); af[i][cc] = fmaf(gv[i], wf[cc], af[i][cc]); } + } + } + for (int i = 0; i < 4; i++) { + const int t = t0 + ty * 4 + i; + if (t >= nt) break; + const int c = c0 + tx * 4; + if (c >= n) continue; + float* o = out + ((size_t)j * nt + t) * n + c; + const float* x = cur + ((size_t)min(j, nins - 1) * nt + t) * n + c; + const float* m = msg + ((size_t)j * nt + t) * n + c; + const int cnt = min(4, n - c); + for (int cc = 0; cc < cnt; cc++) { + const float f = fminf(fmaxf(af[i][cc], -10.f), 10.f), g = fminf(fmaxf(ag[i][cc], -10.f), 10.f); + o[cc] = x[cc] - tanhf(f) * x[cc] + tanhf(g) * m[cc]; + } + } +} + // Short causal convolution with a residual (nc at most 8; out may be cur): hist holds the last nc - 1 inputs, the // oldest first, and is advanced by cur. taps ([c / per][lag], lag 0 the current input) may be null. extern "C" __global__ void ink_conv(const float* cur, const float* w, const float* taps, float* hist, float* out, int n, int nc, int per) { @@ -2904,6 +3027,76 @@ extern "C" __global__ void ink_attn(const float* q, const float* r, const float* } } +#if KV_MODE == 0 +// Decode attention for head_dim 128, one query per head, restructured for bandwidth. A 128-thread block owns 128 key +// positions and stages their K rows in shared memory with coalesced 16-byte loads; lane i of warp w scores key +// 32w + i with sixteen 16-byte loads and 128 FMAs, so there is no shuffle per key (one block max and one block sum +// per 128 keys), and V is read 8 bytes a lane, one key at a time, which is coalesced as it is. The kernel above walks +// one key at a time through ldkv1 (a 2-byte load per lane per element) and reads K/V at about 95 GB/s of the card's +// 360: 8.4 ms a token at 24.5k positions, and most of the 21 ms it takes at 200k. +extern "C" __global__ void __launch_bounds__(128) ink_attn_128(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; + __shared__ __align__(16) float qs[HD], rs[32], lg[128], ac[4][HD]; + __shared__ __align__(16) u16 ks[128 * PQ]; + int h = blockIdx.x, kh = h / (gridDim.x / nkv), kw = nkv * HD; + 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; + float* o = sc + ((size_t)h * gridDim.y + blockIdx.y) * (HD + 2); + if (n == 0) { // a chunk past the keys: a neutral partial for the merge (exp(-3e38) is 0) + if (tid < HD) o[2 + tid] = 0.f; + if (tid == 0) { o[0] = -3.0e38f; o[1] = 0.f; } + return; + } + if (tid < HD) qs[tid] = q[h * HD + tid] * rsqrtf((float)HD); + if (tid < nr) rs[tid] = r[h * nr + tid]; + for (int i = tid; i < 128 * 16; i += 128) { + int row = i >> 4, part = i & 15; + uint4 x = make_uint4(0u, 0u, 0u, 0u); + if (row < n) x = *(const uint4*)(k + (size_t)(i0 + row) * kw + kh * HD + part * 8); + *(uint4*)(ks + row * PQ + part * 8) = x; + } + __syncthreads(); + int i = i0 + warp * 32 + lane; + float l = -3.0e38f; + if (i < i0 + n) { + const u16* kr = ks + (warp * 32 + lane) * PQ; + float d = 0.f; + 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); + d += qs[8 * m + 0] * a.x + qs[8 * m + 1] * a.y + qs[8 * m + 2] * b.x + qs[8 * m + 3] * b.y + + qs[8 * m + 4] * c.x + qs[8 * m + 5] * c.y + qs[8 * m + 6] * e.x + qs[8 * m + 7] * e.y; + } + int dist = at - i; if (dist < 0) dist += rows; + if (dist < ext) for (int c = 0; c < nr; c++) d += rs[c] * bias[(size_t)dist * nr + c]; + l = d - sink[h]; + } + float mx = block_max(l); + float p = i < i0 + n ? expf(l - mx) : 0.f; + lg[tid] = p; + float z = block_sum(p); + __syncthreads(); + float a0 = 0.f, a1 = 0.f, a2 = 0.f, a3 = 0.f; + for (int j = warp; j < n; j += 4) { + float pj = lg[j]; + uint2 vw = *(const uint2*)(v + (size_t)(i0 + j) * kw + kh * HD + 4 * lane); + float2 v01 = ink_h2f2(vw.x), v23 = ink_h2f2(vw.y); + a0 += pj * v01.x; a1 += pj * v01.y; a2 += pj * v23.x; a3 += pj * v23.y; + } + *(float4*)&ac[warp][4 * lane] = make_float4(a0, a1, a2, a3); + __syncthreads(); + if (tid < HD) o[2 + tid] = ac[0][tid] + ac[1][tid] + ac[2][tid] + ac[3][tid]; + if (tid == 0) { o[0] = mx; o[1] = z; } +} +#else +// A quantized KV cache keeps the scalar kernel: this entry point is never selected (see ink_attn in cuda/mod.rs). +extern "C" __global__ void __launch_bounds__(128) ink_attn_128(const float*, const float*, const float*, const u16*, + const u16*, const float*, float*, int, int, int, int, int, int, int, const int*) { __trap(); } +#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; const float* p = sc + (size_t)h * chunks * (hd + 2); @@ -2923,8 +3116,8 @@ template __device__ void ink_attn_prefill_t(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) { - int t = blockIdx.x * 4 + (threadIdx.x >> 5), h = blockIdx.y, lane = threadIdx.x & 31; + int pos, int nt, int nh, int nkv, int nr, int ext, int ring, int win, int tbase) { + int t = tbase + (threadIdx.x >> 5), h = blockIdx.y, lane = threadIdx.x & 31; if (t >= nt) return; constexpr int HD = 32 * PER; int kh = h / (nh / nkv), kw = nkv * HD; @@ -2980,9 +3173,185 @@ __device__ void ink_attn_prefill_t(const float* q, const float* r, const float* 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) { \ - ink_attn_prefill_t(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); \ + ink_attn_prefill_t(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); \ } DEF_INK_PREFILL(32) DEF_INK_PREFILL(64) DEF_INK_PREFILL(128) +#if KV_MODE == 0 +// Key-parallel prefill attention for hd = 128 and an f16 cache, QPB queries a warp. The old kernel gave a warp one +// (query, head) and walked the keys one at a time: two warp reductions and a dozen shuffles per key. Here the block's +// four warps share a 32-key K/V tile in shared memory, lane i scores key i of the tile (the 128-long dot product is +// its own, no shuffles), and a warp reduces once per tile for the online softmax. QPB=1 is one query a warp (four a +// block), QPB=4 is four a warp (sixteen a block). Same math, summed in another order. Needs nr <= 32 and +// nr % 4 == 0 (the relative-bias rows are read as float4). +__device__ __forceinline__ float ink_warp_max(float v) { + for (int o = 16; o; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffff, v, o)); + return v; +} +template +__device__ void ink_attn_prefill_kp_t(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, QB = 4 * QPB; + __shared__ __align__(16) u16 ks[32 * PQ], vs[32 * PQ]; + __shared__ __align__(16) float qs[QB][HD], rs[QB][32], ps[QB][32]; + const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31, h = blockIdx.y; + const int t0 = blockIdx.x * QB, qh = warp * QPB; + const int kh = h / (nh / nkv), kw = nkv * HD; + const float scale = 1.f / sqrtf((float)HD); + int start[QPB], qpos[QPB], valid_t[QPB]; + float sk[QPB]; + for (int j = 0; j < QPB; j++) { + const int t = t0 + qh + j; + valid_t[j] = t < nt; + qpos[j] = pos + t; + start[j] = (win > 0 && qpos[j] + 1 > win) ? (qpos[j] + 1 - win) : 0; + sk[j] = 0.f; + if (!valid_t[j]) continue; + const float* qr = q + ((size_t)t * nh + h) * HD; + for (int d = lane; d < HD; d += 32) qs[qh + j][d] = qr[d] * scale; + rs[qh + j][lane] = lane < nr ? r[((size_t)t * nh + h) * nr + lane] : 0.f; + sk[j] = sink[(size_t)t * nh + h]; + } + const int kmax = pos + min(t0 + QB - 1, nt - 1); + const int kmin = (win > 0 && pos + t0 + 1 > win) ? (pos + t0 + 1 - win) : 0; + float m[QPB], l[QPB], acc[QPB][4]; + for (int j = 0; j < QPB; j++) { + m[j] = 0.f; l[j] = 1.f; + for (int i = 0; i < 4; i++) acc[j][i] = 0.f; + } + const int kp_last = qpos[QPB - 1]; + for (int k0 = kmin; k0 <= kmax; k0 += 32) { + __syncthreads(); +#pragma unroll + for (int n = 0; n < 4; n++) { + const int i = tid + n * 128, rr = i >> 4, c = (i & 15) * 8, kp = k0 + rr; + uint4 kv = make_uint4(0, 0, 0, 0), vv = kv; + if (kp <= kmax) { + const bool un = kc_new && kp >= pos; + const size_t row = un ? (size_t)(kp - pos) : (win > 0 ? (size_t)(kp % ring) : (size_t)kp); + const size_t off = row * kw + (size_t)kh * HD + c; + kv = *(const uint4*)((un ? kc_new : kc) + off); + vv = *(const uint4*)((un ? vc_new : vc) + off); + } + *(uint4*)(ks + rr * PQ + c) = kv; + *(uint4*)(vs + rr * PQ + c) = vv; + } + __syncthreads(); + const int kp = k0 + lane; + const u16* kr = ks + lane * PQ; + uint4 krow[HD / 8]; +#pragma unroll + for (int mm = 0; mm < HD / 8; mm++) krow[mm] = *(const uint4*)(kr + 8 * mm); +#pragma unroll + for (int j = 0; j < QPB; j++) { + if (!valid_t[j]) continue; + const float* qj = qs[qh + j]; + float sd = 0.f; +#pragma unroll + for (int mm = 0; mm < HD / 8; mm++) { + const uint4 w = krow[mm]; + const float2 a = ink_h2f2(w.x), b = ink_h2f2(w.y), c2 = ink_h2f2(w.z), e = ink_h2f2(w.w); + sd += qj[8 * mm + 0] * a.x + qj[8 * mm + 1] * a.y + qj[8 * mm + 2] * b.x + qj[8 * mm + 3] * b.y + + qj[8 * mm + 4] * c2.x + qj[8 * mm + 5] * c2.y + qj[8 * mm + 6] * e.x + qj[8 * mm + 7] * e.y; + } + const bool valid = kp >= start[j] && kp <= qpos[j]; + const int dist = qpos[j] - kp; + float b = 0.f; + if (valid && dist < ext) { + const float4* br = (const float4*)(bias + (size_t)dist * nr); + for (int c = 0; c < nr; c += 4) { + const float4 bv = br[c >> 2]; + b += rs[qh + j][c] * bv.x + rs[qh + j][c + 1] * bv.y + rs[qh + j][c + 2] * bv.z + rs[qh + j][c + 3] * bv.w; + } + } + const float logit = valid ? sd + b - sk[j] : -INFINITY; + const float mn = fmaxf(m[j], ink_warp_max(logit)); + const float cc = expf(m[j] - mn); + const float p = valid ? expf(logit - mn) : 0.f; + l[j] = l[j] * cc + warp_sum(p); + m[j] = mn; + acc[j][0] *= cc; acc[j][1] *= cc; acc[j][2] *= cc; acc[j][3] *= cc; + ps[qh + j][lane] = p; + } + __syncwarp(); + const int nk = min(32, kp_last - k0 + 1); + for (int i = 0; i < nk; i++) { + const uint2 vw = *(const uint2*)(vs + i * PQ + 4 * lane); + const float2 v01 = ink_h2f2(vw.x), v23 = ink_h2f2(vw.y); +#pragma unroll + for (int j = 0; j < QPB; j++) { + if (!valid_t[j]) continue; + const float pi = ps[qh + j][i]; + acc[j][0] += pi * v01.x; acc[j][1] += pi * v01.y; acc[j][2] += pi * v23.x; acc[j][3] += pi * v23.y; + } + } + __syncwarp(); + } +#pragma unroll + for (int j = 0; j < QPB; j++) { + if (!valid_t[j]) continue; + const int t = t0 + qh + j; + const float inv = 1.f / l[j]; +#pragma unroll + for (int i = 0; i < 4; i++) { + const size_t idx = ((size_t)t * nh + h) * HD + 4 * lane + i; + outp[idx] = acc[j][i] * inv * sigmoid(gate[idx]); + } + } +} + +// The old kernel stays reachable as ink_attn_prefill_128_old (STRATA_DS_ATTN_OLD=1) and takes the shapes the new one does not. +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_old( + 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) { + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); +} +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp( + 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) { + if (nr <= 32 && (nr & 3) == 0) ink_attn_prefill_kp_t<1>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + else ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); +} +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp16( + 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) { + if (nr <= 32 && (nr & 3) == 0) ink_attn_prefill_kp_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win); + // The 4-query kernel writes four tokens a block; the host launches this entry point with a 16-token grid, so a + // fallback that calls it once would leave tokens 4..15 of every tile unwritten. Four calls cover the whole tile. + else for (int q0 = 0; q0 < 16; q0 += 4) + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 16 + q0); +} +#else +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_old( + 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) { + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); +} +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp( + 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) { + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 4); +} +extern "C" __global__ void __launch_bounds__(128) ink_attn_prefill_128_kp16( + 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) { + for (int q0 = 0; q0 < 16; q0 += 4) + ink_attn_prefill_t<4>(q, r, sink, gate, kc, vc, kc_new, vc_new, bias, outp, pos, nt, nh, nkv, nr, ext, ring, win, blockIdx.x * 16 + q0); +} +#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 5362d9d..c18f543 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -17,18 +17,57 @@ pub(crate) const QTYPES: [GgmlType; 29] = { 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, TQ2_0, TQ2T, TQK6, TQK7, Q4_1, Q5_1, Q4_0, Q5_0, NVFP4] }; -pub(crate) const KERNELS: [&str; 58] = [ +pub(crate) const KERNELS: [&str; 64] = [ "rope_freq", "qsa_pool", "qsa_score", "qsa_select", "rms_norm", "quant_xq", "argmax_part", "argmax_rows", "l2_norm", "rope_neox", "rms_norm_rope", "add", "swiglu", "situ", "situ_q", "softcap", "swiglu_q", "ssm_gates", "conv_silu", "deltanet_seq", "norm_gate", "kv_store", "attn_merge", "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", "hc_silu", "hc_mix", "hc_write", "ple_gate", "ple_conv", "dflash2_conv", "hadamard", - "ink_mix", "ink_ctrl_gate", "ink_ctrl_out", "ink_conv", "ink_conv_batch", "ink_clip", "ink_attn", "ink_attn_merge", - "ink_attn_prefill_32", "ink_attn_prefill_64", "ink_attn_prefill_128", "ink_attn_prefill_sh_32", "ink_attn_prefill_sh_64", "ink_attn_prefill_sh_128", "ink_ffn_sum", "ink_route", "attn_sel", + "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_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_sh_32", "ink_attn_prefill_sh_64", "ink_attn_prefill_sh_128", "ink_ffn_sum", "ink_route", "attn_sel", ]; pub use crate::backend::{ATT_GQA_MIN, ATT_SPLITS, GEMM_BM, GpuTensor}; use crate::backend::ATT_SPLITS_1; +/// Kernel-choice flags read from the environment once, when the `Gpu` is made: they sit on the token path, so a +/// lookup per launch is not worth it. +#[derive(Clone, Copy)] +struct InkFlags { + /// `STRATA_DS_FAST_KERNELS=auto` (default) uses the tiled controllers, `ink_attn_128` and `kp16` only when + /// the run has more than one device; `1` forces them on, `0` forces the old kernels. One card keeps the + /// `main` kernels (the greedy output must not change). + fast: bool, + /// `STRATA_CTRL_TILE=0` forces the per-token `ink_ctrl_*` pair; unset follows `fast`. + ctrl_tile: bool, + /// `STRATA_DS_ATTN_OLD=1` keeps the scalar/one-query-a-warp attention kernels for a measurement window. + attn_old: bool, + /// `STRATA_DS_ATTN_KP4=1` selects the four-query 128-key tile prefill kernel. + attn_kp4: bool, +} + +impl InkFlags { + fn from_parts(fast: Option<&str>, multi: bool, ctrl: Option<&str>, attn_old: Option<&str>, attn_kp4: 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) } + } + fn from_env() -> Self { + let multi = std::env::var("STRATA_DS_DEVICES") + .map_or(false, |v| v.split(',').filter(|d| !d.trim().is_empty()).count() > 1); + Self::from_parts( + std::env::var("STRATA_DS_FAST_KERNELS").ok().as_deref(), + multi, + 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(), + ) + } +} + pub struct Gpu { pub ctx: Arc, pub stream: Arc, @@ -47,6 +86,8 @@ pub struct Gpu { gd: std::sync::OnceLock>, /// The kernels were compiled for KV cache mode (0 = f16, 1 = q8, 2 = q4). pub kv_mode: u32, + /// The environment's kernel-choice flags, read once at creation. + flags: InkFlags, /// The GPU has int8 tensor-core mma (sm_80+). Turing runs the prefill GEMM on the f16 path instead. pub int8_mma: bool, /// sm_75: m16n8k8 mma, 64 KB of shared memory a block (no int8 mma, unlike sm_80+; unlike sm_70 it has no m8n8k4). @@ -532,7 +573,7 @@ impl Gpu { let am = stream.alloc_zeros(64 * AMAX_PARTS)?; let ring = std::sync::Mutex::new((unsafe { ctx.alloc_pinned::(RING)? }, 0, VecDeque::new())); let done = ctx.new_event(None)?; - Ok(Gpu { ctx, side: stream.fork()?, stream, nb: AtomicUsize::new(usize::MAX), fns, i8_gemm, q8, gd: Default::default(), kv_mode, int8_mma, turing, max_smem: max_optin, am, graphs: Default::default(), ring, done, lag: Default::default(), fr: Default::default() }) + Ok(Gpu { ctx, side: stream.fork()?, stream, nb: AtomicUsize::new(usize::MAX), fns, i8_gemm, q8, gd: Default::default(), kv_mode, flags: InkFlags::from_env(), int8_mma, turing, max_smem: max_optin, am, graphs: Default::default(), ring, done, lag: Default::default(), fr: Default::default() }) } fn f(&self, name: &str) -> &CudaFunction { &self.fns[name] } @@ -781,6 +822,16 @@ impl Gpu { } } +impl Gpu { + /// The decode attention entry point and its key positions per block: the f16 head_dim 128 kernel scores a + /// 128-key tile a block, the scalar one 64 keys (`STRATA_DS_ATTN_OLD=1` keeps it for a measurement window; + /// the flag is cached in `flags` at `Gpu` creation). The 128-key kernel keeps the relative-bias row in 32 + /// shared floats, so a wider `nr` uses the scalar kernel. + pub(crate) fn ink_attn_kernel(&self, hd: usize, nr: usize) -> (&'static str, usize) { + if hd == 128 && nr <= 32 && self.kv_mode == 0 && self.flags.fast && !self.flags.attn_old { ("ink_attn_128", 128) } else { ("ink_attn", 64) } + } +} + impl Backend for Gpu { fn name(&self) -> &'static str { "cuda" } fn device(&self) -> String { self.ctx.name().unwrap_or_default() } @@ -799,6 +850,7 @@ impl Backend for Gpu { q8, gd: Default::default(), kv_mode: self.kv_mode, + flags: self.flags, int8_mma: self.int8_mma, turing: self.turing, max_smem: self.max_smem, @@ -1106,6 +1158,18 @@ impl Backend for Gpu { Ok(()) } fn ink_ctrl_n(&self, down: u64, gain: u64, forget: u64, cur: u64, nins: usize, msg: u64, gate: u64, out: u64, n: usize, rank: usize, count: usize, nt: usize) -> anyhow::Result<()> { + // A prompt chunk uses the tiled pair (a weight row is read once per 64 tokens); a decoded token the + // per-token pair, which has no tile to reuse. Both pairs read and write the same gate layout. + // STRATA_CTRL_TILE=0 forces the per-token pair, to compare the two on the same text (the flag is cached + // in `flags` at `Gpu` creation). + let tiled = nt >= 64 && rank <= 64 && n % 64 == 0 && self.flags.ctrl_tile; + if tiled { + let g1 = cfg((count as u32, nt.div_ceil(64) as u32), 256, 0); + let g2 = LaunchConfig { grid_dim: (count as u32, n.div_ceil(64) as u32, nt.div_ceil(64) as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; + launch!(self, "ink_ctrl_gate_b", g1, down, cur, nins as i32, msg, gate, n as i32, rank as i32, nt as i32); + launch!(self, "ink_ctrl_out_b", g2, gain, forget, gate, cur, nins as i32, msg, out, n as i32, rank as i32, nt as i32); + return Ok(()); + } let g1 = LaunchConfig { grid_dim: (rank as u32, count as u32, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; let g2 = LaunchConfig { grid_dim: (n.div_ceil(256) as u32, count as u32, nt as u32), block_dim: (256, 1, 1), shared_mem_bytes: 0 }; launch!(self, "ink_ctrl_gate", g1, down, cur, nins as i32, msg, gate, n as i32, rank as i32, nt as i32); @@ -1130,7 +1194,7 @@ impl Backend for Gpu { pos0: usize, log_alpha: f32, log_floor: f32, ) -> anyhow::Result<()> { anyhow::ensure!(w <= 128, "ink_clip_n: w={w} > 128"); - anyhow::ensure!(kv_mode() == 0 || dst == 0 || w % 32 == 0, "ink_clip_n: quantized KV requires w % 32 == 0 (got {w})"); + anyhow::ensure!(self.kv_mode == 0 || dst == 0 || w % 32 == 0, "ink_clip_n: quantized KV requires w % 32 == 0 (got {w})"); let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; launch!(self, "ink_clip", cfg((rows as u32, nt as u32), 128, 0), @@ -1144,7 +1208,7 @@ impl Backend for Gpu { pos_ptr: u64, log_alpha: f32, log_floor: f32, ) -> anyhow::Result<()> { anyhow::ensure!(w <= 128, "ink_clip_pos: w={w} > 128"); - anyhow::ensure!(kv_mode() == 0 || dst == 0 || w % 32 == 0, "ink_clip_pos: quantized KV requires w % 32 == 0 (got {w})"); + anyhow::ensure!(self.kv_mode == 0 || dst == 0 || w % 32 == 0, "ink_clip_pos: quantized KV requires w % 32 == 0 (got {w})"); let ring = if dst != 0 { dst_ring.max(1) } else { 1 }; let fl = if log_alpha == 0.0 && log_floor == 0.0 { 1.0 } else { log_floor }; launch!(self, "ink_clip", cfg((rows as u32, nt as u32), 128, 0), @@ -1152,14 +1216,16 @@ impl Backend for Gpu { Ok(()) } 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 chunks = rows.div_ceil(64) as u32; - launch!(self, "ink_attn", 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 (kn, ck) = self.ink_attn_kernel(hd, nr); + 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); 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 chunks = max_rows.div_ceil(64) as u32; - launch!(self, "ink_attn", 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 (kn, ck) = self.ink_attn_kernel(hd, nr); + 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); launch!(self, "ink_attn_merge", cfg((nh as u32, 1), 128, 0), sc, gate, out, chunks as i32, hd as i32); Ok(()) } @@ -1169,7 +1235,18 @@ impl Backend for Gpu { ) -> anyhow::Result<()> { anyhow::ensure!(matches!(hd, 32 | 64 | 128), "ink_attn_prefill: unsupported hd={hd}"); let g = nh / nkv.max(1); - if win == 0 && nkv > 0 && nh % nkv == 0 && g <= 4 { + if hd == 128 && self.kv_mode == 0 && (self.flags.fast || self.flags.attn_kp4) && !self.flags.attn_old { + // The key-parallel kernels: kp16 (16 queries a block) by default, kp (4) for the A/B. The wrapper + // falls back to the four-query template for a relative-bias width it cannot read as float4. + 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), + 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); + } else if hd == 128 && self.flags.attn_old { + launch!(self, "ink_attn_prefill_128_old", cfg((nt.div_ceil(4) as u32, nh as u32), 128, 0), + 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); + } else if win == 0 && nkv > 0 && nh % nkv == 0 && g <= 4 { // Every key: a block is one K/V head and `tb` tokens, with 32 keys of K and V in shared memory. let tb = (32 / g).min(8); launch!(self, &format!("ink_attn_prefill_sh_{hd}"), cfg((nt.div_ceil(tb) as u32, nkv as u32), (32 * tb * g) as u32, (2 * 32 * hd * 4) as u32), @@ -1539,8 +1616,8 @@ mod tests { #[test] fn kernel_names() { let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true)); - assert_eq!(sm80.len(), 397); - assert_eq!(sm70.len(), 328); + assert_eq!(sm80.len(), 403); + assert_eq!(sm70.len(), 334); 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::>()); @@ -1717,4 +1794,26 @@ mod tests { assert_eq!(super::smem_log("attn_decode_*", 98304, 2112, None, None), "cuda shared memory: opt-in 98304 B per block, attn_decode_*: 2112 B static, dynamic max default (48 KiB), carveout default"); } + + /// `STRATA_CTRL_TILE` is read as text: unset or any value but "0" keeps the tiled `ink_ctrl_*` pair. The + /// attention flags are plain presence checks and must pass through unchanged. + #[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); + // Two cards: `auto` turns the fast kernels on. + let two = super::InkFlags::from_parts(None, true, 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!(old.attn_old && !old.attn_kp4); + let kp4 = super::InkFlags::from_parts(None, true, None, None, Some("1")); + assert!(kp4.attn_kp4 && !kp4.attn_old); + let off = super::InkFlags::from_parts(None, true, Some("0"), Some("0"), Some("0")); + assert!(!off.ctrl_tile && !off.attn_old && !off.attn_kp4); + } } diff --git a/src/deepseek/mat.rs b/src/deepseek/mat.rs index 7e2f839..d885cf0 100644 --- a/src/deepseek/mat.rs +++ b/src/deepseek/mat.rs @@ -21,14 +21,14 @@ pub(crate) mod dev { const SHIFT: u32 = 24; pub fn gpu_of(id: u32) -> usize { (id >> SHIFT) as usize } pub(crate) struct Part { pub(crate) be: Box, ts: Vec, x: Buf, y: Buf, stage: Buf, bytes: usize, pub(crate) budget: usize, room: usize } - pub struct SlabBuf { buf: Buf, bytes: usize, freed: std::sync::Arc } + pub struct SlabBuf { buf: Buf, bytes: usize, acct: usize, freed: std::sync::Arc } impl SlabBuf { pub fn addr(&self) -> u64 { self.buf.addr() } pub fn len(&self) -> usize { self.bytes } } impl Drop for SlabBuf { fn drop(&mut self) { - self.freed.fetch_add(self.bytes, std::sync::atomic::Ordering::Relaxed); + self.freed.fetch_add(self.acct, std::sync::atomic::Ordering::Relaxed); } } #[derive(Default)] @@ -42,6 +42,11 @@ pub(crate) mod dev { now: u64, cur: usize, lookups: u64, + /// Local patch (multi-GPU): the stacked expert tensor (base address, bytes) of the expert being looked up. + group: Option<(usize, usize)>, + /// Local patch: stacked expert tensor base address -> GPU that holds all of its experts; bytes promised per GPU. + aff: std::collections::HashMap, + aff_bytes: Vec, } static DEV: LazyLock> = LazyLock::new(Default::default); /// Whether `DEV` is open: None before the first `get` and after `free`. @@ -68,12 +73,44 @@ pub(crate) mod dev { let f: Vec = v.split(',').filter_map(|p| p.trim().parse().ok()).collect(); match f[..] { [small, large] => if free < 8 << 30 { small } else { large }, [v] => v, _ => 0.8 } } + /// Free VRAM GPU 0 keeps after the plain weights for the decode state, the KV growth and the prefill scratch. + /// Those buffers are allocated outside the weight budget, so the reserve is checked against live free VRAM. + const STATE_RESERVE: usize = 768 << 20; + /// Whether `len` more plain-weight bytes fit GPU 0's budget and still leave `STATE_RESERVE` free there. + fn plain_first_fits(bytes: usize, len: usize, budget: usize, free: usize) -> bool { + bytes.saturating_add(len) <= budget && free >= len.saturating_add(STATE_RESERVE) + } + fn plain_first_enabled_from(v: Option<&str>) -> bool { v.is_some_and(|v| v != "0") } + fn plain_first_enabled() -> bool { plain_first_enabled_from(std::env::var("STRATA_DS_PLAIN_FIRST").ok().as_deref()) } #[test] fn gpu_fraction_takes_one_value_or_a_pair() { let gb = |n: usize| n << 30; assert_eq!([gpu_fraction("", gb(4)), gpu_fraction("0.9", gb(4)), gpu_fraction("x", gb(4))], [0.8, 0.9, 0.8]); assert_eq!([gpu_fraction("0.6,0.9", gb(4)), gpu_fraction("0.6, 0.9", gb(11))], [0.6, 0.9]); } + #[test] + fn plain_first_reserves_the_state() { + let budget = 1 << 30; + assert!(plain_first_fits(0, 100, budget, 100 + STATE_RESERVE)); + assert!(!plain_first_fits(0, 100, budget, 100 + STATE_RESERVE - 1)); // free VRAM too low + assert!(!plain_first_fits(budget, 100, budget, 1 << 40)); // budget full + } + #[test] + fn plain_first_env_zero_is_off() { + assert!(!plain_first_enabled_from(None)); + assert!(!plain_first_enabled_from(Some("0"))); + assert!(plain_first_enabled_from(Some("1"))); + } + #[test] + fn expert_group_is_consumed_on_a_cache_hit() { + let mut d = Dev::default(); + let data = vec![0u8; 8]; + let k = data.as_ptr() as usize; + d.ex.insert(k, 0); + d.exs.push((0, k, 1, 1.0)); + assert_eq!(d.expert_grouped((0x1000, 64), &data, GgmlType::F32, 0, 0, 1.0, false), Some(0)); + assert!(d.group.is_none()); + } fn open() -> Option { // Unset or 0: every matvec runs on the CPU. if std::env::var("STRATA_DS_GPU").map_or(true, |v| v == "0") { return None; } @@ -138,26 +175,42 @@ pub(crate) mod dev { /// Allocates and uploads a contiguous buffer inside GPU 0 when both `p.budget` and live `mem_info()` keep the /// given byte reserves free. Static mmap slices with `cache_key` deduplicate across multiple model instances. pub fn alloc_slab(&mut self, data: &[u8], cache_key: Option<(usize, usize)>, budget_reserve: usize, free_reserve: usize) -> Option> { + self.alloc_slab_on(0, data, cache_key, budget_reserve, free_reserve) + } + /// `alloc_slab` on GPU `d`. Local patch (Inkling 2 on two GPUs): a slab on a GPU other than 0 is checked against + /// the live free VRAM only, and stays out of the expert budget bookkeeping (which `freed` tracks for GPU 0). + pub fn alloc_slab_on(&mut self, d: usize, data: &[u8], cache_key: Option<(usize, usize)>, budget_reserve: usize, free_reserve: usize) -> Option> { self.reclaim(); + let cache_key = cache_key.map(|k| (k.0, k.1 | d << 60)); if let Some(k) = cache_key && let Some(hit) = self.slabs.get(&k).and_then(std::sync::Weak::upgrade) { return Some(hit); } - let p = self.parts.first_mut()?; - if p.bytes + data.len() + budget_reserve > p.budget { return None; } + let p = self.parts.get_mut(d)?; + if d == 0 && p.bytes + data.len() + budget_reserve > p.budget { return None; } if let Ok((free, _)) = p.be.mem_info() && free < data.len() + free_reserve { return None; } let b = p.be.alloc(data.len()).ok()?; if p.be.htod(data, &b, 0).is_err() { return None; } - p.bytes += data.len(); - let arc = std::sync::Arc::new(SlabBuf { buf: b, bytes: data.len(), freed: self.freed.clone() }); + if d == 0 { p.bytes += data.len(); } + let arc = std::sync::Arc::new(SlabBuf { buf: b, bytes: data.len(), acct: if d == 0 { data.len() } else { 0 }, freed: self.freed.clone() }); if let Some(k) = cache_key { self.slabs.retain(|_, v| v.strong_count() > 0); self.slabs.insert(k, std::sync::Arc::downgrade(&arc)); } Some(arc) } + /// Free VRAM of GPU `d` now, in bytes. + pub fn free_on(&self, d: usize) -> usize { self.parts.get(d).and_then(|p| p.be.mem_info().ok()).map_or(0, |m| m.0) } /// The GPU that takes `len` more bytes of plain weights: the current one while they fit, then the next; the last takes all. pub fn pick(&mut self, len: usize) -> usize { self.reclaim(); + // Local patch (Inkling 2 on several GPUs): the decode state lives on GPU 0 and reads the plain weights + // there, so they stay on GPU 0 while the budget has room and the live free VRAM keeps the state reserve. + // The state, KV and prefill scratch are allocated outside the budget; `room` alone would move the plain + // weights to GPU 1 (it is ~0.4 GB at 0.9), which is what this branch avoids. + if self.parts.len() > 1 && self.cur == 0 && plain_first_enabled() { + let free = self.parts[0].be.mem_info().map_or(usize::MAX, |m| m.0); + if plain_first_fits(self.parts[0].bytes, len, self.parts[0].budget, free) { return 0; } + } while self.cur + 1 < self.parts.len() && self.parts[self.cur].bytes + len > self.parts[self.cur].room { self.cur += 1; } self.cur } @@ -209,7 +262,27 @@ pub(crate) mod dev { /// `evict` false: a miss with no free room returns None, so the caller can run that expert on the CPU. /// Whether the expert that starts at `data` has a VRAM slot (no lookup is counted). pub fn resident(&self, data: &[u8]) -> bool { self.ex.contains_key(&(data.as_ptr() as usize)) } + /// The GPU that holds the experts of the stacked tensor at `base` (`len` bytes): picked on first sight as the + /// GPU with the smallest share of its expert budget already promised. None with one GPU or + /// STRATA_DS_NO_AFFINITY set (the old per-expert choice). + fn affinity(&mut self, base: usize, len: usize) -> Option { + let n = self.parts.len(); + if n < 2 || std::env::var_os("STRATA_DS_NO_AFFINITY").is_some() { return None; } + if let Some(&d) = self.aff.get(&base) { return Some(d); } + if self.aff_bytes.len() != n { self.aff_bytes = vec![0; n]; } + let frac = |d: usize| self.aff_bytes[d] as f64 / self.parts[d].budget.max(1) as f64; + let d = (0..n).min_by(|&a, &b| frac(a).total_cmp(&frac(b)))?; + self.aff_bytes[d] += len; + self.aff.insert(base, d); + Some(d) + } + /// `expert` for an expert that belongs to the stacked tensor (`base`, `len`): see `affinity`. + pub fn expert_grouped(&mut self, group: (usize, usize), data: &[u8], ty: GgmlType, rows: usize, cols: usize, scale: f32, evict: bool) -> Option { + self.group = Some(group); + self.expert(data, ty, rows, cols, scale, evict) + } pub fn expert(&mut self, data: &[u8], ty: GgmlType, rows: usize, cols: usize, scale: f32, evict: bool) -> Option { + let group = self.group.take(); self.reclaim(); let k = data.as_ptr() as usize; self.now += 1; @@ -223,8 +296,14 @@ pub(crate) mod dev { return Some(self.exs[p].0); } EX_LOOKUPS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + // Local patch: all experts of one stacked tensor (a layer's gate_up or down) go to the same GPU, so a + // layer's matvecs hit `batch_mats`' single-GPU path instead of two sequential batches with two readbacks. + // The GPU with the most free budget used to win per expert, which spread every layer over both cards. + let pref = group.and_then(|(base, len)| self.affinity(base, len)); let room = |p: &Part| (p.bytes + data.len() <= p.budget).then(|| p.budget - p.bytes); - if let Some(d) = (0..self.parts.len()).filter_map(|d| room(&self.parts[d]).map(|r| (r, d))).max().map(|(_, d)| d) { + let pick = pref.filter(|&d| room(&self.parts[d]).is_some()) + .or_else(|| (0..self.parts.len()).filter_map(|d| room(&self.parts[d]).map(|r| (r, d))).max().map(|(_, d)| d)); + if let Some(d) = pick { let i = self.upload_on(d, data, ty, rows, cols, scale)?; self.ex.insert(k, self.exs.len()); self.exs.push((i, k, now, 1.0)); @@ -341,6 +420,8 @@ pub(crate) mod dev { drop(owned); Some(y) } + /// Whether `m` lives in VRAM of the first GPU (a staged matrix is copied up to it per use). + pub fn on_first(&self, m: &Mat) -> bool { self.part_of(m) == Some(0) } fn part_of(&self, m: &Mat) -> Option { let i = m.gpu?; Some(if i == STAGED { 0 } else { gpu_of(i) }) @@ -788,8 +869,15 @@ impl<'a> Mat<'a> { /// `expert` that never overwrites a VRAM slot when `evict` is false: an expert that is not resident and has no /// free room comes back host-only, for the CPU. pub fn expert_opt(&self, e: usize, n_expert: usize, evict: bool) -> Mat<'a> { + self.expert_opt_in(e, n_expert, evict, self, 0) + } + + /// `expert_opt` where the GPU is chosen per `key` (a layer's gate_up tensor) instead of per tensor, so the gate_up + /// and down experts of a layer share a GPU: `extra` is the bytes of the other tensors of the group. + pub fn expert_opt_in(&self, e: usize, n_expert: usize, evict: bool, key: &Mat<'a>, extra: usize) -> Mat<'a> { let mut m = self.expert_host(e, n_expert); - m.gpu = dev::get().and_then(|d| d.lock().unwrap().expert(m.data, m.ty, m.rows, m.cols, m.scale, evict)); + let group = (key.data.as_ptr() as usize, key.data.len() + extra); + m.gpu = dev::get().and_then(|d| d.lock().unwrap().expert_grouped(group, m.data, m.ty, m.rows, m.cols, m.scale, evict)); m } diff --git a/src/inkling2/chat.rs b/src/inkling2/chat.rs index 3d78ddd..1b34693 100644 --- a/src/inkling2/chat.rs +++ b/src/inkling2/chat.rs @@ -74,6 +74,8 @@ const DONE: &str = "<|content_model_end_sampling|>"; pub fn gpu_defaults() { crate::deepseek::chat::gpu_defaults(); if std::env::var_os("STRATA_DS_GPU_FRACTION").is_none() { unsafe { std::env::set_var("STRATA_DS_GPU_FRACTION", "0.6,0.9") } } + // Local patch: with several GPUs the plain weights stay on GPU 0, where the device decode state lives. + if std::env::var_os("STRATA_DS_PLAIN_FIRST").is_none() { unsafe { std::env::set_var("STRATA_DS_PLAIN_FIRST", "1") } } } /// The template's `tojson(sort_keys=true, separators=(",", ":"))`. diff --git a/src/inkling2/forward.rs b/src/inkling2/forward.rs index 41b55e0..648daca 100644 --- a/src/inkling2/forward.rs +++ b/src/inkling2/forward.rs @@ -807,7 +807,7 @@ impl<'a> Inkling2Model<'a> { // share; 0 (also `--fixed-experts`) runs every expert on the GPU: the same numerics on every run. self.lap(4, t); let (share, fixed) = self.share(&self.cpu_share); - let gus: Vec = sel.iter().map(|s| l.gate_up.expert_opt(s.0, ne, share == 0.0)).collect(); + let gus: Vec = sel.iter().map(|s| l.gate_up.expert_opt_in(s.0, ne, share == 0.0, &l.gate_up, l.down.data.len())).collect(); let n_miss = gus.iter().filter(|m| m.gpu.is_none()).count(); let mut left = (share * n_miss as f32).round() as usize; let (mut on_gpu, mut on_cpu) = (vec![], vec![]); @@ -824,7 +824,7 @@ impl<'a> Inkling2Model<'a> { /// The GPU's experts of `plan` with both matrices in VRAM: in a cache slot, or copied up for this use. fn resident(l: &Layer<'a>, ne: usize, on_gpu: &[(Mat<'a>, usize, f32)]) -> Vec<(Mat<'a>, Mat<'a>, f32, f32)> { - let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt(e, ne, true); if x.gpu.is_some() { x } else { x.staged() } }; + let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt_in(e, ne, true, &l.gate_up, l.down.data.len()); if x.gpu.is_some() { x } else { x.staged() } }; on_gpu.iter().map(|&(gu, e, w)| (if gu.gpu.is_some() { gu } else { on(&l.gate_up, e) }, on(&l.down, e), w, l.gu_scale[e])).collect() } @@ -875,8 +875,8 @@ impl<'a> Inkling2Model<'a> { // split of the prefill chunks alone. let cell = if xs.len() <= device::VERIFY_MAX { &self.cpu_share } else { &self.chunk_share }; let (share, fixed) = self.share(cell); - let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt(e, ne, share == 0.0); if x.gpu.is_some() { x } else { x.staged() } }; - let gus: Vec<(usize, Mat)> = by_e.keys().map(|&e| (e, l.gate_up.expert_opt(e, ne, share == 0.0))).collect(); + let on = |m: &Mat<'a>, e: usize| { let x = m.expert_opt_in(e, ne, share == 0.0, &l.gate_up, l.down.data.len()); if x.gpu.is_some() { x } else { x.staged() } }; + let gus: Vec<(usize, Mat)> = by_e.keys().map(|&e| (e, l.gate_up.expert_opt_in(e, ne, share == 0.0, &l.gate_up, l.down.data.len()))).collect(); let n_miss = gus.iter().filter(|g| g.1.gpu.is_none()).count(); let mut left = (share * n_miss as f32).round() as usize; let (mut on_gpu, mut on_cpu) = (vec![], vec![]); @@ -1303,7 +1303,7 @@ impl<'a> Inkling2Model<'a> { let target_end = self.toks.len() + seq.len() - 1; match d.prepare(self, target_end) { Ok(()) => { - let chunk = env_chunk.unwrap_or(256).clamp(1, 256); + let chunk = env_chunk.unwrap_or(device::pf_tokens()).clamp(1, device::pf_tokens()); let mut logits = vec![]; let mut done = 0usize; let mut failed = None; diff --git a/src/inkling2/forward/device.rs b/src/inkling2/forward/device.rs index c0127e7..9b07e3d 100644 --- a/src/inkling2/forward/device.rs +++ b/src/inkling2/forward/device.rs @@ -14,6 +14,8 @@ use std::sync::Arc; /// Contiguous all-expert weights + F32 router uploaded once for a layer, enabling zero-round-trip GPU MoE. struct FullExps { + /// The GPU of the slabs: 0, or 1 when GPU 0 had no room (the FFN of that layer runs there, see `Remote`). + part: usize, _gi: Arc, gate_inp: GpuTensor, bias: Arc, @@ -38,6 +40,19 @@ struct DLoop { msg_query: Buf, down: Buf, gain: Buf, forget: Buf } /// sliding-window slot is a ring of `n_swa` rows (position p in row p % n_swa); the others grow. struct DSlot { k: Buf, v: Buf, hist: Buf, cap: usize } +/// What GPU 1 needs to run the FFN of the layers whose experts live there: a decode scratch (`s`) and, from the first +/// prompt chunk on, a prefill scratch. The activations come over the host once per layer run (about 10 KB per token). +struct Remote { part: usize, scr: Buf, s: Scratch, pf: Option } + +/// Tokens of one prompt chunk on the device: `STRATA_DS_PF_TOKENS` (default 256 on one card, 512 on two or more; +/// at most 2048). +pub(super) fn pf_tokens() -> usize { + let multi = std::env::var("STRATA_DS_DEVICES") + .map_or(false, |v| v.split(',').filter(|d| !d.trim().is_empty()).count() > 1); + let default = if multi { 512 } else { 256 }; + std::env::var("STRATA_DS_PF_TOKENS").ok().and_then(|v| v.parse::().ok()).unwrap_or(default).clamp(1, 2048) +} + /// Device addresses of the regions of the decode scratch buffer (`sc` lives in `Device::sc_buf` so `--ctx` scales dynamically). #[derive(Clone, Copy)] struct Scratch { @@ -116,23 +131,38 @@ struct PrefillScratch { } impl PrefillScratch { - fn alloc(be: &dyn Backend, c: &Inkling2Config, rank: usize, vocab_rows: usize, max_nt: usize) -> Result { + /// Bytes `alloc` takes (plus a little for the allocator). + fn bytes(be: &dyn Backend, c: &Inkling2Config, rank: usize, vocab_rows: usize, max_nt: usize, light: bool) -> usize { + let (kw, n_slot) = (c.n_head_kv * c.head_dim, c.n_slot()); + let rb = 2 * be.kv_words(kw); + let lay = PrefillLayout::at(0, c, rank, max_nt).end as usize; + let swa = (n_slot * VERIFY_MAX * rb).max(1024); + let extra = if light { 0 } else { + 2 * max_nt * rb + 4 * VERIFY_MAX * vocab_rows + 16 * max_nt * c.n_embd + 4 * n_slot * hists(c).1 + + 4 * n_slot * VERIFY_MAX * (2 * kw + 2 * c.n_embd) + 2 * swa + }; + lay + 4 * max_nt * c.n_embd + (40 * max_nt * c.n_used).max(1024) + extra + (16 << 20) + } + + /// `light`: only what the routed experts of a layer need (GPU 1 runs nothing else): the attention logs are tiny. + fn alloc(be: &dyn Backend, c: &Inkling2Config, rank: usize, vocab_rows: usize, max_nt: usize, light: bool) -> Result { let lay0 = PrefillLayout::at(0, c, rank, max_nt); let buf = be.alloc(lay0.end as usize)?; let p = PrefillLayout::at(buf.addr(), c, rank, max_nt); let acc_buf = be.alloc(4 * max_nt * c.n_embd)?; let kw = c.n_head_kv * c.head_dim; let rb = 2 * be.kv_words(kw); - let kv_bytes = max_nt * rb; + let kv_bytes = if light { 256 } else { max_nt * rb }; let (kc_tmp, vc_tmp) = (be.alloc(kv_bytes)?, be.alloc(kv_bytes)?); let max_np = max_nt * c.n_used; let meta = be.alloc((40 * max_np).max(1024))?; - let logits_buf = be.alloc(4 * VERIFY_MAX * vocab_rows)?; - let dspark_buf = be.alloc(4 * 4 * max_nt * c.n_embd)?; + let lt = |b: usize| if light { 256 } else { b }; + let logits_buf = be.alloc(lt(4 * VERIFY_MAX * vocab_rows))?; + let dspark_buf = be.alloc(lt(4 * 4 * max_nt * c.n_embd))?; let n_slot = c.n_slot(); - let hist_bak = be.alloc(4 * n_slot * hists(c).1)?; - let conv_log = be.alloc(4 * n_slot * VERIFY_MAX * (2 * kw + 2 * c.n_embd))?; - let swa_log_bytes = (n_slot * VERIFY_MAX * rb).max(1024); + let hist_bak = be.alloc(lt(4 * n_slot * hists(c).1))?; + let conv_log = be.alloc(lt(4 * n_slot * VERIFY_MAX * (2 * kw + 2 * c.n_embd)))?; + let swa_log_bytes = lt((n_slot * VERIFY_MAX * rb).max(1024)); let (swa_kc_log, swa_vc_log) = (be.alloc(swa_log_bytes)?, be.alloc(swa_log_bytes)?); Ok(Self { max_nt, buf, acc_buf, kc_tmp, vc_tmp, meta, logits_buf, dspark_buf, @@ -153,6 +183,12 @@ pub(super) struct Device { s: Scratch, rank: usize, all_full: bool, + /// GPU 1's share of the FFN layers (None when every layer's experts are on GPU 0). + rem: Option, + /// With `rem`: the loop layers are all on GPU 0, so the loop runs as one graph, and the layers around it launch one by one. + seg_graph: bool, + /// Blocks in the depth mix after the loop (what `layer_attn` counted when the loop graph was recorded). + loop_nb: usize, /// Key of the recorded `step_fast` graph, by `argmax` (0: none). graph_keys: [u64; 2], /// Positions whose rows both sides hold, and whether the device has run tokens after them. @@ -252,8 +288,9 @@ impl Device { let full = (2 * (pos + 1)).clamp(4096.min(m.max_ctx), m.max_ctx); { let mut d = dev::get()?.lock().unwrap(); - if d.parts.len() != 1 { return None; } - let dense = |x: &Mat| !x.host_only(); + // 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; } @@ -293,38 +330,65 @@ impl Device { let s = Scratch::at(scr.addr(), c, rank, m.output.rows); // Preload full-layer expert slabs so selected layers skip CPU routing, uploads, and host syncs. - // Core loop layers run 3x per token (75% of FFN compute), so prioritize them first. + // Core loop layers run 3x per token (75% of FFN compute), so they go first, and to GPU 0, where the attention is. + // Local patch: with two GPUs the layers that run once (outside the loop) prefer GPU 1, and a layer that does not + // fit on its GPU goes to the other one: every layer's experts end up in VRAM, and the FFN of a layer on GPU 1 + // runs there (`Remote`). GPU 0 keeps free what the state still needs: prompt chunk scratch and KV growth. let cpu_share = std::env::var("STRATA_DS_CPU_SHARE").ok().and_then(|v| v.parse::().ok()).unwrap_or(0.0); - let (mut n_full, mut slab_bytes) = (0usize, 0usize); + let (mut n_full, mut slab_bytes, mut per_part) = (0usize, 0usize, [0usize; 2]); + let mut rem: Option = None; if cpu_share <= 0.0 && c.n_expert <= 512 && c.n_used <= 32 { let (b_res, f_res) = (64 << 20, 384 << 20); - let order = (c.loop_start..c.loop_end).chain(0..c.loop_start).chain(c.loop_end..c.n_layer); + let (n_parts, pf_cap, vocab) = (dev::get().unwrap().lock().unwrap().parts.len().min(2), pf_tokens(), m.output.rows); + let (res0, res1) = { + let d = dev::get().unwrap().lock().unwrap(); + let be0 = &*d.parts[0].be; + // The KV rows GPU 0 must still be able to take: all of `--ctx` unless STRATA_DS_KV_TOKENS says less (a + // lower value frees room for more expert slabs on GPU 0, at the price of a host fallback past it). + let kv_rows = std::env::var("STRATA_DS_KV_TOKENS").ok().and_then(|v| v.parse::().ok()).unwrap_or(m.max_ctx) + .min(m.max_ctx).max(full); + let n_att = (0..c.n_slot()).filter(|&il| !c.swa[layer_of(c, il)]).count(); + let kv = 4 * n_att * kv_rows * be0.kv_words(kw) + sc_bytes(c, kv_rows); + let pf0 = PrefillScratch::bytes(be0, c, rank, vocab, pf_cap, false); + let pf1 = if n_parts > 1 { PrefillScratch::bytes(&*d.parts[1].be, c, rank, vocab, pf_cap, true) } else { 0 }; + // One card keeps the old 384 MiB reserve; the KV/prefill reserve is for the two-card plan. + let res0 = if n_parts > 1 { f_res + pf0 + kv } else { f_res }; + (res0, (192 << 20) + pf1 + Scratch::at(0, c, rank, 0).end as usize) + }; let key = |s: &[u8]| Some((s.as_ptr() as usize, s.len())); + let on_loop = |ip: usize| (c.loop_start..c.loop_end).contains(&ip); + let order = (c.loop_start..c.loop_end).chain(0..c.loop_start).chain(c.loop_end..c.n_layer); for ip in order { let ml = &m.layers[ip]; let gi_bytes: Vec = ml.gate_inp.iter().flat_map(|x| x.to_le_bytes()).collect(); let bias_bytes: Vec = ml.bias.iter().flat_map(|x| x.to_le_bytes()).collect(); let gs_bytes: Vec = ml.gu_scale.iter().flat_map(|x| x.to_le_bytes()).collect(); let ds_bytes: Vec = ml.down_scale.iter().flat_map(|x| x.to_le_bytes()).collect(); - let Some((gu, dn, gi_slab, bias, gu_scale, dn_scale)) = (|| -> Option<_> { + let place = |part: usize| -> Option<(usize, Arc, Arc, Arc, Arc, Option>, Option>)> { let mut d = dev::get().unwrap().lock().unwrap(); - let gu = d.alloc_slab(ml.gate_up.data, key(ml.gate_up.data), b_res, f_res)?; - let dn = d.alloc_slab(ml.down.data, key(ml.down.data), b_res, f_res)?; - let gi = d.alloc_slab(&gi_bytes, None, b_res, f_res)?; - let bi = d.alloc_slab(&bias_bytes, None, b_res, f_res)?; - let gs = if gs_bytes.is_empty() { None } else { Some(d.alloc_slab(&gs_bytes, None, b_res, f_res)?) }; - let ds = if ds_bytes.is_empty() { None } else { Some(d.alloc_slab(&ds_bytes, None, b_res, f_res)?) }; - Some((gu, dn, gi, bi, gs, ds)) - })() else { + let fr = if part == 0 { res0 } else { res1 }; + let gu = d.alloc_slab_on(part, ml.gate_up.data, key(ml.gate_up.data), b_res, fr)?; + let dn = d.alloc_slab_on(part, ml.down.data, key(ml.down.data), b_res, fr)?; + let gi = d.alloc_slab_on(part, &gi_bytes, None, b_res, fr)?; + let bi = d.alloc_slab_on(part, &bias_bytes, None, b_res, fr)?; + let gs = if gs_bytes.is_empty() { None } else { Some(d.alloc_slab_on(part, &gs_bytes, None, b_res, fr)?) }; + let ds = if ds_bytes.is_empty() { None } else { Some(d.alloc_slab_on(part, &ds_bytes, None, b_res, fr)?) }; + Some((part, gu, dn, gi, bi, gs, ds)) + }; + let prefs: &[usize] = match (n_parts > 1, on_loop(ip)) { (false, _) => &[0], (true, true) => &[0, 1], (true, false) => &[1, 0] }; + let Some((part, gu, dn, gi_slab, bias, gu_scale, dn_scale)) = prefs.iter().find_map(|&p| place(p)) else { break; }; - slab_bytes += gu.len() + dn.len() + gi_slab.len() + bias.len() + let bytes = gu.len() + dn.len() + gi_slab.len() + bias.len() + gu_scale.as_ref().map_or(0, |b| b.len()) + dn_scale.as_ref().map_or(0, |b| b.len()); + slab_bytes += bytes; + per_part[part] += bytes; n_full += 1; let (gu_rows, gu_cols) = (ml.gate_up.rows / c.n_expert, ml.gate_up.cols); let (dn_rows, dn_cols) = (ml.down.rows / c.n_expert, ml.down.cols); layers[ip].full_exps = Some(FullExps { + part, gate_inp: GpuTensor::new(GgmlType::F32, c.n_expert, c.n_embd, Buf::new(gi_slab.addr(), gi_slab.len(), ())), _gi: gi_slab, bias, @@ -336,12 +400,26 @@ impl Device { dn_scale, }); } + if layers.iter().any(|l| l.full_exps.as_ref().is_some_and(|fe| fe.part == 1)) { + let d = dev::get().unwrap().lock().unwrap(); + let be1 = &*d.parts[1].be; + let r_scr = be1.alloc(Scratch::at(0, c, rank, 0).end as usize)?; + let r_s = Scratch::at(r_scr.addr(), c, rank, 0); + let pf = PrefillScratch::alloc(be1, c, rank, vocab, pf_cap, true).ok(); + rem = Some(Remote { part: 1, scr: r_scr, s: r_s, pf }); + } } if std::env::var_os("STRATA_DS_PROF").is_some() { - eprintln!("inkling2: preloaded {n_full}/{} expert layers ({:.2} GB) as contiguous slabs", c.n_layer, slab_bytes as f64 / 1e9); + eprintln!("inkling2: preloaded {n_full}/{} expert layers ({:.2} GB: {:.2} on GPU 0, {:.2} on GPU 1) as contiguous slabs", + c.n_layer, slab_bytes as f64 / 1e9, per_part[0] as f64 / 1e9, per_part[1] as f64 / 1e9); } - let all_full = layers.iter().all(|l| l.full_exps.is_some()); - Ok(Device { layers, loops, slots, out_query, out_norm, scr, sc_buf, pf: None, s, rank, all_full, graph_keys: [0; 2], synced: 0, ahead: false }) + let all_full = rem.is_none() && layers.iter().all(|l| l.full_exps.is_some()); + 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()) + && (c.loop_start..c.loop_end).all(|ip| layers[ip].full_exps.as_ref().is_some_and(|fe| fe.part == 0)) + && (c.loop_count * core) % 2 == 0; + Ok(Device { layers, loops, slots, out_query, out_norm, scr, sc_buf, pf: None, s, rank, all_full, rem, seg_graph, loop_nb: 0, graph_keys: [0; 2], synced: 0, ahead: false }) })(); made.inspect_err(|e| eprintln!("inkling2: no room in VRAM for the decode state ({e:#}); the tokens run as prompt chunks do")).ok() } @@ -524,45 +602,97 @@ impl Device { // 17 MiB of device memory, and the backend stops recording at 32 of them). let last = std::mem::replace(&mut self.graph_keys[argmax as usize], key); if last != 0 && last != key { be.graph_drop(last)?; } - be.graph(key, &mut || { + if !self.seg_graph { + be.graph(key, &mut || { + let mut nb = 0usize; + for il in 0..c.loop_start { + self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; + self.layer_ffn_gpu(be, m, il, il)?; + } + 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 { + let n_bank = nb.saturating_sub(n_pre + 1); + if pass > 0 { + let s = self.s; + if n_bank > 0 { + be.dtod(&self.scr, (s.blocks - o) as usize + 4 * (n_pre + 1) * n, &self.scr, (s.bank - o) as usize, 4 * n_bank * n)?; + } + be.dtod(&self.scr, (s.cur - o) as usize, &self.scr, (s.outb - o) as usize, 4 * n)?; + be.dtod(&self.scr, (s.prelude - o) as usize, &self.scr, (s.cur - o) as usize, 4 * n)?; + nb = n_pre; + } + 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 { + let s = self.s; + 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)?; + self.layer_ffn_gpu(be, m, il, ip)?; + } + } + for il in c.loop_end..c.n_layer { + self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; + self.layer_ffn_gpu(be, m, il, il)?; + } + self.finish_logits(be, &d, m, nb)?; + if argmax { + be.argmax_rows(self.s.logits, c.n_vocab, 1, self.s.amax)?; + } + Ok(()) + })?; + } else { + // Local patch: layers 0..loop_start and loop_end.. launch one by one (their FFN may be on GPU 1, which needs + // the host between the attention and the experts); the loop between them is one graph. + let prof = std::env::var_os("STRATA_DS_PROF").is_some(); + 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)?; - self.layer_ffn_gpu(be, m, il, il)?; + if !self.layer_ffn_remote(&d, m, il, il)? { self.layer_ffn_gpu(be, m, il, il)?; } } - be.dtod(&self.scr, (self.s.cur - o) as usize, &self.scr, (self.s.prelude - o) as usize, 4 * n)?; + if prof { be.sync()?; m.lap(1, tt); tt = std::time::Instant::now(); } let n_pre = nb; - for pass in 0..c.loop_count { - let n_bank = nb.saturating_sub(n_pre + 1); - if pass > 0 { - let s = self.s; - if n_bank > 0 { - be.dtod(&self.scr, (s.blocks - o) as usize + 4 * (n_pre + 1) * n, &self.scr, (s.bank - o) as usize, 4 * n_bank * n)?; - } - be.dtod(&self.scr, (s.cur - o) as usize, &self.scr, (s.outb - o) as usize, 4 * n)?; - be.dtod(&self.scr, (s.prelude - o) as usize, &self.scr, (s.cur - o) as usize, 4 * n)?; - nb = n_pre; - } - 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 }; + be.graph(key, &mut || { + let mut nb = n_pre; + be.dtod(&self.scr, (self.s.cur - o) as usize, &self.scr, (self.s.prelude - o) as usize, 4 * n)?; + for pass in 0..c.loop_count { + let n_bank = nb.saturating_sub(n_pre + 1); if pass > 0 { let s = self.s; - be.ink_mix(s.bank, n_bank, s.outb, self.loops[ip - c.loop_start].msg_query.addr(), 4, s.msg, n)?; + if n_bank > 0 { + be.dtod(&self.scr, (s.blocks - o) as usize + 4 * (n_pre + 1) * n, &self.scr, (s.bank - o) as usize, 4 * n_bank * n)?; + } + be.dtod(&self.scr, (s.cur - o) as usize, &self.scr, (s.outb - o) as usize, 4 * n)?; + be.dtod(&self.scr, (s.prelude - o) as usize, &self.scr, (s.cur - o) as usize, 4 * n)?; + nb = n_pre; + } + 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 { + let s = self.s; + 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)?; + self.layer_ffn_gpu(be, m, il, ip)?; } - self.layer_attn(be, &d, m, il, ip, pass > 0, pos, true, &mut nb)?; - self.layer_ffn_gpu(be, m, il, ip)?; } - } + self.loop_nb = nb; + Ok(()) + })?; + if prof { be.sync()?; m.lap(2, tt); tt = std::time::Instant::now(); } + let mut nb = self.loop_nb; for il in c.loop_end..c.n_layer { self.layer_attn(be, &d, m, il, il, false, pos, true, &mut nb)?; - self.layer_ffn_gpu(be, m, il, il)?; + if !self.layer_ffn_remote(&d, m, il, il)? { self.layer_ffn_gpu(be, m, il, il)?; } } + if prof { be.sync()?; m.lap(3, tt); } self.finish_logits(be, &d, m, nb)?; if argmax { be.argmax_rows(self.s.logits, c.n_vocab, 1, self.s.amax)?; } - Ok(()) - })?; + } if argmax { let id = be.get::(&self.scr, ((self.s.amax - o) / 4) as usize, 1)?[0] as u32; Ok((Vec::new(), id)) @@ -632,7 +762,7 @@ impl Device { let pos = m.toks.len(); assert!(pos < m.max_ctx, "context is limited to {} tokens", m.max_ctx); assert!((tok as usize) < m.tok_embd.rows, "token {tok} is outside the vocabulary"); - if self.all_full { + 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); @@ -656,7 +786,7 @@ impl Device { let pos = m.toks.len(); assert!(pos < m.max_ctx, "context is limited to {} tokens", m.max_ctx); assert!((tok as usize) < m.tok_embd.rows, "token {tok} is outside the vocabulary"); - if self.all_full { + 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); @@ -682,12 +812,12 @@ impl Device { be.sync()?; self.pf = None; } - let target = need_nt.max(256).min(256); + let target = need_nt.max(pf_tokens()); let mut tries = vec![target]; if need_nt < target { tries.push(need_nt.max(128)); tries.push(need_nt.max(64)); tries.push(need_nt); } let mut last_err = None; for cap in tries { - match PrefillScratch::alloc(be, c, self.rank, vocab_rows, cap) { + match PrefillScratch::alloc(be, c, self.rank, vocab_rows, cap, false) { Ok(pf) => { self.pf = Some(pf); return Ok(()); } Err(e) => last_err = Some(e), } @@ -695,6 +825,17 @@ impl Device { Err(last_err.unwrap()) } + /// GPU 1's prefill scratch for `need_nt` rows, when some layer's experts live there. + fn ensure_pf_remote(&mut self, d: &dev::Dev, c: &Inkling2Config, vocab_rows: usize, need_nt: usize) -> Result<()> { + let rank = self.rank; + let Some(r) = &mut self.rem else { return Ok(()) }; + if r.pf.as_ref().is_some_and(|pf| pf.max_nt >= need_nt) { return Ok(()); } + let be1 = &*d.parts[r.part].be; + if r.pf.is_some() { be1.sync()?; r.pf = None; } + r.pf = Some(PrefillScratch::alloc(be1, c, rank, vocab_rows, need_nt.max(pf_tokens()), true)?); + Ok(()) + } + /// Project a single corrected hidden vector `h_corr` (`[n_embd]`) through the target's LM head on GPU /// and return the argmax token ID (`0..c.n_vocab`). No softcap: `softcap * tanh(x / softcap)` keeps the /// order of the logits (two that differ by a few ulp may become equal), and the token is a draft that @@ -785,6 +926,7 @@ impl Device { let d = dev::get().unwrap().lock().unwrap(); let be = &*d.parts[0].be; self.ensure_pf(be, c, m.output.rows, nt)?; + self.ensure_pf_remote(&d, c, m.output.rows, nt)?; if !self.ahead { self.to_device(m, be, pos0)?; } let pf = self.pf.as_ref().unwrap(); be.put(&cur_host, &pf.buf, 0)?; @@ -898,6 +1040,7 @@ impl Device { let d = dev::get().unwrap().lock().unwrap(); let be = &*d.parts[0].be; self.ensure_pf(be, c, m.output.rows, nt)?; + self.ensure_pf_remote(&d, c, m.output.rows, nt)?; if !self.ahead { self.to_device(m, be, pos0)?; } let pf = self.pf.as_ref().unwrap(); for (il, ds) in self.slots.iter().enumerate() { @@ -1186,7 +1329,7 @@ impl Device { h = p.h2; } if let Some(fe) = &l.full_exps { - let use_gemm = !small && fe.gu_cols % 64 == 0 && fe.dn_cols % 64 == 0; + let use_gemm = (!small || fe.part != 0) && fe.gu_cols % 64 == 0 && fe.dn_cols % 64 == 0; if use_gemm || fe.gu_ty.float_x() { be.rms_norm(h, n, l.ffn_norm.addr(), p.hn, n, n, nt, c.eps)?; } else { @@ -1194,86 +1337,24 @@ impl Device { } m.lap(0, t_prep); let t_gpu = std::time::Instant::now(); - Self::proj_n(be, &fe.gate_inp, small, nt, p.hn, 0, p.rlogits, 0)?; - let gu_sc = fe.gu_scale.as_ref().map_or(0, |b| b.addr()); - let dn_sc = fe.dn_scale.as_ref().map_or(0, |b| b.addr()); - let gsc_out = if gu_sc != 0 { p.gsc } else { 0 }; - be.ink_route(p.rlogits, fe.bias.addr(), p.ids, p.wts, gu_sc, dn_sc, gsc_out, c.n_expert, k, c.exp_scale, nt)?; - if !use_gemm { - // Process up to 16 tokens per moe_gemv batch so zero host sync is needed (exact decode speed for nt <= 16). - for tok0 in (0..nt).step_by(16) { - let bt = (nt - tok0).min(16); - let np = bt * k; - let xh_tok_floats = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; - let ids_a = p.ids + (4 * tok0 * k) as u64; - let wts_a = p.wts + f(tok0 * k); - let gsc_a = if gu_sc != 0 { p.gsc + f(tok0 * k) } else { 0 }; - let hn_a = p.hn + f(tok0 * n); - let xh_a = p.xh + f(tok0 * xh_tok_floats); - let y_a = p.y; - let d_a = p.d; - let acc_a = pf.acc_buf.addr() + f(tok0 * n); - be.moe_gemv(fe.gu_ty, fe.gu_rows, fe.gu_cols, fe.gu.addr(), fe.gu_stride, ids_a, np, hn_a, n, k, y_a, None, xh_a)?; - if fe.dn_ty.float_x() || nf % 32 != 0 { - be.situ(y_a, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; - be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, ids_a, np, y_a, 2 * nf, 1, d_a, None, 0)?; - } else { - be.situ_q(y_a, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta, p.xq)?; - be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, ids_a, np, y_a, 2 * nf, 1, d_a, None, p.xq)?; - } - be.ink_ffn_sum_n(acc_a, d_a, wts_a, k, n, bt, 0)?; - } + if fe.part == 0 { + Self::pf_ffn_core(be, m, ip, fe, pf, nt, small, use_gemm)?; } else { - use crate::backend::GEMM_BM; - let ids: Vec = be.get(&pf.buf, ((p.ids - buf_o) / 4) as usize, nt * k)?; - let mut by_e: Vec> = vec![vec![]; c.n_expert]; - for (t, row) in ids.chunks_exact(k).enumerate() { - for (j, &e) in row.iter().enumerate() { by_e[e as usize].push((t, j)); } + // Experts on GPU 1: the normed rows cross over, the experts run there, the sum comes back. + let r = self.rem.as_ref().ok_or_else(|| anyhow::anyhow!("experts on GPU 1 without a scratch there"))?; + let pf1 = r.pf.as_ref().ok_or_else(|| anyhow::anyhow!("no prefill scratch on GPU 1"))?; + let be1 = &*d.parts[r.part].be; + let (o0, o1) = (buf_o, pf1.buf.addr()); + let hn: Vec = be.get(&pf.buf, ((p.hn - o0) / 4) as usize, nt * n)?; + be1.put(&hn, &pf1.buf, ((pf1.p.hn - o1) / 4) as usize)?; + if !use_gemm && !fe.gu_ty.float_x() { + let xw = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; + let xh: Vec = be.get(&pf.buf, ((p.xh - o0) / 4) as usize, nt * xw)?; + be1.put(&xh, &pf1.buf, ((pf1.p.xh - o1) / 4) as usize)?; } - let np = nt * k; - let mut tiles_gu: Vec = Vec::with_capacity(2 * (c.n_expert + np / GEMM_BM)); - let mut tiles_dn: Vec = Vec::with_capacity(2 * (c.n_expert + np / GEMM_BM)); - let mut xrow: Vec = Vec::with_capacity(np); - let mut inv: Vec = vec![0i32; nt * k]; - let mut gsc_rows: Vec = if ml.gu_scale.is_empty() { Vec::new() } else { Vec::with_capacity(np) }; - let mut m0 = 0usize; - for e in 0..c.n_expert { - if by_e[e].is_empty() { continue; } - let wg = fe.gu.addr() + (e * fe.gu_stride) as u64; - let wd = fe.dn.addr() + (e * fe.dn_stride) as u64; - for at in (0..by_e[e].len()).step_by(GEMM_BM) { - let cnt = GEMM_BM.min(by_e[e].len() - at) as u64; - tiles_gu.extend([wg, (m0 + at) as u64 | (cnt << 32)]); - tiles_dn.extend([wd, (m0 + at) as u64 | (cnt << 32)]); - } - for &(t, j) in &by_e[e] { - inv[t * k + j] = xrow.len() as i32; - xrow.push(t as i32); - if !ml.gu_scale.is_empty() { gsc_rows.push(ml.gu_scale[e]); } - } - m0 += by_e[e].len(); - } - let n_tiles = tiles_gu.len() / 2; - let dn_off = 8 * tiles_gu.len(); - let xr_off = dn_off + 8 * tiles_dn.len(); - let inv_off = xr_off + 4 * np; - ensure!(inv_off + 4 * nt * k <= pf.meta.len(), "prefill meta overflow"); - be.put(&tiles_gu, &pf.meta, 0)?; - be.put(&tiles_dn, &pf.meta, dn_off / 8)?; - be.put(&xrow, &pf.meta, xr_off / 4)?; - be.put(&inv, &pf.meta, inv_off / 4)?; - let gsc_a = if !gsc_rows.is_empty() { - be.put(&gsc_rows, &pf.buf, ((p.gsc - buf_o) / 4) as usize)?; - p.gsc - } else { - 0 - }; - let ma = pf.meta.addr(); - be.gemm(fe.gu_ty, fe.gu_rows, fe.gu_cols, ma, n_tiles, p.hn, n, nt, ma + xr_off as u64, p.y, 2 * nf, 0)?; - be.situ(p.y, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; - be.gemm(fe.dn_ty, fe.dn_rows, fe.dn_cols, ma + dn_off as u64, n_tiles, p.y, 2 * nf, np, 0, p.d, n, 0)?; - be.memset(&pf.acc_buf)?; - be.moe_combine_seq(pf.acc_buf.addr(), p.d, p.wts, ma + inv_off as u64, k, 0, 0, n, nt)?; + Self::pf_ffn_core(be1, m, ip, fe, pf1, nt, small, use_gemm)?; + let acc: Vec = be1.get(&pf1.acc_buf, 0, nt * n)?; + be.put(&acc, &pf.acc_buf, 0)?; } if verify_mode { be.dtod(&pf.acc_buf, 0, &pf.conv_log, log_base + 4 * VERIFY_MAX * (2 * kw + n), 4 * nt * n)?; @@ -1309,6 +1390,97 @@ impl Device { Ok(()) } + /// The routed experts of a prompt chunk on the GPU `be` runs on: from the normed rows in `pf.p.hn` (and, below the + /// GEMM size, their quantized copy in `pf.p.xh`) to the weighted sum in `pf.acc_buf`. + #[allow(clippy::too_many_arguments)] + fn pf_ffn_core(be: &dyn Backend, m: &Inkling2Model, ip: usize, fe: &FullExps, pf: &PrefillScratch, nt: usize, small: bool, use_gemm: bool) -> Result<()> { + let (c, ml) = (&m.cfg, &m.layers[ip]); + let (n, nf, k) = (c.n_embd, c.n_ff_exp, c.n_used); + let (p, buf_o) = (pf.p, pf.buf.addr()); + Self::proj_n(be, &fe.gate_inp, small, nt, p.hn, 0, p.rlogits, 0)?; + let gu_sc = fe.gu_scale.as_ref().map_or(0, |b| b.addr()); + let dn_sc = fe.dn_scale.as_ref().map_or(0, |b| b.addr()); + let gsc_out = if gu_sc != 0 { p.gsc } else { 0 }; + be.ink_route(p.rlogits, fe.bias.addr(), p.ids, p.wts, gu_sc, dn_sc, gsc_out, c.n_expert, k, c.exp_scale, nt)?; + if !use_gemm { + // Process up to 16 tokens per moe_gemv batch so zero host sync is needed (exact decode speed for nt <= 16). + for tok0 in (0..nt).step_by(16) { + let bt = (nt - tok0).min(16); + let np = bt * k; + let xh_tok_floats = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; + let ids_a = p.ids + (4 * tok0 * k) as u64; + let wts_a = p.wts + f(tok0 * k); + let gsc_a = if gu_sc != 0 { p.gsc + f(tok0 * k) } else { 0 }; + let hn_a = p.hn + f(tok0 * n); + let xh_a = p.xh + f(tok0 * xh_tok_floats); + let y_a = p.y; + let d_a = p.d; + let acc_a = pf.acc_buf.addr() + f(tok0 * n); + be.moe_gemv(fe.gu_ty, fe.gu_rows, fe.gu_cols, fe.gu.addr(), fe.gu_stride, ids_a, np, hn_a, n, k, y_a, None, xh_a)?; + if fe.dn_ty.float_x() || nf % 32 != 0 { + be.situ(y_a, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; + be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, ids_a, np, y_a, 2 * nf, 1, d_a, None, 0)?; + } else { + be.situ_q(y_a, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta, p.xq)?; + be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, ids_a, np, y_a, 2 * nf, 1, d_a, None, p.xq)?; + } + be.ink_ffn_sum_n(acc_a, d_a, wts_a, k, n, bt, 0)?; + } + } else { + use crate::backend::GEMM_BM; + let ids: Vec = be.get(&pf.buf, ((p.ids - buf_o) / 4) as usize, nt * k)?; + let mut by_e: Vec> = vec![vec![]; c.n_expert]; + for (t, row) in ids.chunks_exact(k).enumerate() { + for (j, &e) in row.iter().enumerate() { by_e[e as usize].push((t, j)); } + } + let np = nt * k; + let mut tiles_gu: Vec = Vec::with_capacity(2 * (c.n_expert + np / GEMM_BM)); + let mut tiles_dn: Vec = Vec::with_capacity(2 * (c.n_expert + np / GEMM_BM)); + let mut xrow: Vec = Vec::with_capacity(np); + let mut inv: Vec = vec![0i32; nt * k]; + let mut gsc_rows: Vec = if ml.gu_scale.is_empty() { Vec::new() } else { Vec::with_capacity(np) }; + let mut m0 = 0usize; + for e in 0..c.n_expert { + if by_e[e].is_empty() { continue; } + let wg = fe.gu.addr() + (e * fe.gu_stride) as u64; + let wd = fe.dn.addr() + (e * fe.dn_stride) as u64; + for at in (0..by_e[e].len()).step_by(GEMM_BM) { + let cnt = GEMM_BM.min(by_e[e].len() - at) as u64; + tiles_gu.extend([wg, (m0 + at) as u64 | (cnt << 32)]); + tiles_dn.extend([wd, (m0 + at) as u64 | (cnt << 32)]); + } + for &(t, j) in &by_e[e] { + inv[t * k + j] = xrow.len() as i32; + xrow.push(t as i32); + if !ml.gu_scale.is_empty() { gsc_rows.push(ml.gu_scale[e]); } + } + m0 += by_e[e].len(); + } + let n_tiles = tiles_gu.len() / 2; + let dn_off = 8 * tiles_gu.len(); + let xr_off = dn_off + 8 * tiles_dn.len(); + let inv_off = xr_off + 4 * np; + ensure!(inv_off + 4 * nt * k <= pf.meta.len(), "prefill meta overflow"); + be.put(&tiles_gu, &pf.meta, 0)?; + be.put(&tiles_dn, &pf.meta, dn_off / 8)?; + be.put(&xrow, &pf.meta, xr_off / 4)?; + be.put(&inv, &pf.meta, inv_off / 4)?; + let gsc_a = if !gsc_rows.is_empty() { + be.put(&gsc_rows, &pf.buf, ((p.gsc - buf_o) / 4) as usize)?; + p.gsc + } else { + 0 + }; + let ma = pf.meta.addr(); + be.gemm(fe.gu_ty, fe.gu_rows, fe.gu_cols, ma, n_tiles, p.hn, n, nt, ma + xr_off as u64, p.y, 2 * nf, 0)?; + be.situ(p.y, nf, np, gsc_a, c.situ_beta, c.situ_linear_beta)?; + be.gemm(fe.dn_ty, fe.dn_rows, fe.dn_cols, ma + dn_off as u64, n_tiles, p.y, 2 * nf, np, 0, p.d, n, 0)?; + be.memset(&pf.acc_buf)?; + be.moe_combine_seq(pf.acc_buf.addr(), p.d, p.wts, ma + inv_off as u64, k, 0, 0, n, nt)?; + } + Ok(()) + } + fn layer_attn(&self, be: &dyn Backend, d: &dev::Dev, m: &Inkling2Model, il: usize, ip: usize, msgs: bool, pos: usize, graph: bool, nb: &mut usize) -> Result<()> { let (c, ml, l, ds, s, rank) = (&m.cfg, &m.layers[ip], &self.layers[ip], &self.slots[il], self.s, self.rank); let (n, hd, nh, nkv, nr, nc) = (c.n_embd, c.head_dim, c.n_head, c.n_head_kv, c.n_rel, c.n_conv); @@ -1402,11 +1574,10 @@ impl Device { be.rms_norm_q(h, n, l.ffn_norm.addr(), s.hn, n, n, 1, c.eps, s.xh, 0) } - fn layer_ffn_gpu(&mut self, be: &dyn Backend, m: &Inkling2Model, il: usize, ip: usize) -> Result { - let Some(fe) = &self.layers[ip].full_exps else { return Ok(false) }; - let (c, ds, s) = (&m.cfg, &self.slots[il], self.s); - let (n, hd, nc, nf, k) = (c.n_embd, c.head_dim, c.n_conv, c.n_ff_exp, c.n_used); - let hist3 = ds.hist.addr() + f(hists(c).0[3]); + /// The routed experts of one token on the GPU `be` runs on, from the normed input in `s.hn` (and its quantized + /// copy `s.xh`) to the weighted sum in `s.acc`. All of it stays on that device. + fn ffn_core(be: &dyn Backend, c: &Inkling2Config, s: Scratch, fe: &FullExps) -> Result<()> { + let (n, nf, k) = (c.n_embd, c.n_ff_exp, c.n_used); be.gemv(&fe.gate_inp, s.hn, s.rlogits)?; let gu_sc = fe.gu_scale.as_ref().map_or(0, |b| b.addr()); let dn_sc = fe.dn_scale.as_ref().map_or(0, |b| b.addr()); @@ -1420,10 +1591,44 @@ impl Device { be.situ_q(s.y, nf, k, gsc_a, c.situ_beta, c.situ_linear_beta, s.xq)?; be.moe_gemv(fe.dn_ty, fe.dn_rows, fe.dn_cols, fe.dn.addr(), fe.dn_stride, s.ids, k, s.y, 2 * nf, 1, s.d, None, s.xq)?; } - be.ink_ffn_sum(s.acc, s.d, s.wc, k, n, 0)?; + be.ink_ffn_sum(s.acc, s.d, s.wc, k, n, 0) + } + + /// What follows the experts of a layer run: the short convolution, the residual add, and the swap of the streams. + fn ffn_tail(&mut self, be: &dyn Backend, m: &Inkling2Model, il: usize, ip: usize) -> Result<()> { + let (c, ds, s) = (&m.cfg, &self.slots[il], self.s); + let (n, hd, nc) = (c.n_embd, c.head_dim, c.n_conv); + let hist3 = ds.hist.addr() + f(hists(c).0[3]); be.ink_conv(s.acc, self.layers[ip].convs[3].addr(), 0, hist3, s.acc, n, nc, hd)?; be.add(s.x, s.acc, n)?; (self.s.cur, self.s.x) = (s.x, s.cur); + Ok(()) + } + + fn layer_ffn_gpu(&mut self, be: &dyn Backend, m: &Inkling2Model, il: usize, ip: usize) -> Result { + let Some(fe) = &self.layers[ip].full_exps else { return Ok(false) }; + Self::ffn_core(be, &m.cfg, self.s, fe)?; + self.ffn_tail(be, m, il, ip)?; + Ok(true) + } + + /// `layer_ffn_gpu` for a layer whose experts are on GPU 1: the normed input crosses to it through the host, the + /// experts run there, and the sum comes back (two small copies and two syncs per layer run). False: not that kind of layer. + fn layer_ffn_remote(&mut self, d: &dev::Dev, m: &Inkling2Model, il: usize, ip: usize) -> Result { + let (Some(fe), Some(r)) = (&self.layers[ip].full_exps, &self.rem) else { return Ok(false) }; + if fe.part == 0 { return Ok(false) } + let (c, s, rs) = (&m.cfg, self.s, r.s); + let (be0, be1) = (&*d.parts[0].be, &*d.parts[r.part].be); + let (n, o0, o1) = (c.n_embd, self.scr.addr(), r.scr.addr()); + let xh_words = (n + n.div_ceil(32) * 4).div_ceil(16) * 4; + let hn: Vec = be0.get(&self.scr, ((s.hn - o0) / 4) as usize, n)?; + let xh: Vec = be0.get(&self.scr, ((s.xh - o0) / 4) as usize, xh_words)?; + be1.put(&hn, &r.scr, ((rs.hn - o1) / 4) as usize)?; + be1.put(&xh, &r.scr, ((rs.xh - o1) / 4) as usize)?; + Self::ffn_core(be1, c, rs, fe)?; + let acc: Vec = be1.get(&r.scr, ((rs.acc - o1) / 4) as usize, n)?; + be0.put(&acc, &self.scr, ((s.acc - o0) / 4) as usize)?; + self.ffn_tail(be0, m, il, ip)?; Ok(true) } @@ -1440,7 +1645,7 @@ impl Device { let d = lock(); let be = &*d.parts[0].be; self.layer_attn(be, &d, m, il, ip, msgs, pos, false, nb).expect("inkling2 device step"); - if self.layer_ffn_gpu(be, m, il, ip).expect("inkling2 device step") { + if self.layer_ffn_remote(&d, m, il, ip).expect("inkling2 device step remote") || self.layer_ffn_gpu(be, m, il, ip).expect("inkling2 device step") { m.lap(0, t); return; } @@ -1449,9 +1654,12 @@ impl Device { m.lap(0, t); // The experts: those of the GPU read the device's copy of the input and leave their outputs there. let (on_gpu, on_cpu, adapt) = m.plan(ip, &hn); + // Local patch: an expert with a matrix on another GPU cannot run in this GPU's queue; `remote` runs through + // `run_experts` (each matrix where it lives), next to the CPU share. + let on_first = |x: &Mat| x.gpu.is_none_or(|i| i == dev::STAGED || dev::gpu_of(i) == 0); + let (list, remote): (Vec<_>, Vec<_>) = Inkling2Model::resident(ml, c.n_expert, &on_gpu).into_iter().partition(|e| on_first(&e.0) && on_first(&e.1)); let gpu_side = || -> Option { let t = std::time::Instant::now(); - let list = Inkling2Model::resident(ml, c.n_expert, &on_gpu); let d = lock(); let (p, mut staged) = (&d.parts[0], None); (|| -> Option<()> { @@ -1496,15 +1704,24 @@ impl Device { let t = std::time::Instant::now(); (run_experts(&on_cpu, &hn, c), t.elapsed().as_secs_f32()) }; - let (gpu, (cpu, tc)) = rayon::join(gpu_side, cpu_side); + let remote_side = || (!remote.is_empty()).then(|| run_experts(&remote, &hn, c)); + let (gpu, ((cpu, tc), rem)) = rayon::join(gpu_side, || rayon::join(cpu_side, remote_side)); let d = lock(); let be = &*d.parts[0].be; match gpu { Some(tg) => { m.balance(&m.cpu_share, adapt, tg, tc); - let wc: Vec = (0..c.n_used).map(|i| on_gpu.get(i).map_or(0.0, |e| e.2)).chain(cpu).collect(); + // `cpu` and `r` are per-dimension sums (`run_experts` returns the weighted mix), not per-expert + // weights: both have length `n`, and the elementwise add is the host total. + debug_assert_eq!(cpu.len(), n); + let host: Vec = match rem { + Some(r) => { debug_assert_eq!(r.len(), n); cpu.iter().zip(&r).map(|(a, b)| a + b).collect() } + None => cpu, + }; + debug_assert_eq!(host.len(), n); + let wc: Vec = (0..c.n_used).map(|i| list.get(i).map_or(0.0, |e| e.2)).chain(host).collect(); be.put(&wc, &self.scr, ((s.wc - o) / 4) as usize).expect("inkling2 device step"); - be.ink_ffn_sum(s.acc, s.d, s.wc, on_gpu.len(), n, s.wc + f(c.n_used)).expect("inkling2 device step"); + be.ink_ffn_sum(s.acc, s.d, s.wc, list.len(), n, s.wc + f(c.n_used)).expect("inkling2 device step"); } None => { // No room to stage a routed weight (a card with little free VRAM): the experts of the GPU run on diff --git a/src/main.rs b/src/main.rs index a9a3ac4..6b5fff0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1391,16 +1391,25 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { } Cmd::Perplexity { model, file, ctx_len: n, chunks, kld_base, mut engine } => { let g = Gguf::open(&model)?; - let aux_g = open_mtp_gguf(engine.aux_model_path())?; - let m = Model::load_with_aux(&g, aux_g.as_ref(), &engine.lora_specs())?; let tok = Tokenizer::from_gguf(&g)?; // ponytail: no BOS at chunk starts (llama-perplexity adds one where the vocabulary asks for it; Qwen does not) let ids = tok.encode(&std::fs::read_to_string(&file)?)?; let n_chunk = (ids.len() / n).min(chunks.unwrap_or(usize::MAX)); anyhow::ensure!(n >= 4 && n_chunk > 0, "{} tokens: need at least one chunk of --ctx-len {n} (>= 4)", ids.len()); engine.ctx = engine.ctx.max(n); - let mut r = engine.runner(&m, &model)?; - let nv = m.cfg.n_vocab; + // Inkling 2 runs its own forward (`Model` does not load that architecture); it scores the same way, so + // `--kld-base` compares it with another build the same as it compares llama.cpp with the others. + let mut ink = if g.get("general.architecture").ok().and_then(|v| v.as_str()).is_some_and(rusting_strata::inkling2::is_arch) { + rusting_strata::inkling2::chat::gpu_defaults(); + engine.ds_env(); + Some(rusting_strata::inkling2::forward::Inkling2Model::new_with_ctx(&g, n)?) + } else { + None + }; + let aux_g = if ink.is_none() { open_mtp_gguf(engine.aux_model_path())? } else { None }; + let m = if ink.is_none() { Some(Model::load_with_aux(&g, aux_g.as_ref(), &engine.lora_specs())?) } else { None }; + let mut r = match &m { Some(m) => Some(engine.runner(m, &model)?), None => None }; + let nv = match (&ink, &m) { (Some(im), _) => im.cfg.n_vocab, (_, Some(m)) => m.cfg.n_vocab, _ => unreachable!() }; let mut out = kld_base.map(|p| std::fs::File::create(p).map(std::io::BufWriter::new)).transpose()?; if let Some(o) = &mut out { o.write_all(b"_logits_")?; @@ -1410,10 +1419,19 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { let (mut nll, mut count, mut row) = (0f64, 0usize, Vec::new()); let first = n / 2; for c in ids.chunks_exact(n).take(n_chunk) { - r.reset()?; - let mut logits = r.prefill(&c[..=first])?; + let mut logits = match (&mut ink, &mut r) { + (Some(im), _) => { im.reset(); im.prefill(&c[..=first]) } + (_, Some(run)) => { run.reset()?; run.prefill(&c[..=first])? } + _ => unreachable!(), + }; for i in first..n - 1 { - if i > first { logits = r.step(c[i])?; } + if i > first { + logits = match (&mut ink, &mut r) { + (Some(im), _) => im.step(c[i]), + (_, Some(run)) => run.step(c[i])?, + _ => unreachable!(), + }; + } anyhow::ensure!(logits.len() == nv, "{} logits, vocabulary {nv}", logits.len()); nll += log_probs(&logits, c[i + 1], &mut row); if let Some(o) = &mut out { for v in &row { o.write_all(&v.to_le_bytes())?; } } @@ -1423,7 +1441,7 @@ fn run(cmd: Cmd) -> anyhow::Result<()> { } if let Some(o) = &mut out { o.flush()?; } println!("\nPPL = {:.4} over {n_chunk} chunks of {n} tokens ({count} scored)", (nll / count as f64).exp()); - r.finish()?; + if let Some(run) = &mut r { run.finish()?; } } Cmd::Bench { model, pp, tg, reps, json_out, prompt_file, mut engine } => { if let Some(f) = &prompt_file { @@ -2215,7 +2233,9 @@ fn gemma_bench_chunk(v: Option<&str>) -> usize { /// `strata bench` for Inkling 2 (uses GPU argmax decode, plus `--draft-model` DSpark / `--spec-type` context lookup). fn bench_inkling2(g: &Gguf, model: &Path, pp: &[usize], tg: usize, reps: usize, json_out: Option, engine: &mut Engine) -> anyhow::Result<()> { - rusting_strata::deepseek::chat::gpu_defaults(); + // The same defaults `chat`, `generate` and `serve` set: without them the plain weights spread over both cards, + // `Device::new` refuses the second one and the whole benchmark runs the host path (about a fifth of the speed). + rusting_strata::inkling2::chat::gpu_defaults(); let tok = Tokenizer::from_gguf(g)?; let max_ctx = engine.ctx.max(pp.iter().copied().max().unwrap_or(0) + tg + 64); let opts = rusting_strata::inkling2::chat::Inkling2Opts { diff --git a/tests/bench_script.rs b/tests/bench_script.rs new file mode 100644 index 0000000..210f4f5 --- /dev/null +++ b/tests/bench_script.rs @@ -0,0 +1,150 @@ +//! `tools/bench_2x3060.sh`: a row that fails or prints nothing must not end the sweep, the sweep must exit nonzero +//! when a row was lost, and the environment must reach `bench` (`gpu_defaults` sets `STRATA_DS_PLAIN_FIRST=1` only +//! when it is unset, so the script must not unset it). +#![cfg(unix)] + +use std::os::unix::fs::PermissionsExt; +use std::path::PathBuf; + +/// Run the sweep with `--pp 512,2048 --ctx 32768` against `body` as `BIN`; `out` adds `--out`. Returns the temp +/// dir and the output. +fn sweep(tag: &str, body: &str, out: bool) -> (PathBuf, std::process::Output) { + let dir = + std::env::temp_dir().join(format!("strata-bench-script-{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + // `BIN` is checked with `-f` after the script cds to the repo root, so it is a path, not a name on PATH. + let bin = dir.join("fake"); + std::fs::write(&bin, body).unwrap(); + std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap(); + let json = dir.join("out").to_string_lossy().into_owned(); + let mut cmd = std::process::Command::new("bash"); + cmd.arg(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tools/bench_2x3060.sh" + )) + .args(["--pp", "512,2048", "--ctx", "32768"]) + .env("BIN", &bin) + .env("STRATA_INKLING2_MODEL", "/dev/null") + .env("FAKE_LOG", dir.join("calls")) + .env("STRATA_DS_PLAIN_FIRST", "0"); + if out { + cmd.args(["--out", &json]); + } + let out = cmd.output().unwrap(); + (dir, out) +} + +fn report(out: &std::process::Output) -> String { + format!( + "status {}\nstdout:\n{}\nstderr:\n{}", + out.status, + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ) +} + +#[test] +fn a_failed_row_does_not_end_the_sweep() { + let (dir, out) = sweep( + "failed-row", + r#"#!/bin/sh +if echo "$*" | grep -q -- "--pp 512"; then echo boom >&2; exit 1; fi +echo "pp 2048: prefill 100.0 (100.0-100.0) tok/s | tg 32: decode 50.0 (50.0-50.0) tok/s" +echo "${STRATA_DS_PLAIN_FIRST:-unset}" >> "$FAKE_LOG" +"#, + false, + ); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + !out.status.success(), + "a sweep with a lost row must exit nonzero: {}", + report(&out) + ); + // The table row of the second prompt: ctx pp prefill decode. + assert!( + stdout + .lines() + .any(|l| l.split_whitespace().eq(["32768", "2048", "100.0", "50.0"])), + "the row after the failure is missing: {}", + report(&out) + ); + assert!( + stdout.lines().any( + |l| l.contains("pp 512") && (l.contains("no result") || l.contains("bench failed")) + ), + "no diagnostic for the failed row: {}", + report(&out) + ); + let calls = std::fs::read_to_string(dir.join("calls")).unwrap_or_default(); + assert!( + !calls.is_empty(), + "the fake bench never ran: {}", + report(&out) + ); + for (i, line) in calls.lines().enumerate() { + assert_eq!( + line, + "0", + "call {} saw STRATA_DS_PLAIN_FIRST={line:?}, so the script unset it: {}", + i + 1, + report(&out) + ); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_row_with_no_output_does_not_end_the_sweep() { + let (dir, out) = sweep("silent-row", "#!/bin/sh\nexit 0\n", false); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + !out.status.success(), + "a sweep with no rows must exit nonzero: {}", + report(&out) + ); + let missing = stdout + .lines() + .filter(|l| l.contains("no result") || l.contains("bench failed")) + .count(); + assert_eq!( + missing, + 2, + "both rows must report no result: {}", + report(&out) + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_successful_sweep_exits_zero_with_out() { + let (dir, out) = sweep( + "ok-out", + r#"#!/bin/sh +pp="" +prev="" +for a in "$@"; do + [ "$prev" = "--pp" ] && pp="$a" + prev="$a" +done +echo "pp $pp: prefill 100.0 (100.0-100.0) tok/s | tg 32: decode 50.0 (50.0-50.0) tok/s" +"#, + true, + ); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + out.status.success(), + "a successful sweep must exit zero: {}", + report(&out) + ); + for pp in ["512", "2048"] { + assert!( + stdout + .lines() + .any(|l| l.split_whitespace().eq(["32768", pp, "100.0", "50.0"])), + "the pp {pp} row is missing: {}", + report(&out) + ); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/tests/inkling2_ctrl.rs b/tests/inkling2_ctrl.rs new file mode 100644 index 0000000..5a56f44 --- /dev/null +++ b/tests/inkling2_ctrl.rs @@ -0,0 +1,50 @@ +//! The tiled controller path (`STRATA_DS_FAST_KERNELS=1`, `nt >= 64`): `ink_ctrl_n` must match the per-token +//! `ink_ctrl` for every token. Separate test binary so the env is isolated. +mod common; +use common::{down, up}; +use rusting_strata::backend::Backend; + +fn xs(n: usize) -> Vec { (0..n).map(|i| ((i as f32 * 0.7548777).fract() - 0.5) * 2.0).collect() } + +fn rel_l2(a: &[f32], b: &[f32]) -> f32 { + let num: f32 = a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum(); + let den: f32 = b.iter().map(|y| y * y).sum(); + (num / den.max(1e-30)).sqrt() +} + +#[test] +fn tiled_controllers_match_per_token() { + unsafe { std::env::set_var("STRATA_DS_FAST_KERNELS", "1") }; + for (bk, gpu) in common::backends() { + let gpu = &*gpu; + if bk != "cuda" { continue; } + let (rank, count, n, nt) = (4usize, 3usize, 128usize, 64usize); + let down_w: Vec = xs(count * rank * 2 * n + 7)[7..].iter().map(|&v| half::f16::from_f32(v * 0.25).to_bits()).collect(); + let gain_w: Vec = xs(count * rank * n + 13)[13..].iter().map(|&v| half::f16::from_f32(v * 0.25).to_bits()).collect(); + let forget_w: Vec = xs(count * rank * n + 19)[19..].iter().map(|&v| half::f16::from_f32(v * 0.25).to_bits()).collect(); + let msg = xs(count * nt * n + 23)[23..].to_vec(); + for nins in [1usize, count] { + let cur_c = xs(nins * nt * n + 31)[31..].to_vec(); + let (dd, dg, df) = (up(gpu, &down_w), up(gpu, &gain_w), up(gpu, &forget_w)); + let mut want = vec![0.0f32; count * nt * n]; + let dgate1 = gpu.zeros::(count * rank).unwrap(); + for tok in 0..nt { + let mut c1 = Vec::with_capacity(nins * n); + for j in 0..nins { c1.extend_from_slice(&cur_c[(j * nt + tok) * n..(j * nt + tok + 1) * n]); } + let mut m1 = Vec::with_capacity(count * n); + for j in 0..count { m1.extend_from_slice(&msg[(j * nt + tok) * n..(j * nt + tok + 1) * n]); } + let (dc1, dm1, do1) = (up(gpu, &c1), up(gpu, &m1), gpu.zeros::(count * n).unwrap()); + gpu.ink_ctrl(dd.addr(), dg.addr(), df.addr(), dc1.addr(), nins, dm1.addr(), dgate1.addr(), do1.addr(), n, rank, count).unwrap(); + let o1 = down::(gpu, &do1); + for j in 0..count { + want[(j * nt + tok) * n..(j * nt + tok + 1) * n].copy_from_slice(&o1[j * n..(j + 1) * n]); + } + } + let (dcc, dmm, dgg, doo) = (up(gpu, &cur_c), up(gpu, &msg), + gpu.zeros::(nt * count * rank).unwrap(), gpu.zeros::(count * nt * n).unwrap()); + gpu.ink_ctrl_n(dd.addr(), dg.addr(), df.addr(), dcc.addr(), nins, dmm.addr(), dgg.addr(), doo.addr(), n, rank, count, nt).unwrap(); + let got = down::(gpu, &doo); + assert!(rel_l2(&got, &want) < 1e-6, "{bk} tiled ink_ctrl_n nins={nins} nt={nt}"); + } + } +} diff --git a/tests/inkling2_prefill.rs b/tests/inkling2_prefill.rs new file mode 100644 index 0000000..098046d --- /dev/null +++ b/tests/inkling2_prefill.rs @@ -0,0 +1,66 @@ +//! The fast prefill path (`STRATA_DS_FAST_KERNELS=1`): `kp16` must cover every 16-token tile, including the +//! fallback for a relative-bias width it cannot read as float4. Separate test binary so the env is isolated. +mod common; +use common::{down, up}; +use rusting_strata::backend::Backend; + +fn xs(n: usize) -> Vec { (0..n).map(|i| ((i as f32 * 0.7548777).fract() - 0.5) * 2.0).collect() } + +fn rel_l2(a: &[f32], b: &[f32]) -> f32 { + let num: f32 = a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum(); + let den: f32 = b.iter().map(|y| y * y).sum(); + (num / den.max(1e-30)).sqrt() +} + +/// The 16-query prefill entry point is launched with a 16-token grid. When the relative-bias width does not fit its +/// four-query fallback (`nr > 32` or `nr % 4 != 0`), the wrapper must still cover all 16 tokens: one call to the +/// four-query kernel leaves tokens 4..15 of every tile unwritten. `nr=28` is the fast path, `nr=30` the tile fallback +/// and `nr=40` the wide-bias fallback (which also makes decode use the scalar kernel). +#[test] +fn ink_attn_prefill_kp16_fallback_covers_every_query() { + unsafe { std::env::set_var("STRATA_DS_FAST_KERNELS", "1") }; + for (bk, gpu) in common::backends() { + let gpu = &*gpu; + // kp16 is the CUDA f16-cache path; Vulkan has its own prefill, and a quantized KV or the measurement knobs + // select another kernel. + if bk != "cuda" + || std::env::var_os("STRATA_KV").is_some() + || std::env::var_os("STRATA_DS_ATTN_OLD").is_some() + || std::env::var_os("STRATA_DS_ATTN_KP4").is_some() { continue; } + for nr in [28usize, 30, 40] { + let (nh, nkv, hd, ext, nt) = (2usize, 1usize, 128usize, 8usize, 20usize); + let q = xs(nt * nh * hd + 3)[3..].to_vec(); + let r = xs(nt * nh * nr + 5)[5..].to_vec(); + let sink = xs(nt * nh + 7)[7..].to_vec(); + let gate = xs(nt * nh * hd + 11)[11..].to_vec(); + let k = xs(nt * nkv * hd + 13)[13..].to_vec(); + let v = xs(nt * nkv * hd + 17)[17..].to_vec(); + let bias = xs(ext * nr + 19)[19..].to_vec(); + let kc: Vec = k.iter().map(|&x| half::f16::from_f32(x).to_bits()).collect(); + let vc: Vec = v.iter().map(|&x| half::f16::from_f32(x).to_bits()).collect(); + let (dq, dr, dsink, dgate) = (up(gpu, &q), up(gpu, &r), up(gpu, &sink), up(gpu, &gate)); + let (dkc, dvc, dbias) = (up(gpu, &kc), up(gpu, &vc), up(gpu, &bias)); + let dout = gpu.zeros::(nt * nh * hd).unwrap(); + gpu.ink_attn_prefill( + dq.addr(), dr.addr(), dsink.addr(), dgate.addr(), dkc.addr(), dvc.addr(), 0, 0, dbias.addr(), dout.addr(), + 0, nt, nh, nkv, hd, nr, ext, nt, 0, + ).unwrap(); + let dsc = gpu.zeros::(nh * nt.div_ceil(64) * (hd + 2)).unwrap(); + let mut want = Vec::with_capacity(nt * nh * hd); + for tok in 0..nt { + let dout1 = gpu.zeros::(nh * hd).unwrap(); + gpu.ink_attn( + dq.addr() + (tok * nh * hd * 4) as u64, + dr.addr() + (tok * nh * nr * 4) as u64, + dsink.addr() + (tok * nh * 4) as u64, + dgate.addr() + (tok * nh * hd * 4) as u64, + dkc.addr(), dvc.addr(), dbias.addr(), dsc.addr(), dout1.addr(), + tok + 1, tok, nh, nkv, hd, nr, ext, + ).unwrap(); + want.extend_from_slice(&down::(gpu, &dout1)); + } + let got = down::(gpu, &dout); + assert!(rel_l2(&got, &want) < 1e-6, "{bk} ink_attn_prefill kp16 fallback nr={nr} nt={nt}"); + } + } +} diff --git a/tools/bench_2x3060.sh b/tools/bench_2x3060.sh new file mode 100755 index 0000000..b7abad3 --- /dev/null +++ b/tools/bench_2x3060.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# Inkling 2 on two RTX 3060s: prompt lengths at a 32k and a 200k context, greedy decode, one repetition each. +# tools/bench_2x3060.sh [--model PATH] [--out STEM] [--pp LIST] [--ctx LIST] [--tg N] +# Prints one table row per (ctx, pp); with --out writes STEM--.json (`strata.bench.v1`) per row. +# +# The load line is printed under each row: how many expert layers are in VRAM and where decides most of the speed, +# and it depends on the free VRAM at that moment (a desktop on GPU 0 costs layers). A run whose line differs from +# the one in docs/BENCHMARKS.md is not comparable to it. +set -euo pipefail +cd "$(dirname "$0")/.." +model=${STRATA_INKLING2_MODEL:-} +out="" +pp_list="512,2048,4096" +ctx_list="32768 200000" +tg=32 +while [ $# -gt 0 ]; do + case "$1" in + --model) model=$2; shift 2 ;; + --out) out=$2; shift 2 ;; + --pp) pp_list=$2; shift 2 ;; + --ctx) ctx_list=$2; shift 2 ;; + --tg) tg=$2; shift 2 ;; + *) echo "unknown option: $1" >&2; exit 1 ;; + esac +done +bin=${BIN:-target/release/rustingstrata} +[ -n "$model" ] || { echo "set STRATA_INKLING2_MODEL or pass --model PATH" >&2; exit 1; } +# `bench` turns the plain-weights path on itself (`gpu_defaults` sets STRATA_DS_PLAIN_FIRST=1 when it is unset), so +# the environment is passed through: set STRATA_DS_PLAIN_FIRST=0 here to measure the other path (mat.rs reads "0" as off). +# If NVRTC is not on the loader path, set NVRTC_LIB to the directory that holds libnvrtc.so. +if [ -n "${NVRTC_LIB:-}" ]; then export LD_LIBRARY_PATH="$NVRTC_LIB${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"; fi +[ -f "$bin" ] || { echo "no $bin (cargo build --release)" >&2; exit 1; } +printf '%-8s %-10s %10s %10s\n' ctx pp prefill decode +fail=0 +for ctx in $ctx_list; do + for pp in ${pp_list//,/ }; do + log=$(mktemp) + # A fresh process per row: the prefill scratch and the KV are sized by the context, and a second prompt in the + # same process reuses them (a different measurement). + if [ -n "$out" ]; then + if ! env STRATA_DS_KV_TOKENS="$ctx" STRATA_DS_PF_TOKENS=512 \ + "$bin" bench --model "$model" --pp "$pp" --tg "$tg" --reps 1 --ctx "$ctx" --device 0,1 --gpu \ + --json-out "$out-$ctx-$pp.json" >"$log" 2>&1; then + echo "ctx $ctx pp $pp: no result"; sed -n '1,20p' "$log"; rm -f "$log"; fail=$((fail+1)); continue + fi + else + if ! env STRATA_DS_KV_TOKENS="$ctx" STRATA_DS_PF_TOKENS=512 \ + "$bin" bench --model "$model" --pp "$pp" --tg "$tg" --reps 1 --ctx "$ctx" --device 0,1 --gpu \ + >"$log" 2>&1; then + echo "ctx $ctx pp $pp: no result"; sed -n '1,20p' "$log"; rm -f "$log"; fail=$((fail+1)); continue + fi + fi + row=$(grep -E '^pp ' "$log" | tail -1 || true) + if [ -z "$row" ]; then + echo "ctx $ctx pp $pp: no result"; sed -n '1,20p' "$log"; rm -f "$log"; fail=$((fail+1)); continue + fi + # `pp 512: prefill V (...) tok/s | tg 32: decode D (...) tok/s`. + printf '%-8s %-10s %10s %10s\n' "$ctx" "$pp" "$(awk '{print $4}' <<<"$row")" "$(awk '{print $11}' <<<"$row")" + grep -E '^inkling2: preloaded' "$log" | sed 's/^inkling2: / /' || true + rm -f "$log" + done +done +[ "$fail" -eq 0 ] || exit 1 diff --git a/tools/kld_compare.py b/tools/kld_compare.py new file mode 100644 index 0000000..fb07e40 --- /dev/null +++ b/tools/kld_compare.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Compare two `perplexity --kld-base` files: KLD, top-token agreement, both PPLs, and how many cells moved. + + tools/kld_compare.py a.bin b.bin [--quiet] + +The file (written by `log_probs` in src/main.rs) is llama-perplexity's: `_logits_`, `n`, `n_vocab`, `n_chunks` +(u32 each), the `n_chunks * n` token ids (u32), then one row per scored position: the row's scale and offset (two +f32, as their u16 halves) and `n_vocab` u16 values, `logp(v) = offset + q(v) * scale` after dequantization. Two +builds of the engine that run the same kernels write byte-identical files; a kernel whose sums are reordered moves +the log-probabilities by a few ulp, below the u16 quantum (16 nats / 65535 = 2.4e-4), so most cells stay equal and +a few move by one step. + +Exit status: 0 when the files are byte-identical, 1 when they differ (the report says by how much). +""" + +import argparse +import struct +import sys + +import numpy as np + + +def header(f): + magic = f.read(8) + if magic != b"_logits_": + sys.exit(f"{f.name}: not a --kld-base file (starts with {magic[:8]!r})") + n, nv, nch = struct.unpack("