diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index e2d30cd16ea..ddaa603975f 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -609,6 +609,15 @@ vision tower: `Inkling2VisionEmbeddings`, `Inkling2VisionRotaryEmbedding`, `Inkl `Inkling2VisionMLP` and `Inkling2VisionMerger`. `zig/src/families/inkling2/image.zig` follows `Inkling2ImageProcessor` in `image_processing_inkling2.py` at the same commit for its 40-pixel patches and the tower's input tables. +## Inkling 2 DSpark drafter kernels + +`zig/kernels/cuda/inkling2/dspark.cu` and `zig/src/families/inkling2/dspark_ops.zig` compute the drafter in +`vllm/models/inkling2/nvidia/dspark.py` at commit `abb8194dc35e` of +[vllm-project/vllm](https://github.com/vllm-project/vllm) (Apache-2.0): the tap mix and its RMS norm in +`Inkling2DSparkDecoder.mix`, `Inkling2DraftSelfAttention`, `Inkling2DraftMLP` and the recurrent `Inkling2MarkovHead`. +The drafter's weights ship in Thinking Machines' Inkling 2 Small release under Apache-2.0. The kernels are TensorFold's +own. + ## Hy4-flash NVFP4 tensor table and build scripts `zig/src/families/hy4_flash/nvfp4_header.txt` lists names, types and shapes from the safetensors headers of the NVFP4 diff --git a/docs/design/inkling-2-mini.md b/docs/design/inkling-2-mini.md index a168fe87ebb..8c28a220d8f 100644 --- a/docs/design/inkling-2-mini.md +++ b/docs/design/inkling-2-mini.md @@ -100,6 +100,8 @@ DSpark support is part of the plan on both backends, not an extra: H4, C5 and M6 The engine slices C4 and M5 land first without it, so plain decode exists as the reference the drafter is checked against. The drafter taps by zero-based decoder visit: 5, 23 and 41 are the inputs to those visits, and 48 is the output after the final norm, not a cache slot. +On CUDA, the Mini adapter reuses #4858's batched DSpark Q/K, attention, context, recurrence and pick kernels across the active lane streams. It advertises batched drafting to the shared lane scheduler; without that fact, the scheduler passes only one stream to each hold and cannot use the grouped kernels. The serving adapter limits requested drafts to two per stream: the eight-row head is a kernel capacity, not a reason to verify mostly rejected rows across concurrent streams. The drafter checks the full unembedding checkpoint shape but packs only the valid vocabulary rows, so the batched matmul output, softcap and picks use the same row stride. The target computes its final norm before capturing the fourth tap or unembedding; the drafter's seven recurrent contexts use mask rows 1–7, aligned with its hidden projection. The adapter verifies proposals through the ordinary target and rolls back rejected rows. Passing this device path does not waive the same-engine fidelity and speed gate below. + ## Gate The gate is agreed; the speed bar below is its threshold. diff --git a/tools/bench_concurrent.py b/tools/bench_concurrent.py index 5e6aa14fa82..fc7d00a0658 100644 --- a/tools/bench_concurrent.py +++ b/tools/bench_concurrent.py @@ -330,7 +330,7 @@ def main() -> None: rep["pooled"] = bench_metrics.pooled(runs) rep["evidence"] = [{k: r.get(k) for k in ("prompt_tokens", "cached_tokens", "tokens", "cache_state", "complete", "token_sha", "token_sha256", "output_sha256", - "completion", "finish_reasons", "tool_calls", "tool_sha256")} + "completion", "finish_reasons", "tool_calls", "tool_sha256", "speculative")} for r in runs] rep["client_intervals"] = [{"start": r["sent"], "first": r.get("first"), "last": r.get("last"), "end": r.get("completed"), diff --git a/tools/zig/cuda_common_allowlist.json b/tools/zig/cuda_common_allowlist.json index 0d83d8a4f48..4bb5bc5d2b5 100644 --- a/tools/zig/cuda_common_allowlist.json +++ b/tools/zig/cuda_common_allowlist.json @@ -32,6 +32,10 @@ {"path":"zig/kernels/cuda/flashnext_gdn_tpr.cuh","kind":"asm:cp.async.wait_group","fingerprint":"f39f99cfddd23a17f459f43825e9603b36fb1dac7f464d7bec5fec0f40da73c8","count":1,"reason":"This cp.async.wait_group uses its literal pending-group count at this dependency boundary; a helper substitution needs the same immediate, scheduling and machine code."}, {"path":"zig/kernels/cuda/glm_triton.cuh","kind":"definition:block_sum","fingerprint":"c668775654a3913f9ca96e2b23f2d4be09aef3b2ecbe60e46d06f7a510cecbbb","count":1,"reason":"Triton NW-dependent butterfly and early return; different reduction order."}, {"path":"zig/kernels/cuda/glm_vision.cu","kind":"definition:block_sum","fingerprint":"679cb663bd7688332a53b69d2a4ecbf5d94ba8f0b9318aa279f21e1586fa5d41","count":1,"reason":"Tree reduction owns shared scratch and broadcasts through total; shape differs from shared tree."}, +{"path":"zig/kernels/cuda/inkling2/attention.cu","kind":"definition:warpSum","fingerprint":"23eaa1ba706617a178d504e531ed1537b557d8428c2b881a3ffc6e92c07b8f76","count":1,"reason":"Inkling 2's attention keeps its xor butterfly, offsets 16 down to 1, the order tf_common::warp_sum uses; the swap needs identical SASS on the family's images."}, +{"path":"zig/kernels/cuda/inkling2/dspark.cu","kind":"definition:blockSum","fingerprint":"6e1159a5a63b8da0f60b6ae6fdbccfa959c996a2d255066335d30a21b642b7c2","count":1,"reason":"Core block_sum_tree compiles to different SASS; this broadcast form keeps the DSpark kernels' recorded machine code."}, +{"path":"zig/kernels/cuda/inkling2/ops.cu","kind":"definition:blockSums","fingerprint":"60bc85468608b496a7c788416a3db98223e96585e76d8842367bea5c21d1c0e2","count":1,"reason":"Sums N values a thread in one pass behind one pair of barriers; the shared block sums take one value a call."}, +{"path":"zig/kernels/cuda/inkling2/ops.cu","kind":"definition:warpSum","fingerprint":"23eaa1ba706617a178d504e531ed1537b557d8428c2b881a3ffc6e92c07b8f76","count":1,"reason":"Inkling 2's glue keeps its xor butterfly, offsets 16 down to 1, the order tf_common::warp_sum uses; the swap needs identical SASS on the family's images."}, {"path":"zig/kernels/cuda/lfm2.cu","kind":"definition:block_sum","fingerprint":"d9816f70067e6b5d8b584e4a323f9aa0c84309292758719e0b2f1364e66d6c67","count":1,"reason":"Serial sum starts at red[0] with family-specific barriers; retain order and signed-zero behavior."}, {"path":"zig/kernels/cuda/minimax_m3.cuh","kind":"asm:mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32","fingerprint":"edff3872cb8a0cba7404cb7e391b3fdfdabee3a8109294582e49b95953721be9","count":1,"reason":"Expert projections retain the mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 accumulator and operand constraints; a shared substitution needs machine-code identity checks."}, {"path":"zig/kernels/cuda/minimax_m3.cuh","kind":"definition:block_sum","fingerprint":"5cdf621633053e5319eafb758a82aa96a7b2716308018e821e84724de1c518dc","count":1,"reason":"Leading-sync serial block sum with no trailing sync; deliberate shape variant."}, diff --git a/tools/zig/cuda_common_check.py b/tools/zig/cuda_common_check.py index f859995a049..36008b7cf54 100644 --- a/tools/zig/cuda_common_check.py +++ b/tools/zig/cuda_common_check.py @@ -11,7 +11,7 @@ ALLOW = Path(__file__).with_name("cuda_common_allowlist.json") TOKEN = re.compile(r'//[^\n]*|/\*[\s\S]*?\*/|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|[A-Za-z_]\w*|\d+(?:\.\d*)?|[^\s]') OPS = re.compile(r'\b(?:ldmatrix[.\w]*|mma\.sync[.\w]*|cp\.async[.\w]*|ld\.global\.nc[.\w]*|griddepcontrol[.\w]*)') -NAMES = re.compile(r'(?:warp_sum|block_sum\w*|fp4pair|fp8pair|e4m3f|unpack8|pack8)\Z') +NAMES = re.compile(r'(?:[wW]arp_?[sS]um|[bB]lock_?[sS]um\w*|fp4pair|fp8pair|e4m3f|unpack8|pack8)\Z') @dataclass(frozen=True) diff --git a/tools/zig/cuda_common_check_test.py b/tools/zig/cuda_common_check_test.py index 6348147dd1a..e4655143df8 100644 --- a/tools/zig/cuda_common_check_test.py +++ b/tools/zig/cuda_common_check_test.py @@ -80,6 +80,13 @@ def test_every_requested_instruction_and_definition(self): self.unit.write_text(DEFINITION + DEFINITION.replace("warp_sum", name)) self.assertIn("definition:" + name, " ".join(self.errors())) + def test_camel_case_reductions(self): + for name in ("warpSum", "WarpSum", "blockSum", "blockSums", "BlockSumTree"): + self.unit.write_text(DEFINITION + DEFINITION.replace("warp_sum", name)) + self.assertIn("definition:" + name, " ".join(self.errors())) + self.unit.write_text(DEFINITION + DEFINITION.replace("warp_sum", "warpSumOf")) + self.assertEqual(self.errors(), []) + if __name__ == "__main__": unittest.main() diff --git a/zig/build/cuda_kernels.zig b/zig/build/cuda_kernels.zig index cc0c00e15e5..b0df6ae795d 100644 --- a/zig/build/cuda_kernels.zig +++ b/zig/build/cuda_kernels.zig @@ -167,6 +167,7 @@ pub const kernels = [_]Kernel{ .{ .name = "inkling2_pattn", .src = "inkling2/prompt_attention", .flags = &.{"-O3"} }, // ours: Inkling 2's global-layer prompt attention .{ .name = "inkling2_ops", .src = "inkling2/ops", .flags = glue }, // ours: Inkling 2's residual mix, convs, router, SwiGLU .{ .name = "inkling2_rows", .src = "inkling2/rows", .flags = glue }, // ours: Inkling 2's router row dots on prompt rows + .{ .name = "inkling2_dspark", .src = "inkling2/dspark", .flags = glue }, // Inkling 2 DSpark kernels .{ .name = "ricursive", .flags = glue }, // ours: Ripple's glue (embed, add-norms, output gate, FFN activation), glue.metal step for step .{ .name = "ricursive_prep", .flags = glue }, // ours: Ripple's attention prep (q/k head norms, RoPE, K and V into rings or pages) .{ .name = "inkling2_experts", .src = "inkling2/experts", .flags = &.{ "-O3", "--expt-relaxed-constexpr" } }, // ours: Inkling 2's grouped experts diff --git a/zig/kernels/cuda/act_rows.cu b/zig/kernels/cuda/act_rows.cu index 0f5bce5bea0..531a9086222 100644 --- a/zig/kernels/cuda/act_rows.cu +++ b/zig/kernels/cuda/act_rows.cu @@ -22,11 +22,19 @@ __device__ __forceinline__ float sigmoid(float x) { return tf_common::sigmoid_rn using namespace tf_act; -// out[r, i] = bf16(silu(gate[r * g_ld + i]) * up[r * u_ld + i]) for i < n (n % 64 == 0); xs (or null) out's sums. -extern "C" __global__ void __launch_bounds__(NT) tf_swiglu_rows(const __nv_bfloat16* __restrict__ gate, long long g_ld, - const __nv_bfloat16* __restrict__ up, long long u_ld, - __nv_bfloat16* __restrict__ out, float* __restrict__ xs, - int n) { +namespace tf_act { + +// silu(g) * u: core's g * sigmoid(g), or with Torch torch's g / (1 + expf(-g)), each step rounded as written. +template +__device__ __forceinline__ float silu_mul(float g, float u) { + if (Torch) return __fmul_rn(__fdiv_rn(g, __fadd_rn(1.0f, expf(-g))), u); + return __fmul_rn(__fmul_rn(g, sigmoid(g)), u); +} + +template +__device__ __forceinline__ void swiglu_rows(const __nv_bfloat16* __restrict__ gate, long long g_ld, + const __nv_bfloat16* __restrict__ up, long long u_ld, + __nv_bfloat16* __restrict__ out, float* __restrict__ xs, int n) { const int64_t r = blockIdx.x; const int c = blockIdx.y * blockDim.x + threadIdx.x; // 8 values const bool live = 8 * c < n; @@ -36,7 +44,7 @@ extern "C" __global__ void __launch_bounds__(NT) tf_swiglu_rows(const __nv_bfloa unpack8(*reinterpret_cast(up + r * u_ld + 8 * c), u); } #pragma unroll - for (int i = 0; i < 8; ++i) o[i] = live ? __fmul_rn(__fmul_rn(g[i], sigmoid(g[i])), u[i]) : 0.f; + for (int i = 0; i < 8; ++i) o[i] = live ? silu_mul(g[i], u[i]) : 0.f; const uint4 op = pack8(o); if (live) *reinterpret_cast(out + r * n + 8 * c) = op; if (xs != nullptr) { @@ -45,6 +53,24 @@ extern "C" __global__ void __launch_bounds__(NT) tf_swiglu_rows(const __nv_bfloa } } +} // namespace tf_act + +// out[r, i] = bf16(silu(gate[r * g_ld + i]) * up[r * u_ld + i]) for i < n (n % 64 == 0); xs (or null) out's sums. +extern "C" __global__ void __launch_bounds__(NT) tf_swiglu_rows(const __nv_bfloat16* __restrict__ gate, long long g_ld, + const __nv_bfloat16* __restrict__ up, long long u_ld, + __nv_bfloat16* __restrict__ out, float* __restrict__ xs, + int n) { + tf_act::swiglu_rows(gate, g_ld, up, u_ld, out, xs, n); +} + +// tf_swiglu_rows with torch's silu, g / (1 + expf(-g)): Inkling 2's DSpark drafter (expf, not tf_exp, for its bits). +extern "C" __global__ void __launch_bounds__(NT) tf_swiglu_rows_expf(const __nv_bfloat16* __restrict__ gate, long long g_ld, + const __nv_bfloat16* __restrict__ up, long long u_ld, + __nv_bfloat16* __restrict__ out, float* __restrict__ xs, + int n) { + tf_act::swiglu_rows(gate, g_ld, up, u_ld, out, xs, n); +} + // out[r, h * d + e] = bf16(o[r, h * d + e] * sigmoid(g[r * g_ld + h * g_hs + e])) (d % 64 == 0); xs (or null) its sums. extern "C" __global__ void __launch_bounds__(NT) tf_gate_rows(const __nv_bfloat16* __restrict__ o, const __nv_bfloat16* __restrict__ g, long long g_ld, diff --git a/zig/kernels/cuda/common/dspark_pick.cuh b/zig/kernels/cuda/common/dspark_pick.cuh new file mode 100644 index 00000000000..fa9cf666561 --- /dev/null +++ b/zig/kernels/cuda/common/dspark_pick.cuh @@ -0,0 +1,26 @@ +// DSpark's pick merge, one body for every family: the ranks' gathered (value, id) picks to the walk's next token. +#pragma once + +#include + +namespace tf_common { + +// Thread 0, picks stride bytes apart: the largest value, the lower id on a tie, kNone when none beats -Inf. +template +__device__ __forceinline__ void dspark_pick(const unsigned char* __restrict__ picks, int world, int stride, + int* __restrict__ walk, int j) { + if (threadIdx.x != 0) return; + float best = -CUDART_INF_F; + int id = kNone; + for (int q = 0; q < world; ++q) { + const float v = *reinterpret_cast(picks + (size_t)q * stride); + const int k = *reinterpret_cast(picks + (size_t)q * stride + 4); + if (v > best || (v == best && k < id)) { + best = v; + id = k; + } + } + walk[j + 1] = id; +} + +} // namespace tf_common diff --git a/zig/kernels/cuda/inkling2/dspark.cu b/zig/kernels/cuda/inkling2/dspark.cu new file mode 100644 index 00000000000..b37ffe39047 --- /dev/null +++ b/zig/kernels/cuda/inkling2/dspark.cu @@ -0,0 +1,361 @@ +// Inkling 2's DSpark drafter: tap mix, q/k norm + RoPE into the draft caches, block attention, the Markov head. +#include +#include + +#include "common/dspark_pick.cuh" +#include "common/reduce.cuh" + +namespace ink2d { + +constexpr int kD = 128; +constexpr int kMaxQ = 48; +constexpr int kKT = 32; +constexpr int kChunk = 1024; +constexpr int kMaxRows = 8; + +__device__ __forceinline__ float bf(uint16_t u) { return __uint_as_float(static_cast(u) << 16); } + +__device__ __forceinline__ uint16_t tobf(float f) { return __bfloat16_as_ushort(__float2bfloat16_rn(f)); } + +__device__ __forceinline__ float bfr(float f) { return bf(tobf(f)); } + +// One sum over the block in a fixed order: warp shuffles, then warp 0 over the warps' partials. +__device__ __forceinline__ float blockSum(float v, float* sh) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5; + v = tf_common::warp_sum(v); + __syncthreads(); + if (lane == 0) sh[w] = v; + __syncthreads(); + const float t = lane < nw ? sh[lane] : 0.0f; + return __shfl_sync(0xffffffffu, tf_common::warp_sum(t), 0); +} + +} // namespace ink2d + +// out[row] = RMSNorm(sum_t alpha[t] * taps[row][t]) * w, the mix in fp32 in tap order (vLLM's mix_rmsnorm). +extern "C" __global__ void __launch_bounds__(512) tf_ink2_dsp_mix(const uint16_t* __restrict__ taps, const float* __restrict__ alpha, + const uint16_t* __restrict__ w, uint16_t* __restrict__ out, + int taps_n, int C, float eps) { + using namespace ink2d; + __shared__ float sh[32]; + const size_t row = blockIdx.x; + const uint16_t* x = taps + row * taps_n * C; + float ss = 0.0f; + for (int c = threadIdx.x; c < C; c += blockDim.x) { + float m = 0.0f; + for (int t = 0; t < taps_n; ++t) m += bf(x[t * C + c]) * alpha[t]; + ss += m * m; + } + const float r = rsqrtf(blockSum(ss, sh) / C + eps); + for (int c = threadIdx.x; c < C; c += blockDim.x) { + float m = 0.0f; + for (int t = 0; t < taps_n; ++t) m += bf(x[t * C + c]) * alpha[t]; + out[row * C + c] = tobf(m * r * bf(w[c])); + } +} + +// Unlike core's add-norms: resid stays bf16 (+= fp32 partials in rank order); out = RMSNorm of the unrounded sum * w. +extern "C" __global__ void __launch_bounds__(512) tf_ink2_dsp_addnorm(uint16_t* __restrict__ resid, const float* __restrict__ parts, + int nparts, long long part_stride, const uint16_t* __restrict__ w, + uint16_t* __restrict__ out, int C, float eps) { + using namespace ink2d; + __shared__ float sh[32]; + const size_t row = blockIdx.x; + float ss = 0.0f; + for (int c = threadIdx.x; c < C; c += blockDim.x) { + float s = 0.0f; + for (int p = 0; p < nparts; ++p) s += parts[p * part_stride + row * C + c]; + const float v = bf(resid[row * C + c]) + s; + ss += v * v; + } + const float r = rsqrtf(blockSum(ss, sh) / C + eps); + for (int c = threadIdx.x; c < C; c += blockDim.x) { + float s = 0.0f; + for (int p = 0; p < nparts; ++p) s += parts[p * part_stride + row * C + c]; + const float v = bf(resid[row * C + c]) + s; + if (nparts > 0) resid[row * C + c] = tobf(v); + out[row * C + c] = tobf(v * r * bf(w[c])); + } +} + +struct QkArgs { + const uint16_t* x; // bf16 [rows][ld]: q heads, then key heads, then value heads (128 wide each) + const uint16_t* qw; + const uint16_t* kw; + uint16_t* q; // bf16 [rows][hq][128] + uint16_t* kc; // bf16 [ring][hk][128] + uint16_t* vc; + long long ld; + int hq, hk, ring, pos0; + float eps, theta; +}; + +// Per (row, head): RMSNorm * weight rounded to bf16, then neox RoPE at pos0 + row; key and value heads to the caches. +extern "C" __global__ void __launch_bounds__(64) tf_ink2_dsp_qk(QkArgs a) { + using namespace ink2d; + __shared__ float sh[32]; + const int row = blockIdx.x, h = blockIdx.y, i = threadIdx.x; + const bool isq = h < a.hq; + const uint16_t* x = a.x + row * a.ld + static_cast(h) * kD; + const float x0 = bf(x[i]), x1 = bf(x[i + 64]); + const float inv = 1.0f / sqrtf(blockSum(x0 * x0 + x1 * x1, sh) / kD + a.eps); + const uint16_t* w = isq ? a.qw : a.kw; + const float y0 = bfr(x0 * inv * bf(w[i])), y1 = bfr(x1 * inv * bf(w[i + 64])); + const int pos = a.pos0 + row; + const float f = static_cast(pos) * (1.0f / powf(a.theta, static_cast(2 * i) / kD)); + const float co = cosf(f), si = sinf(f); + const uint16_t o0 = tobf(y0 * co - y1 * si), o1 = tobf(y1 * co + y0 * si); + if (isq) { + uint16_t* q = a.q + (static_cast(row) * a.hq + h) * kD; + q[i] = o0; + q[i + 64] = o1; + return; + } + const int j = h - a.hq; + const size_t at = (static_cast(pos % a.ring) * a.hk + j) * kD; + a.kc[at + i] = o0; + a.kc[at + i + 64] = o1; + const uint16_t* v = a.x + row * a.ld + static_cast(a.hq + a.hk + j) * kD; + a.vc[at + i] = v[i]; + a.vc[at + i + 64] = v[i + 64]; +} + +struct AttnArgs { + const uint16_t* q; // bf16 [T][hq][128] + const uint16_t* kc; // bf16 [ring][hk][128] + const uint16_t* vc; + float* po; // fp32 [chunks][T * hq][128]: unnormalised sums + float* pml; // fp32 [chunks][T * hq][2]: max, total + int T, hq, hk, ring, lo, hi, c0; + float scale; +}; + +// A block's rows against keys [lo, hi], unmasked (the block sees itself whole); a 1,024-key chunk and key head a block. +extern "C" __global__ void __launch_bounds__(256) tf_ink2_dsp_attn(AttnArgs a) { + using namespace ink2d; + __shared__ float sq[kMaxQ][kD]; + __shared__ uint16_t sk[kKT][kD + 8]; + __shared__ uint16_t sv[kKT][kD]; + __shared__ float sp[kMaxQ][kKT]; + __shared__ float sm[kMaxQ], sl[kMaxQ], sa[kMaxQ]; + const int j = blockIdx.y, c = a.c0 + blockIdx.x, tid = threadIdx.x; + const int g = a.hq / a.hk, nq = a.T * g, nqt = a.T * a.hq; + const int k0 = max(a.lo, c * kChunk), k1 = min(a.hi + 1, (c + 1) * kChunk); + for (int idx = tid; idx < nq * kD; idx += blockDim.x) { + const int qi = idx / kD, d = idx % kD; + sq[qi][d] = bf(a.q[(static_cast(qi / g) * a.hq + j * g + qi % g) * kD + d]); + } + for (int qi = tid; qi < nq; qi += blockDim.x) { + sm[qi] = -INFINITY; + sl[qi] = 0.0f; + } + const int d = tid & (kD - 1), half = tid >> 7; + float o[kMaxQ / 2]; + for (int r = 0; r < kMaxQ / 2; ++r) o[r] = 0.0f; + __syncthreads(); + for (int kt = k0; kt < k1; kt += kKT) { + const int nk = min(kKT, k1 - kt); + for (int idx = tid; idx < nk * kD; idx += blockDim.x) { + const int kk = idx / kD, dd = idx % kD; + const size_t at = (static_cast((kt + kk) % a.ring) * a.hk + j) * kD + dd; + sk[kk][dd] = a.kc[at]; + sv[kk][dd] = a.vc[at]; + } + __syncthreads(); + for (int idx = tid; idx < nq * kKT; idx += blockDim.x) { + const int qi = idx / kKT, kk = idx % kKT; + float s = -INFINITY; + if (kk < nk) { + s = 0.0f; + for (int dd = 0; dd < kD; ++dd) s += sq[qi][dd] * bf(sk[kk][dd]); + s *= a.scale; + } + sp[qi][kk] = s; + } + __syncthreads(); + for (int qi = tid; qi < nq; qi += blockDim.x) { + float mx = sm[qi]; + for (int kk = 0; kk < nk; ++kk) mx = fmaxf(mx, sp[qi][kk]); + const float al = expf(sm[qi] - mx); + float sum = 0.0f; + for (int kk = 0; kk < nk; ++kk) { + const float p = expf(sp[qi][kk] - mx); + sp[qi][kk] = p; + sum += p; + } + sl[qi] = sl[qi] * al + sum; + sm[qi] = mx; + sa[qi] = al; + } + __syncthreads(); + for (int r = 0; r < kMaxQ / 2; ++r) { + const int qi = half * (kMaxQ / 2) + r; + if (qi >= nq) break; + float acc = o[r] * sa[qi]; + for (int kk = 0; kk < nk; ++kk) acc += sp[qi][kk] * bf(sv[kk][d]); + o[r] = acc; + } + __syncthreads(); + } + for (int r = 0; r < kMaxQ / 2; ++r) { + const int qi = half * (kMaxQ / 2) + r; + if (qi >= nq) break; + const size_t rh = static_cast(blockIdx.x) * nqt + (qi / g) * a.hq + j * g + qi % g; + a.po[rh * kD + d] = o[r]; + if (d == 0) { + a.pml[rh * 2] = sm[qi]; + a.pml[rh * 2 + 1] = sl[qi]; + } + } +} + +// Each (row, head)'s chunks folded in order: out bf16 [T][hq][128]. +extern "C" __global__ void __launch_bounds__(128) tf_ink2_dsp_merge(const float* __restrict__ po, const float* __restrict__ pml, + int chunks, int nqt, uint16_t* __restrict__ out) { + using namespace ink2d; + const size_t rh = blockIdx.x; + const int d = threadIdx.x; + float mx = -INFINITY; + for (int c = 0; c < chunks; ++c) mx = fmaxf(mx, pml[(c * nqt + rh) * 2]); + float l = 0.0f, acc = 0.0f; + for (int c = 0; c < chunks; ++c) { + const float m = pml[(c * nqt + rh) * 2]; + const float wt = m == -INFINITY ? 0.0f : expf(m - mx); + l += pml[(c * nqt + rh) * 2 + 1] * wt; + acc += po[(c * nqt + rh) * kD + d] * wt; + } + out[rh * kD + d] = tobf(acc / l); +} + +// The Markov head's context: out fp32 [rows][3R] = bias + rnn_proj[:, 2R:] . [hidden_row, f_rnn], a warp an output. +extern "C" __global__ void __launch_bounds__(256) tf_ink2_dsp_ctx(const uint16_t* __restrict__ hidden, const uint16_t* __restrict__ frnn, + const uint16_t* __restrict__ W, const uint16_t* __restrict__ bias, + float* __restrict__ out, int rows, int C, int R) { + using namespace ink2d; + const int o = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (o >= 3 * R) return; + const uint16_t* w = W + static_cast(o) * (2 * R + 2 * C) + 2 * R; + float acc[kMaxRows]; + for (int r = 0; r < kMaxRows; ++r) acc[r] = 0.0f; + for (int k = lane; k < 2 * C; k += 32) { + const float wk = bf(w[k]); + if (k < C) { + for (int r = 0; r < kMaxRows; ++r) + if (r < rows) acc[r] += wk * bf(hidden[static_cast(r) * C + k]); + } else { + const float f = wk * bf(frnn[k - C]); + for (int r = 0; r < kMaxRows; ++r) acc[r] += f; + } + } + for (int r = 0; r < kMaxRows; ++r) { + const float s = tf_common::warp_sum(acc[r]); + if (lane == 0 && r < rows) out[static_cast(r) * 3 * R + o] = s + bf(bias[o]); + } +} + +// One recurrence step (one block, R threads): raw = ctx + rnn_proj[:, :2R] . [state, w1[prev]]; gated as the bf16 ops. +extern "C" __global__ void __launch_bounds__(256) tf_ink2_dsp_rnn(const float* __restrict__ ctx, const uint16_t* __restrict__ W, + const uint16_t* __restrict__ w1, const int* __restrict__ walk, int j, + uint16_t* __restrict__ state, uint16_t* __restrict__ latent, int R, int C) { + using namespace ink2d; + __shared__ float in[512]; + __shared__ float raw[768]; + const int c = threadIdx.x, lane = c & 31, wp = c >> 5, nw = blockDim.x >> 5; + const size_t prev = static_cast(walk[j]); + in[c] = bf(state[c]); + in[R + c] = bf(w1[prev * R + c]); + __syncthreads(); + const int ld = 2 * R + 2 * C; + for (int o = wp; o < 3 * R; o += nw) { + float s = 0.0f; + for (int k = lane; k < 2 * R; k += 32) s += bf(W[static_cast(o) * ld + k]) * in[k]; + s = tf_common::warp_sum(s); + if (lane == 0) raw[o] = s + ctx[o]; + } + __syncthreads(); + const float gate = bfr(1.0f / (1.0f + expf(-bfr(raw[c])))); + const float cand = bfr(tanhf(bfr(raw[R + c]))); + const float keep = bfr(gate * in[c]); + const float upd = bfr(bfr(1.0f - gate) * cand); + state[c] = tobf(keep + upd); + latent[c] = tobf(tanhf(bfr(raw[2 * R + c]))); +} + +// A step's logits over this rank's vocabulary: softcap(bf16(base + bf16(fold_bias + fold . latent))), -inf past valid. +extern "C" __global__ void __launch_bounds__(256) tf_ink2_dsp_vocab(const uint16_t* __restrict__ base, const uint16_t* __restrict__ latent, + const uint16_t* __restrict__ fold, const uint16_t* __restrict__ fbias, + float cap, int valid, int nv, float* __restrict__ out) { + using namespace ink2d; + const int v = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (v >= nv) return; + const uint16_t* f = fold + static_cast(v) * 256; + float s = 0.0f; + for (int k = lane; k < 256; k += 32) s += bf(latent[k]) * bf(f[k]); + s = tf_common::warp_sum(s); + if (lane != 0) return; + const float b = bfr(s + bf(fbias[v])); + const float x = bfr(bf(base[v]) + b); + out[v] = v < valid ? bfr(tanhf(x / cap) * cap) : -INFINITY; +} + +// tf_ink2_dsp_vocab for `rows` streams at once (base rows base_ld apart): each fold row read once, sums as its order. +extern "C" __global__ void __launch_bounds__(256) tf_ink2_dsp_vocab_rows(const uint16_t* __restrict__ base, long long base_ld, + const uint16_t* __restrict__ latent, + const uint16_t* __restrict__ fold, + const uint16_t* __restrict__ fbias, float cap, int valid, + int nv, int rows, float* __restrict__ out) { + using namespace ink2d; + const int v = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (v >= nv) return; + const uint16_t* f = fold + static_cast(v) * 256; + float w[8]; + for (int q = 0; q < 8; ++q) w[q] = bf(f[lane + 32 * q]); + const float fb = bf(fbias[v]); + for (int r = 0; r < rows; ++r) { + const uint16_t* lt = latent + static_cast(r) * 256; + float s = 0.0f; + for (int q = 0; q < 8; ++q) s += bf(lt[lane + 32 * q]) * w[q]; + s = tf_common::warp_sum(s); + if (lane == 0) { + const float b = bfr(s + fb); + const float x = bfr(bf(base[r * base_ld + v]) + b); + out[static_cast(r) * nv + v] = v < valid ? bfr(tanhf(x / cap) * cap) : -INFINITY; + } + } +} + +// tf_ink2_dsp_pick_merge for `rows` streams, a block a stream: rank q's pick of row r at (q * rows + r) * 16 bytes. +extern "C" __global__ void tf_ink2_dsp_pick_rows(const unsigned char* __restrict__ picks, int world, int rows, + int* __restrict__ walk, int T, int j) { + const int r = blockIdx.x; + tf_common::dspark_pick<0x7fffffff>(picks + (size_t)r * 16, world, rows * 16, walk + (size_t)r * T, j); +} + +// The ranks' (value, id) picks to walk[j + 1]: MiniMax M3's merge, with 0x7fffffff when no value beats -Inf. +extern "C" __global__ void tf_ink2_dsp_pick_merge(const unsigned char* __restrict__ picks, int world, int stride, + int* __restrict__ walk, int j) { + tf_common::dspark_pick<0x7fffffff>(picks, world, stride, walk, j); +} + +// Mini-only bridge: copy a target visit row into its interleaved four-tap block. +extern "C" __global__ void tf_ink2_mini_tap(const uint16_t* src, uint16_t* taps, int rows, int channel, int width) { + const int row = blockIdx.y, col = blockIdx.x * blockDim.x + threadIdx.x; + if (row < rows && col < width) taps[(static_cast(row) * 4 + channel) * width + col] = + src[static_cast(row) * width + col]; +} + +// Mini's hidden_out cannot use DSpark's vocabulary fold: its output goes through the target unembedding. +extern "C" __global__ void tf_ink2_mini_hidden(const uint16_t* y, long long ystride, + const uint16_t* latent, const uint16_t* w, + const uint16_t* bias, uint16_t* out, int width, int rank) { + const int stream = blockIdx.y; + for (int c = blockIdx.x * blockDim.x + threadIdx.x; c < width; c += gridDim.x * blockDim.x) { + float v = ink2d::bf(y[static_cast(stream) * ystride + c]) + ink2d::bf(bias[c]); + for (int r = 0; r < rank; ++r) + v += ink2d::bf(w[static_cast(c) * rank + r]) * + ink2d::bf(latent[static_cast(stream) * rank + r]); + out[static_cast(stream) * width + c] = ink2d::tobf(v); + } +} + +#include "inkling2/dspark_many.cuh" diff --git a/zig/kernels/cuda/inkling2/dspark_many.cuh b/zig/kernels/cuda/inkling2/dspark_many.cuh new file mode 100644 index 00000000000..87ccbd7f0cc --- /dev/null +++ b/zig/kernels/cuda/inkling2/dspark_many.cuh @@ -0,0 +1,308 @@ +// Inkling 2's DSpark drafter, every stream of a pass in one launch a step (Mini's batched pass; dspark_many.zig). +#pragma once + +// One stream of a batched pass (dspark_many.zig's Stream): its slot's caches by layer, f_rnn, anchor, keys, race. +struct DspStream { + uint16_t* kc[8]; + uint16_t* vc[8]; + const uint16_t* frnn; + unsigned long long seed; + int p, race; + float inv_t; + int lo[8]; + int pad; +}; + +namespace ink2m { + +__device__ __forceinline__ bool better(float v, int i, float bv, int bi) { return v > bv || (v == bv && i < bi); } + +// sample.cu's keys (as ops.cu's tf_ink2_race1) +__device__ __forceinline__ unsigned long long mix(unsigned long long x) { + x ^= x >> 30; + x *= 0xBF58476D1CE4E5B9ull; + x ^= x >> 27; + x *= 0x94D049BB133111EBull; + return x ^ (x >> 31); +} + +__device__ __forceinline__ float race_uniform(unsigned long long seed, unsigned pos, unsigned id) { + unsigned long long x = mix(seed + 0x9E3779B97F4A7C15ull); + x = mix(x ^ (static_cast(pos) * 0xD1B54A32D192ED03ull)); + x = mix(x ^ static_cast(id)); + const float u = (static_cast(static_cast(x >> 40)) + 0.5f) * (1.0f / 16777216.0f); + return fminf(u, __uint_as_float(0x3F7FFFFFu)); +} + +} // namespace ink2m + +// tf_ink2_dsp_qk over every stream's rows: row r is stream at[2r]'s position at[2r + 1], into that slot's caches. +extern "C" __global__ void __launch_bounds__(64) tf_ink2_dsp_qk_many(QkArgs a, const DspStream* __restrict__ st, + const int* __restrict__ at, int layer) { + using namespace ink2d; + __shared__ float sh[32]; + const int row = blockIdx.x, h = blockIdx.y, i = threadIdx.x; + const bool isq = h < a.hq; + const uint16_t* x = a.x + row * a.ld + static_cast(h) * kD; + const float x0 = bf(x[i]), x1 = bf(x[i + 64]); + const float inv = 1.0f / sqrtf(blockSum(x0 * x0 + x1 * x1, sh) / kD + a.eps); + const uint16_t* w = isq ? a.qw : a.kw; + const float y0 = bfr(x0 * inv * bf(w[i])), y1 = bfr(x1 * inv * bf(w[i + 64])); + const int pos = at[2 * row + 1]; + const float f = static_cast(pos) * (1.0f / powf(a.theta, static_cast(2 * i) / kD)); + const float co = cosf(f), si = sinf(f); + const uint16_t o0 = tobf(y0 * co - y1 * si), o1 = tobf(y1 * co + y0 * si); + if (isq) { + uint16_t* q = a.q + (static_cast(row) * a.hq + h) * kD; + q[i] = o0; + q[i + 64] = o1; + return; + } + const DspStream& s = st[at[2 * row]]; + uint16_t* kc = s.kc[layer]; + uint16_t* vc = s.vc[layer]; + const int j = h - a.hq; + const size_t o = (static_cast(pos % a.ring) * a.hk + j) * kD; + kc[o + i] = o0; + kc[o + i + 64] = o1; + const uint16_t* v = a.x + row * a.ld + static_cast(a.hq + a.hk + j) * kD; + vc[o + i] = v[i]; + vc[o + i + 64] = v[i + 64]; +} + +// tf_ink2_dsp_attn for every stream's block (blockIdx.z): its keys [lo, p + T - 1], partials maxc chunks apart. +extern "C" __global__ void __launch_bounds__(256) tf_ink2_dsp_attn_many(AttnArgs a, const DspStream* __restrict__ st, int layer, + int maxc) { + using namespace ink2d; + __shared__ float sq[kMaxQ][kD]; + __shared__ uint16_t sk[kKT][kD + 8]; + __shared__ uint16_t sv[kKT][kD]; + __shared__ float sp[kMaxQ][kKT]; + __shared__ float sm[kMaxQ], sl[kMaxQ], sa[kMaxQ]; + const DspStream& S = st[blockIdx.z]; + const int lo = S.lo[layer], hi = S.p + a.T - 1; + if (static_cast(blockIdx.x) > hi / kChunk - lo / kChunk) return; + const int j = blockIdx.y, c = lo / kChunk + blockIdx.x, tid = threadIdx.x; + const int g = a.hq / a.hk, nq = a.T * g, nqt = a.T * a.hq; + const uint16_t* aq = a.q + static_cast(blockIdx.z) * nqt * kD; + const uint16_t* kc = S.kc[layer]; + const uint16_t* vc = S.vc[layer]; + float* po = a.po + static_cast(blockIdx.z) * maxc * nqt * kD; + float* pml = a.pml + static_cast(blockIdx.z) * maxc * nqt * 2; + const int k0 = max(lo, c * kChunk), k1 = min(hi + 1, (c + 1) * kChunk); + for (int idx = tid; idx < nq * kD; idx += blockDim.x) { + const int qi = idx / kD, d = idx % kD; + sq[qi][d] = bf(aq[(static_cast(qi / g) * a.hq + j * g + qi % g) * kD + d]); + } + for (int qi = tid; qi < nq; qi += blockDim.x) { + sm[qi] = -INFINITY; + sl[qi] = 0.0f; + } + const int d = tid & (kD - 1), half = tid >> 7; + float o[kMaxQ / 2]; + for (int r = 0; r < kMaxQ / 2; ++r) o[r] = 0.0f; + __syncthreads(); + for (int kt = k0; kt < k1; kt += kKT) { + const int nk = min(kKT, k1 - kt); + for (int idx = tid; idx < nk * kD; idx += blockDim.x) { + const int kk = idx / kD, dd = idx % kD; + const size_t at = (static_cast((kt + kk) % a.ring) * a.hk + j) * kD + dd; + sk[kk][dd] = kc[at]; + sv[kk][dd] = vc[at]; + } + __syncthreads(); + for (int idx = tid; idx < nq * kKT; idx += blockDim.x) { + const int qi = idx / kKT, kk = idx % kKT; + float s = -INFINITY; + if (kk < nk) { + s = 0.0f; + for (int dd = 0; dd < kD; ++dd) s += sq[qi][dd] * bf(sk[kk][dd]); + s *= a.scale; + } + sp[qi][kk] = s; + } + __syncthreads(); + for (int qi = tid; qi < nq; qi += blockDim.x) { + float mx = sm[qi]; + for (int kk = 0; kk < nk; ++kk) mx = fmaxf(mx, sp[qi][kk]); + const float al = expf(sm[qi] - mx); + float sum = 0.0f; + for (int kk = 0; kk < nk; ++kk) { + const float p = expf(sp[qi][kk] - mx); + sp[qi][kk] = p; + sum += p; + } + sl[qi] = sl[qi] * al + sum; + sm[qi] = mx; + sa[qi] = al; + } + __syncthreads(); + for (int r = 0; r < kMaxQ / 2; ++r) { + const int qi = half * (kMaxQ / 2) + r; + if (qi >= nq) break; + float acc = o[r] * sa[qi]; + for (int kk = 0; kk < nk; ++kk) acc += sp[qi][kk] * bf(sv[kk][d]); + o[r] = acc; + } + __syncthreads(); + } + for (int r = 0; r < kMaxQ / 2; ++r) { + const int qi = half * (kMaxQ / 2) + r; + if (qi >= nq) break; + const size_t rh = static_cast(blockIdx.x) * nqt + (qi / g) * a.hq + j * g + qi % g; + po[rh * kD + d] = o[r]; + if (d == 0) { + pml[rh * 2] = sm[qi]; + pml[rh * 2 + 1] = sl[qi]; + } + } +} + +// tf_ink2_dsp_merge for every stream (blockIdx.y): its chunks folded in order into its block's rows of out. +extern "C" __global__ void __launch_bounds__(128) tf_ink2_dsp_merge_many(const float* __restrict__ po, const float* __restrict__ pml, + const DspStream* __restrict__ st, int layer, int T, + int maxc, int nqt, uint16_t* __restrict__ out) { + using namespace ink2d; + const DspStream& S = st[blockIdx.y]; + const int chunks = (S.p + T - 1) / kChunk - S.lo[layer] / kChunk + 1; + po += static_cast(blockIdx.y) * maxc * nqt * kD; + pml += static_cast(blockIdx.y) * maxc * nqt * 2; + out += static_cast(blockIdx.y) * nqt * kD; + const size_t rh = blockIdx.x; + const int d = threadIdx.x; + float mx = -INFINITY; + for (int c = 0; c < chunks; ++c) mx = fmaxf(mx, pml[(c * nqt + rh) * 2]); + float l = 0.0f, acc = 0.0f; + for (int c = 0; c < chunks; ++c) { + const float m = pml[(c * nqt + rh) * 2]; + const float wt = m == -INFINITY ? 0.0f : expf(m - mx); + l += pml[(c * nqt + rh) * 2 + 1] * wt; + acc += po[(c * nqt + rh) * kD + d] * wt; + } + out[rh * kD + d] = tobf(acc / l); +} + +// tf_ink2_dsp_ctx for every stream (blockIdx.y): its hidden rows hstride elements apart, its slot's f_rnn. +extern "C" __global__ void __launch_bounds__(256) tf_ink2_dsp_ctx_many(const uint16_t* __restrict__ hidden, long long hstride, + const DspStream* __restrict__ st, const uint16_t* __restrict__ W, + const uint16_t* __restrict__ bias, float* __restrict__ out, + int rows, int C, int R) { + using namespace ink2d; + const int o = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5), lane = threadIdx.x & 31; + if (o >= 3 * R) return; + hidden += blockIdx.y * hstride; + out += static_cast(blockIdx.y) * rows * 3 * R; + const uint16_t* frnn = st[blockIdx.y].frnn; + const uint16_t* w = W + static_cast(o) * (2 * R + 2 * C) + 2 * R; + float acc[kMaxRows]; + for (int r = 0; r < kMaxRows; ++r) acc[r] = 0.0f; + for (int k = lane; k < 2 * C; k += 32) { + const float wk = bf(w[k]); + if (k < C) { + for (int r = 0; r < kMaxRows; ++r) + if (r < rows) acc[r] += wk * bf(hidden[static_cast(r) * C + k]); + } else { + const float f = wk * bf(frnn[k - C]); + for (int r = 0; r < kMaxRows; ++r) acc[r] += f; + } + } + for (int r = 0; r < kMaxRows; ++r) { + const float s = tf_common::warp_sum(acc[r]); + if (lane == 0 && r < rows) out[static_cast(r) * 3 * R + o] = s + bf(bias[o]); + } +} + +// tf_ink2_dsp_rnn for every stream (a block each): ctx rows cstride apart, walks T apart, states and latents R apart. +extern "C" __global__ void __launch_bounds__(256) tf_ink2_dsp_rnn_many(const float* __restrict__ ctx, long long cstride, + const uint16_t* __restrict__ W, const uint16_t* __restrict__ w1, + const int* __restrict__ walk, int T, int j, + uint16_t* __restrict__ state, uint16_t* __restrict__ latent, + int R, int C) { + using namespace ink2d; + __shared__ float in[512]; + __shared__ float raw[768]; + const int c = threadIdx.x, lane = c & 31, wp = c >> 5, nw = blockDim.x >> 5; + ctx += blockIdx.x * cstride; + walk += blockIdx.x * T; + state += blockIdx.x * R; + latent += blockIdx.x * R; + const size_t prev = static_cast(walk[j]); + in[c] = bf(state[c]); + in[R + c] = bf(w1[prev * R + c]); + __syncthreads(); + const int ld = 2 * R + 2 * C; + for (int o = wp; o < 3 * R; o += nw) { + float s = 0.0f; + for (int k = lane; k < 2 * R; k += 32) s += bf(W[static_cast(o) * ld + k]) * in[k]; + s = tf_common::warp_sum(s); + if (lane == 0) raw[o] = s + ctx[o]; + } + __syncthreads(); + const float gate = bfr(1.0f / (1.0f + expf(-bfr(raw[c])))); + const float cand = bfr(tanhf(bfr(raw[R + c]))); + const float keep = bfr(gate * in[c]); + const float upd = bfr(bfr(1.0f - gate) * cand); + state[c] = tobf(keep + upd); + latent[c] = tobf(tanhf(bfr(raw[2 * R + c]))); +} + +// Each stream's step pick (a block each): greedy over nv columns or its keyed race over valid, into picks 16 B apart. +extern "C" __global__ void __launch_bounds__(1024) tf_ink2_dsp_pick_many(const float* __restrict__ scores, int nv, int valid, + int base, const DspStream* __restrict__ st, int step, + float* __restrict__ picks) { + using namespace ink2d; + using ink2m::better; + __shared__ float sv[32]; + __shared__ int si[32]; + const DspStream& S = st[blockIdx.x]; + const float* r = scores + static_cast(blockIdx.x) * nv; + float bv = -INFINITY; + int bi = 0x7fffffff; + if (S.race) { + const unsigned pos = static_cast(S.p + 1 + step); + for (int i = threadIdx.x; i < valid; i += blockDim.x) { + const float v = bfr(r[i]) * S.inv_t - logf(-logf(ink2m::race_uniform(S.seed, pos, static_cast(base + i)))); + if (better(v, i, bv, bi)) { + bv = v; + bi = i; + } + } + } else { + for (int i = threadIdx.x; i < nv; i += blockDim.x) { + if (better(r[i], i, bv, bi)) { + bv = r[i]; + bi = i; + } + } + } + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffffu, bv, o); + const int oi = __shfl_xor_sync(0xffffffffu, bi, o); + if (better(ov, oi, bv, bi)) { + bv = ov; + bi = oi; + } + } + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + if (lane == 0) { + sv[warp] = bv; + si[warp] = bi; + } + __syncthreads(); + if (warp != 0) return; + const int nw = blockDim.x >> 5; + bv = lane < nw ? sv[lane] : -INFINITY; + bi = lane < nw ? si[lane] : 0x7fffffff; + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffffu, bv, o); + const int oi = __shfl_xor_sync(0xffffffffu, bi, o); + if (better(ov, oi, bv, bi)) { + bv = ov; + bi = oi; + } + } + if (lane == 0) { + picks[blockIdx.x * 4] = bv; + reinterpret_cast(picks)[blockIdx.x * 4 + 1] = (bi == 0x7fffffff ? 0 : bi) + base; + } +} diff --git a/zig/kernels/cuda/minimax_m3.cu b/zig/kernels/cuda/minimax_m3.cu index 80ea6a67926..cbcc73c9278 100644 --- a/zig/kernels/cuda/minimax_m3.cu +++ b/zig/kernels/cuda/minimax_m3.cu @@ -1,6 +1,7 @@ // MiniMax-M3.1-Flash's glue on CUDA: the Metal family's glue.metal step for step (bf16 activations, fp32 sums). #include "minimax_m3.cuh" +#include "common/dspark_pick.cuh" namespace tf_mm3 { // The token ids' bf16 embeddings as the fp32 residual rows (bf16 values). @@ -358,18 +359,7 @@ extern "C" __global__ void __launch_bounds__(1024) tf_mm3_top1f(const float* __r // The ranks' gathered (value, id) picks to one, the best (the low id on a tie), into walk[j + 1] extern "C" __global__ void tf_mm3_pick_merge(const unsigned char* __restrict__ picks, int world, int stride, int* __restrict__ walk, int j) { - if (threadIdx.x != 0) return; - float best = -CUDART_INF_F; - int id = 0; - for (int q = 0; q < world; ++q) { - const float v = *reinterpret_cast(picks + (size_t)q * stride); - const int k = *reinterpret_cast(picks + (size_t)q * stride + 4); - if (v > best || (v == best && k < id)) { - best = v; - id = k; - } - } - walk[j + 1] = id; + tf_common::dspark_pick<0>(picks, world, stride, walk, j); } // fp32 pixels [P][K] . the fp32 conv weight [N][K]^T, each output one fma chain in k order, rounded to bf16 once diff --git a/zig/src/core/contract/inkling2_cuda_records.zig b/zig/src/core/contract/inkling2_cuda_records.zig index b24f4ea1efe..94426f828a6 100644 --- a/zig/src/core/contract/inkling2_cuda_records.zig +++ b/zig/src/core/contract/inkling2_cuda_records.zig @@ -1,8 +1,9 @@ //! Inkling 2's CUDA kernels: their compile records, one file per kernel group. const attn = @import("inkling2_attn_records.zig"); const ops = @import("inkling2_ops_records.zig"); +const dspark = @import("inkling2_dspark_records.zig"); const experts = @import("inkling2_experts_records.zig"); -pub const cuda = attn.cuda ++ ops.cuda ++ experts.cuda; -pub const cuda_132 = attn.cuda_132 ++ ops.cuda_132 ++ experts.cuda_132; -pub const cuda_133 = attn.cuda_133 ++ ops.cuda_133 ++ experts.cuda_133; +pub const cuda = attn.cuda ++ ops.cuda ++ dspark.cuda ++ experts.cuda; +pub const cuda_132 = attn.cuda_132 ++ ops.cuda_132 ++ dspark.cuda_132 ++ experts.cuda_132; +pub const cuda_133 = attn.cuda_133 ++ ops.cuda_133 ++ dspark.cuda_133 ++ experts.cuda_133; diff --git a/zig/src/core/contract/inkling2_dspark_records.zig b/zig/src/core/contract/inkling2_dspark_records.zig new file mode 100644 index 00000000000..123da2b1459 --- /dev/null +++ b/zig/src/core/contract/inkling2_dspark_records.zig @@ -0,0 +1,30 @@ +//! Inkling 2's DSpark drafter launches: every SM's compile records (nvcc 13.0, 13.2, 13.3). +const registry = @import("registry.zig"); + +/// nvcc 13.0's usage (nvcc -cubin, five SMs, the glue flags); 13.2 pending, 13.3 in measurements/pending_133.zig. +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_mix", .symbol = "tf_ink2_dsp_mix", .image = "inkling2_dspark", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 128, .bound = 512 }, .{ .regs = 40, .static = 128, .bound = 512 }, .{ .regs = 40, .static = 128, .bound = 512 }, .{ .regs = 40, .static = 128, .bound = 512 }, .{ .regs = 40, .static = 128, .bound = 512 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_addnorm", .symbol = "tf_ink2_dsp_addnorm", .image = "inkling2_dspark", .threads = 512, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 128, .bound = 512 }, .{ .regs = 40, .static = 128, .bound = 512 }, .{ .regs = 40, .static = 128, .bound = 512 }, .{ .regs = 40, .static = 128, .bound = 512 }, .{ .regs = 40, .static = 128, .bound = 512 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_qk", .symbol = "tf_ink2_dsp_qk", .image = "inkling2_dspark", .threads = 64, .min_sm = 80 }, .usage = .{ .{ .regs = 28, .static = 128, .bound = 64 }, .{ .regs = 28, .static = 128, .bound = 64 }, .{ .regs = 28, .static = 128, .bound = 64 }, .{ .regs = 24, .static = 128, .bound = 64 }, .{ .regs = 26, .static = 128, .bound = 64 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_attn", .symbol = "tf_ink2_dsp_attn", .image = "inkling2_dspark", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 67, .static = 48192, .bound = 256 }, .{ .regs = 69, .static = 48192, .bound = 256 }, .{ .regs = 69, .static = 48192, .bound = 256 }, .{ .regs = 46, .static = 48192, .bound = 256 }, .{ .regs = 46, .static = 48192, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_merge", .symbol = "tf_ink2_dsp_merge", .image = "inkling2_dspark", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 39, .static = 0, .bound = 128 }, .{ .regs = 39, .static = 0, .bound = 128 }, .{ .regs = 33, .static = 0, .bound = 128 }, .{ .regs = 33, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "act_rows tf_swiglu_rows_expf (Inkling 2 DSpark)", .symbol = "tf_swiglu_rows_expf", .image = "act_rows", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 33, .static = 0, .bound = 256 }, .{ .regs = 33, .static = 0, .bound = 256 }, .{ .regs = 33, .static = 0, .bound = 256 }, .{ .regs = 33, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_ctx", .symbol = "tf_ink2_dsp_ctx", .image = "inkling2_dspark", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 47, .static = 0, .bound = 256 }, .{ .regs = 47, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_rnn", .symbol = "tf_ink2_dsp_rnn", .image = "inkling2_dspark", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 5120, .bound = 256 }, .{ .regs = 39, .static = 5120, .bound = 256 }, .{ .regs = 39, .static = 5120, .bound = 256 }, .{ .regs = 40, .static = 5120, .bound = 256 }, .{ .regs = 40, .static = 5120, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_vocab", .symbol = "tf_ink2_dsp_vocab", .image = "inkling2_dspark", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 21, .static = 0, .bound = 256 }, .{ .regs = 22, .static = 0, .bound = 256 }, .{ .regs = 22, .static = 0, .bound = 256 }, .{ .regs = 15, .static = 0, .bound = 256 }, .{ .regs = 15, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_pick_merge", .symbol = "tf_ink2_dsp_pick_merge", .image = "inkling2_dspark", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_qk_many", .symbol = "tf_ink2_dsp_qk_many", .image = "inkling2_dspark", .threads = 64, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 128, .bound = 64 }, .{ .regs = 30, .static = 128, .bound = 64 }, .{ .regs = 30, .static = 128, .bound = 64 }, .{ .regs = 32, .static = 128, .bound = 64 }, .{ .regs = 34, .static = 128, .bound = 64 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_attn_many", .symbol = "tf_ink2_dsp_attn_many", .image = "inkling2_dspark", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 75, .static = 48192, .bound = 256 }, .{ .regs = 76, .static = 48192, .bound = 256 }, .{ .regs = 76, .static = 48192, .bound = 256 }, .{ .regs = 57, .static = 48192, .bound = 256 }, .{ .regs = 57, .static = 48192, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_merge_many", .symbol = "tf_ink2_dsp_merge_many", .image = "inkling2_dspark", .threads = 128, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 36, .static = 0, .bound = 128 }, .{ .regs = 36, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_ctx_many", .symbol = "tf_ink2_dsp_ctx_many", .image = "inkling2_dspark", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 48, .static = 0, .bound = 256 }, .{ .regs = 48, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_rnn_many", .symbol = "tf_ink2_dsp_rnn_many", .image = "inkling2_dspark", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 39, .static = 5120, .bound = 256 }, .{ .regs = 39, .static = 5120, .bound = 256 }, .{ .regs = 39, .static = 5120, .bound = 256 }, .{ .regs = 40, .static = 5120, .bound = 256 }, .{ .regs = 40, .static = 5120, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_pick_many", .symbol = "tf_ink2_dsp_pick_many", .image = "inkling2_dspark", .threads = 1024, .min_sm = 80 }, .usage = .{ .{ .regs = 23, .static = 256, .bound = 1024 }, .{ .regs = 24, .static = 256, .bound = 1024 }, .{ .regs = 24, .static = 256, .bound = 1024 }, .{ .regs = 25, .static = 256, .bound = 1024 }, .{ .regs = 25, .static = 256, .bound = 1024 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_vocab_rows", .symbol = "tf_ink2_dsp_vocab_rows", .image = "inkling2_dspark", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 33, .static = 0, .bound = 256 }, .{ .regs = 33, .static = 0, .bound = 256 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_dsp_pick_rows", .symbol = "tf_ink2_dsp_pick_rows", .image = "inkling2_dspark", .threads = 32, .min_sm = 80 }, .usage = .{ .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_mini_tap", .symbol = "tf_ink2_mini_tap", .image = "inkling2_dspark", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 }, .{ .regs = 12, .static = 0, .bound = 0 } }, .later_pending = true }, + .{ .launch = .{ .name = "inkling2 dspark tf_ink2_mini_hidden", .symbol = "tf_ink2_mini_hidden", .image = "inkling2_dspark", .threads = 256, .min_sm = 80 }, .usage = .{ .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 31, .static = 0, .bound = 0 }, .{ .regs = 31, .static = 0, .bound = 0 } }, .later_pending = true }, +}; +/// nvcc 13.2's, where it differs: none measured (no 13.2 compiler), so later_pending keeps every launch pending. +pub const cuda_132 = [_]registry.Override{}; +/// nvcc 13.3's: none here, as later_pending reads 13.3 from measurements/pending_133.zig. +pub const cuda_133 = [_]registry.Override{}; diff --git a/zig/src/core/contract/measurements/pending_133.zig b/zig/src/core/contract/measurements/pending_133.zig index 56af8cdf40d..bcddadf491b 100644 --- a/zig/src/core/contract/measurements/pending_133.zig +++ b/zig/src/core/contract/measurements/pending_133.zig @@ -83,4 +83,12 @@ pub const records = [_]Override{ .{ .name = "ricursive_prep tf_rc_prep_rows", .usage = .{ .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 } } }, .{ .name = "window attention wattn_kernel<128, 8, 2, 8>", .usage = .{ .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 218, .static = 0, .bound = 256 }, .{ .regs = 218, .static = 0, .bound = 256 } } }, .{ .name = "window attention tf_window_prompt_h2_pg", .usage = .{ .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 222, .static = 0, .bound = 256 }, .{ .regs = 231, .static = 0, .bound = 256 }, .{ .regs = 231, .static = 0, .bound = 256 } } }, + .{ .name = "inkling2 dspark tf_ink2_dsp_qk_many", .usage = .{ .{ .regs = 32, .static = 128, .bound = 64 }, .{ .regs = 30, .static = 128, .bound = 64 }, .{ .regs = 30, .static = 128, .bound = 64 }, .{ .regs = 32, .static = 128, .bound = 64 }, .{ .regs = 32, .static = 128, .bound = 64 } } }, + .{ .name = "inkling2 dspark tf_ink2_dsp_attn_many", .usage = .{ .{ .regs = 75, .static = 48192, .bound = 256 }, .{ .regs = 76, .static = 48192, .bound = 256 }, .{ .regs = 76, .static = 48192, .bound = 256 }, .{ .regs = 58, .static = 48192, .bound = 256 }, .{ .regs = 58, .static = 48192, .bound = 256 } } }, + .{ .name = "inkling2 dspark tf_ink2_dsp_merge_many", .usage = .{ .{ .regs = 32, .static = 0, .bound = 128 }, .{ .regs = 36, .static = 0, .bound = 128 }, .{ .regs = 36, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 }, .{ .regs = 40, .static = 0, .bound = 128 } } }, + .{ .name = "inkling2 dspark tf_ink2_dsp_ctx_many", .usage = .{ .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 40, .static = 0, .bound = 256 }, .{ .regs = 48, .static = 0, .bound = 256 }, .{ .regs = 48, .static = 0, .bound = 256 } } }, + .{ .name = "inkling2 dspark tf_ink2_dsp_rnn_many", .usage = .{ .{ .regs = 39, .static = 5120, .bound = 256 }, .{ .regs = 39, .static = 5120, .bound = 256 }, .{ .regs = 39, .static = 5120, .bound = 256 }, .{ .regs = 39, .static = 5120, .bound = 256 }, .{ .regs = 39, .static = 5120, .bound = 256 } } }, + .{ .name = "inkling2 dspark tf_ink2_dsp_pick_many", .usage = .{ .{ .regs = 23, .static = 256, .bound = 1024 }, .{ .regs = 24, .static = 256, .bound = 1024 }, .{ .regs = 24, .static = 256, .bound = 1024 }, .{ .regs = 25, .static = 256, .bound = 1024 }, .{ .regs = 25, .static = 256, .bound = 1024 } } }, + .{ .name = "inkling2 dspark tf_ink2_dsp_vocab_rows", .usage = .{ .{ .regs = 32, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 33, .static = 0, .bound = 256 }, .{ .regs = 33, .static = 0, .bound = 256 } } }, + .{ .name = "inkling2 dspark tf_ink2_dsp_pick_rows", .usage = .{ .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 22, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 } } }, }; diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index e90fda57074..240431c1c1c 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -117,6 +117,7 @@ pub const inkling2_attn: []const u8 = if (available) &Blob("fatbin_inkling2_attn pub const inkling2_pattn: []const u8 = if (available) &Blob("fatbin_inkling2_pattn").bytes else &.{}; pub const inkling2_ops: []const u8 = if (available) &Blob("fatbin_inkling2_ops").bytes else &.{}; pub const inkling2_rows: []const u8 = if (available) &Blob("fatbin_inkling2_rows").bytes else &.{}; +pub const inkling2_dspark: []const u8 = if (available) &Blob("fatbin_inkling2_dspark").bytes else &.{}; pub const ricursive: []const u8 = if (available) &Blob("fatbin_ricursive").bytes else &.{}; pub const ricursive_prep: []const u8 = if (available) &Blob("fatbin_ricursive_prep").bytes else &.{}; pub const inkling2_experts: []const u8 = if (available) &Blob("fatbin_inkling2_experts").bytes else &.{}; diff --git a/zig/src/families/inkling2/cuda_dspark.zig b/zig/src/families/inkling2/cuda_dspark.zig new file mode 100644 index 00000000000..c2bc706e58f --- /dev/null +++ b/zig/src/families/inkling2/cuda_dspark.zig @@ -0,0 +1,177 @@ +//! CUDA DSpark adapter: committed target taps into per-stream speculative heads. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const dspark = @import("dspark.zig"); +const engine = @import("loop_engine.zig"); + +const dr = lanes.drafter; +const Stream = lanes.Stream; +const prior = [_]f64{ 0.55, 0.45, 0.35 }; + +const Entry = struct { + context: dspark.Context, + held: [dspark.depth]u32 = undefined, + count: usize = 0, +}; + +pub const Drafter = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + s: cuda.Stream, + kernels: *engine.Kernels, + context: u32, + lane: cuda.qmmf.Lane, + weights: dspark.Weights, + head: dspark.Head, + entries: std.AutoHashMapUnmanaged(*Stream, *Entry) = .empty, + + pub fn init(gpa: std.mem.Allocator, io: std.Io, target: *engine.Model, kernels: *engine.Kernels, s: cuda.Stream, target_dir: []const u8, dir: []const u8) !*Drafter { + const out = try gpa.create(Drafter); + errdefer gpa.destroy(out); + const mtp = target.w.c.mtp orelse return error.DSparkNotConfigured; + if (mtp.layers != 3 or mtp.q_heads != 24 or mtp.kv_heads != 8 or mtp.head_dim != 128 or + mtp.inter != dspark.inter or mtp.window != 1024 or mtp.block != dspark.rows or + mtp.rank != dspark.rank or mtp.rope_theta != 1e6 or mtp.taps_n != dspark.taps.len or + !std.mem.eql(u32, mtp.taps[0..mtp.taps_n], &dspark.taps) or + !mtp.local[0] or mtp.local[1] or !mtp.local[2]) + return error.UnsupportedDSparkConfig; + const d = target.d; + var weights = try dspark.load(gpa, io, d, target_dir, dir, target.w.c.text.vocab, target.w.c.text.unpadded_vocab); + errdefer weights.deinit(gpa); + var lane = try cuda.qmmf.Lane.load(d, (try d.currentCapability()) / 10); + errdefer lane.unload(); + const head = try dspark.Head.init(gpa, d, &weights, &kernels.draft.?, &kernels.glue, .{ .w = target.w, .lane = &lane, .unembed = weights.unembed }, target.context); + out.* = .{ + .gpa = gpa, + .kernels = kernels, + .d = d, + .s = s, + .context = @intCast(target.context), + .lane = lane, + .weights = weights, + .head = head, + }; + // A Head points at the owners, not the temporary values from load. + out.head.w = &out.weights; + out.head.t.lane = &out.lane; + return out; + } + + pub fn deinit(out: *Drafter) void { + out.s.synchronize() catch {}; + var it = out.entries.valueIterator(); + while (it.next()) |entry| { + entry.*.context.deinit(); + out.gpa.destroy(entry.*); + } + out.entries.deinit(out.gpa); + out.head.deinit(out.gpa); + out.lane.unload(); + out.weights.deinit(out.gpa); + out.gpa.destroy(out); + } + + pub fn reserve(_: *Drafter, streams: u32) !void { + if (streams > engine.max_slots) return error.Inkling2TooManyStreams; + } + + pub fn drafter(out: *Drafter) dr.Drafter { + return .{ .kind = "DSpark", .ptr = out, .vtable = &.{ + .taps = tapsFn, + .facts = factsFn, + .open = openFn, + .absorb = absorbFn, + .hold = holdFn, + .held = heldFn, + .release = releaseFn, + } }; + } + + fn cast(ptr: *anyopaque) *Drafter { + return @ptrCast(@alignCast(ptr)); + } + + fn tapsFn(_: *anyopaque) []const u32 { + return &dspark.taps; + } + + fn factsFn(ptr: *anyopaque) dr.Facts { + const out = cast(ptr); + return .{ + .depth = 2, // longer shared verification windows spend more target work on rejected proposals + .step_ms = 0, + .prior = &prior, + .plain_guard = false, + .fixed_block = true, + .batched = true, + .stream_bytes = 2 * (@as(usize, 2 * dspark.local_ring) + out.context) * dspark.kv * 2 + dspark.hidden * 2, + }; + } + + fn openFn(ptr: *anyopaque, stream: *Stream) anyerror!void { + const out = cast(ptr); + if (out.entries.contains(stream)) return error.DSparkStreamAlreadyOpen; + if (out.entries.count() >= engine.max_slots) return error.Inkling2TooManyStreams; + const entry = try out.gpa.create(Entry); + errdefer out.gpa.destroy(entry); + entry.* = .{ .context = try dspark.Context.init(out.d, out.context) }; + errdefer entry.context.deinit(); + try out.entries.put(out.gpa, stream, entry); + } + + fn releaseFn(ptr: *anyopaque, stream: *Stream) void { + const out = cast(ptr); + if (out.entries.fetchRemove(stream)) |owned| { + out.s.synchronize() catch {}; + owned.value.context.deinit(); + out.gpa.destroy(owned.value); + } + } + + fn absorbFn(ptr: *anyopaque, items: []const dr.Absorb) anyerror!void { + const out = cast(ptr); + for (items) |item| { + const entry = out.entries.get(item.stream) orelse return error.DraftStreamUnknown; + const f = item.features; + if (item.rows != null or f.ready != .none or f.space != .device or f.dtype != .bf16 or + f.row_bytes != dspark.taps.len * dspark.hidden * 2 or f.rows == 0 or f.rows != item.follow.len) + return error.DraftFeaturesUnsupported; + try out.head.absorb(out.s, &entry.context, f.buffer + f.offset, item.start, f.rows); + entry.count = 0; + } + } + + fn holdFn(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { + const out = cast(ptr); + if (items.len == 0 or items.len > engine.max_slots) return error.DSparkHoldGeometry; + var contexts: [engine.max_slots]*dspark.Context = undefined; + var pending: [engine.max_slots]u32 = undefined; + var max_depth: usize = 0; + for (items, 0..) |item, i| { + const entry = out.entries.get(item.stream) orelse return error.DraftStreamUnknown; + if (item.lanes != null or item.depth == 0 or item.depth > dspark.depth or + item.position != entry.context.end + 1) return error.DSparkHoldGeometry; + contexts[i] = &entry.context; + pending[i] = item.pending; + max_depth = @max(max_depth, item.depth); + } + var picks: [engine.max_slots * dspark.rows]u32 = undefined; + try out.head.draftMany(out.s, contexts[0..items.len], pending[0..items.len], max_depth, picks[0 .. items.len * dspark.rows]); + for (items, 0..) |item, i| { + const entry = out.entries.get(item.stream).?; + @memcpy(entry.held[0..item.depth], picks[i * dspark.rows + 1 ..][0..item.depth]); + entry.count = item.depth; + } + } + + fn heldFn(ptr: *anyopaque, streams: []const *Stream, destinations: []const []u32) anyerror!void { + const out = cast(ptr); + if (streams.len != destinations.len) return error.DraftHeldCount; + for (streams, destinations) |stream, dest| { + const entry = out.entries.get(stream) orelse return error.DraftStreamUnknown; + if (dest.len > entry.count) return error.DraftHeldFewer; + @memcpy(dest, entry.held[0..dest.len]); + } + } +}; diff --git a/zig/src/families/inkling2/cuda_native.zig b/zig/src/families/inkling2/cuda_native.zig index 882170e2b63..98461b312d5 100644 --- a/zig/src/families/inkling2/cuda_native.zig +++ b/zig/src/families/inkling2/cuda_native.zig @@ -8,6 +8,8 @@ const plan_ = @import("plan.zig"); const loop = @import("loop.zig"); const engine = @import("loop_engine.zig"); const backend = @import("loop_backend.zig"); +const dspark = @import("dspark.zig"); +const cuda_dspark = @import("cuda_dspark.zig"); pub const model_type = "inkling2_loop"; pub const formats: []const []const u8 = &.{"modelopt-mixed"}; @@ -16,6 +18,7 @@ pub const max_segments: u32 = 1; pub const prompt_rows: u32 = engine.prompt_rows; pub const window_rows: u32 = engine.window_rows; pub const explains_open = true; +pub const takes_drafter = true; pub const VisionOptions = struct { image_tokens: u32, max_images: u32 }; pub const Room = struct { ctx: *anyopaque, read: *const fn (*anyopaque) ?u64 }; @@ -36,6 +39,7 @@ pub const Options = struct { pub const Owned = struct { gpa: std.mem.Allocator, + dir: []u8, admission: loop.Admission, kernels: engine.Kernels, stream: cuda.Stream, @@ -63,6 +67,7 @@ fn own(ptr: *anyopaque) *Owned { fn release(p: *anyopaque) void { const o = own(p); o.stream.synchronize() catch {}; + o.gpa.free(o.dir); o.backend.deinit(); o.stream.deinit(); o.model.deinit(); @@ -86,7 +91,6 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ if (kernels != null) return error.Inkling2CapturedKernels; if (o.segments != 1 or o.tp != 1 or o.rank != 0) return error.Inkling2LoopOneRankOnly; if (o.vision != null) return error.Inkling2LoopTextOnly; - if (o.drafter != null) return error.Inkling2DSparkPending; const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); defer gpa.free(path); const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)); @@ -123,7 +127,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ errdefer be.deinit(); const out = try gpa.create(Owned); errdefer gpa.destroy(out); - out.* = .{ .gpa = gpa, .admission = .{ .context = @intCast(o.context) }, .kernels = k, .stream = stream, .weights = w, .model = m, .backend = be }; + out.* = .{ .gpa = gpa, .dir = try gpa.dupe(u8, dir), .admission = .{ .context = @intCast(o.context) }, .kernels = k, .stream = stream, .weights = w, .model = m, .backend = be }; // The value copies above own pointers to their old stack homes; retarget the live model/backend now. out.model.w = &out.weights; out.backend.m = &out.model; @@ -131,6 +135,38 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ return .{ .backend = out.backend.backend(), .facts = out.backend.facts(), .rows = window_rows, .stream_bytes = backend.streamBytes(&out.model), .ctx = out, .deinit = release, .target = out }; } +pub const OpenedDrafter = struct { + drafter: lanes.drafter.Drafter, + ctx: *anyopaque, + close: *const fn (*anyopaque) void, + reserve: *const fn (*anyopaque, u32) anyerror!void, +}; + +fn closeDrafter(ptr: *anyopaque) void { + const d: *cuda_dspark.Drafter = @ptrCast(@alignCast(ptr)); + const kernels = d.kernels; + d.deinit(); + kernels.draft.?.unload(); + kernels.draft = null; +} + +fn reserveDrafter(ptr: *anyopaque, streams: u32) anyerror!void { + const d: *cuda_dspark.Drafter = @ptrCast(@alignCast(ptr)); + return d.reserve(streams); +} + +pub fn openDrafter(gpa: std.mem.Allocator, io: std.Io, ptr: *anyopaque, dir: []const u8, _: u8) !OpenedDrafter { + const o = own(ptr); + if (o.kernels.draft != null) return error.DSparkAlreadyAttached; + o.kernels.draft = try dspark.Kernels.load(o.model.d); + errdefer { + o.kernels.draft.?.unload(); + o.kernels.draft = null; + } + const d = try cuda_dspark.Drafter.init(gpa, io, &o.model, &o.kernels, o.stream, o.dir, dir); + return .{ .drafter = d.drafter(), .ctx = d, .close = closeDrafter, .reserve = reserveDrafter }; +} + pub fn snap_bytes(ptr: *anyopaque, at: u32) u64 { return own(ptr).model.snapshotBytes(at); } @@ -151,7 +187,7 @@ pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { return switch (err) { error.Inkling2LoopOneRankOnly => "Inkling 2 Mini runs at one CUDA rank with one segment; TP and multi-segment modes are refused", error.Inkling2LoopTextOnly => "Inkling 2 Mini is text-only on CUDA: images and --vision are refused", - error.Inkling2DSparkPending => "the Mini DSpark drafter has names and taps but no native draft engine in this build", + error.UnsupportedInkling2Taps => "the DSpark checkpoint needs Mini's four visit taps in checkpoint order", error.Inkling2CapturedKernels => "Inkling 2 Mini runs the engine's own kernels: unset TENSORFOLD_CUDA_KERNELS", error.Inkling2TooManyStreams => "Inkling 2 Mini on CUDA holds at most 16 streams: lower --parallel", error.StructuresUnsupported, error.ChainsOnly => "Inkling 2 Mini serves only unconstrained, non-branching text drafts", @@ -163,7 +199,7 @@ test "Mini native registration and refusal wording are explicit" { try std.testing.expectEqualStrings("inkling2_loop", model_type); try std.testing.expect(max_segments == 1 and prompt_rows == 2048 and window_rows == 16); try std.testing.expectEqual(16, engine.max_slots); // the stream cap explain() names - for ([_]anyerror{ error.Inkling2LoopOneRankOnly, error.Inkling2LoopTextOnly, error.Inkling2DSparkPending, error.Inkling2CapturedKernels, error.Inkling2TooManyStreams }) |err| { + for ([_]anyerror{ error.Inkling2LoopOneRankOnly, error.Inkling2LoopTextOnly, error.Inkling2CapturedKernels, error.Inkling2TooManyStreams }) |err| { try std.testing.expect(explain(null, err) != null); } } diff --git a/zig/src/families/inkling2/dspark.zig b/zig/src/families/inkling2/dspark.zig new file mode 100644 index 00000000000..bc2b3c02afd --- /dev/null +++ b/zig/src/families/inkling2/dspark.zig @@ -0,0 +1,260 @@ +//! Inkling 2 Mini DSpark checkpoint weights and committed per-stream caches. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const wts = @import("loop_weights.zig"); + +const DeviceBuffer = cuda.DeviceBuffer; +const Lane = cuda.qmmf.Weight; + +pub const hidden = 2304; +pub const query = 3072; +pub const kv = 1024; +pub const inter = 9216; +pub const rank = 256; +pub const markov_vocab = 201024; +/// The block's rows: the pending token, then seven masks; each mask row drafts one step. +pub const rows = 8; +pub const depth = rows - 1; +/// Context rows one absorb launch set takes. +pub const absorb_rows = 64; +pub const taps = [_]u32{ 5, 23, 41, 48 }; +/// The local rings retain the last 1,024 committed keys plus eight transient draft keys. +pub const local_ring = 1024 + rows; + +pub const Proj = struct { qkv: Lane, ctx_kv: Lane, o: Lane, gu: Lane, down: Lane }; +const Norms = struct { input: u64, post: u64, q: u64, k: u64, k_ctx: u64 }; + +pub const Weights = struct { + proj: [3]Proj, + norms: [3]Norms, + alpha: u64, // fp32 softmax of the checkpoint's four rows of fuse_weight + dflare: u64, // bf16 [4][H]: the layers' then the Markov head's + mask: u64, + norm: u64, + hidden_w: u64, // bf16 [H][R] + hidden_b: u64, + markov: u64, // bf16 [201024][R] + rnn: u64, // bf16 [768][5120] + rnn_b: u64, + unembed: Lane, // packed BF16 copy of the target's output table + buffers: std.ArrayList(DeviceBuffer) = .empty, + + pub fn deinit(w: *Weights, gpa: std.mem.Allocator) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(gpa); + } +}; + +const Loader = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + ck: *core.checkpoint.Checkpoint, + w: *Weights, + + fn tensor(l: Loader, name: []const u8, dims: []const usize) !core.checkpoint.Tensor { + const t = l.ck.get(name) catch |e| { + std.log.err("inkling2 dspark: mtp.safetensors has no {s}", .{name}); + return e; + }; + if (t.dtype != .bf16 or t.rank != dims.len) return error.DSparkTensorShape; + for (dims, 0..) |n, i| if (t.dim(i) != n) return error.DSparkTensorShape; + return t; + } + + fn upload(l: Loader, bytes: []const u8) !u64 { + var b = try DeviceBuffer.fromHost(l.d, bytes); + errdefer b.free(); + try l.w.buffers.append(l.gpa, b); + return b.ptr; + } + + fn raw(l: Loader, name: []const u8, dims: []const usize) !u64 { + return l.upload((try l.tensor(name, dims)).bytes); + } + + const Piece = struct { suffix: []const u8, rows: usize }; + + /// Join checkpoint projections before packing so the drafter projects all streams in one GEMM. + fn joined(l: Loader, layer: usize, pieces: []const Piece, k: usize) !Lane { + var n: usize = 0; + for (pieces) |piece| n += piece.rows; + const src = try l.gpa.alloc(u16, n * k); + defer l.gpa.free(src); + var at: usize = 0; + for (pieces) |piece| { + var name: [96]u8 = undefined; + const key = try std.fmt.bufPrint(&name, "layers.{d}.{s}", .{ layer, piece.suffix }); + const t = try l.tensor(key, &.{ piece.rows, k }); + @memcpy(std.mem.sliceAsBytes(src[at..][0 .. piece.rows * k]), t.bytes); + at += piece.rows * k; + } + const dest = try l.gpa.alloc(u16, cuda.modelopt.padded(n) * k); + defer l.gpa.free(dest); + cuda.qmmf.packBf16(dest, src, n, k); + return cuda.modelopt.bf16Weight(try l.upload(std.mem.sliceAsBytes(dest)), n, k); + } +}; + +/// Load mtp.safetensors and a packed target unembedding for the shared BF16 matmul lane. +pub fn load(gpa: std.mem.Allocator, io: std.Io, d: *const cuda.Driver, target_dir: []const u8, dir: []const u8, vocab: usize, valid: usize) !Weights { + var ck: core.checkpoint.Checkpoint = .{ .gpa = gpa, .io = io }; + defer ck.close(); + ck.add(dir, "mtp.safetensors") catch |e| { + std.log.err("inkling2 dspark: no mtp.safetensors in {s}", .{dir}); + return e; + }; + var w: Weights = undefined; + w.buffers = .empty; + errdefer w.deinit(gpa); + const l: Loader = .{ .gpa = gpa, .d = d, .ck = &ck, .w = &w }; + var dflare: [4 * hidden]u16 = undefined; + for (0..3) |i| { + var b: [96]u8 = undefined; + const n = struct { + fn at(buf: []u8, layer: usize, s: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, "layers.{d}.{s}", .{ layer, s }); + } + }.at; + w.proj[i] = .{ + .qkv = try l.joined(i, &.{ + .{ .suffix = "self_attn.q_proj.weight", .rows = query }, + .{ .suffix = "self_attn.k_proj.weight", .rows = kv }, + .{ .suffix = "self_attn.v_proj.weight", .rows = kv }, + }, hidden), + .ctx_kv = try l.joined(i, &.{ + .{ .suffix = "self_attn.k_proj_ctx.weight", .rows = kv }, + .{ .suffix = "self_attn.v_proj_ctx.weight", .rows = kv }, + }, hidden), + .o = try l.joined(i, &.{.{ .suffix = "self_attn.o_proj.weight", .rows = hidden }}, query), + .gu = try l.joined(i, &.{ + .{ .suffix = "mlp.gate_proj.weight", .rows = inter }, + .{ .suffix = "mlp.up_proj.weight", .rows = inter }, + }, hidden), + .down = try l.joined(i, &.{.{ .suffix = "mlp.down_proj.weight", .rows = hidden }}, inter), + }; + w.norms[i] = .{ + .input = try l.raw(try n(&b, i, "input_layernorm.weight"), &.{hidden}), + .post = try l.raw(try n(&b, i, "post_attention_layernorm.weight"), &.{hidden}), + .q = try l.raw(try n(&b, i, "self_attn.q_norm.weight"), &.{128}), + .k = try l.raw(try n(&b, i, "self_attn.k_norm.weight"), &.{128}), + .k_ctx = try l.raw(try n(&b, i, "self_attn.k_norm_ctx.weight"), &.{128}), + }; + @memcpy(std.mem.sliceAsBytes(dflare[i * hidden ..][0..hidden]), (try l.tensor(try n(&b, i, "dflare_norm.weight"), &.{hidden})).bytes); + } + @memcpy(std.mem.sliceAsBytes(dflare[3 * hidden ..]), (try l.tensor("markov_head.dflare_norm.weight", &.{hidden})).bytes); + w.dflare = try l.upload(std.mem.sliceAsBytes(&dflare)); + const fuse = try l.tensor("fuse_weight", &.{ 4, 4 }); + const fuse_src: [*]align(1) const u16 = @ptrCast(fuse.bytes.ptr); + var alpha: [16]f32 = undefined; + for (0..4) |f| { + var peak: f32 = -std.math.inf(f32); + for (0..4) |j| { + const v: f32 = @bitCast(@as(u32, fuse_src[f * 4 + j]) << 16); + peak = @max(peak, v); + alpha[f * 4 + j] = v; + } + var sum: f32 = 0; + for (0..4) |j| { + alpha[f * 4 + j] = @exp(alpha[f * 4 + j] - peak); + sum += alpha[f * 4 + j]; + } + for (0..4) |j| alpha[f * 4 + j] /= sum; + } + w.alpha = try l.upload(std.mem.sliceAsBytes(&alpha)); + w.mask = try l.raw("mask_embed", &.{hidden}); + w.norm = try l.raw("norm.weight", &.{hidden}); + w.hidden_w = try l.raw("markov_head.hidden_out.weight", &.{ hidden, rank }); + w.hidden_b = try l.raw("markov_head.hidden_out.bias", &.{hidden}); + w.markov = try l.raw("markov_head.markov_w1.weight", &.{ markov_vocab, rank }); + w.rnn = try l.raw("markov_head.rnn_proj.weight", &.{ 3 * rank, 2 * hidden + 2 * rank }); + w.rnn_b = try l.raw("markov_head.rnn_proj.bias", &.{3 * rank}); + var target = try core.Checkpoint.openModelPrefixes(gpa, io, target_dir, &.{"model.llm.unembed.weight"}); + defer target.close(); + const source = try target.expect("model.llm.unembed.weight", .bf16, &.{ vocab, hidden }); + if (valid == 0 or valid > vocab) return error.UnsupportedDSparkVocab; + var aligned: ?[]u16 = null; + defer if (aligned) |buf| gpa.free(buf); + const src: []const u16 = if (@intFromPtr(source.bytes.ptr) % @alignOf(u16) == 0) + @as([*]const u16, @ptrCast(@alignCast(source.bytes.ptr)))[0 .. valid * hidden] + else blk: { + const buf = try gpa.alloc(u16, valid * hidden); + @memcpy(std.mem.sliceAsBytes(buf), source.bytes[0 .. valid * hidden * 2]); + aligned = buf; + break :blk buf; + }; + const table = try gpa.alloc(u16, cuda.modelopt.padded(valid) * hidden); + defer gpa.free(table); + cuda.qmmf.packBf16(table, src, valid, hidden); + w.unembed = cuda.modelopt.bf16Weight(try l.upload(std.mem.sliceAsBytes(table)), valid, hidden); + return w; +} + +pub const Kernels = @import("dspark_ops.zig").Kernels; + +/// One stream's committed context: each layer's K/V ring, the newest fused Markov feature, and its span. +pub const Context = struct { + k: [3]DeviceBuffer, + v: [3]DeviceBuffer, + rings: [3]u32, + newest: DeviceBuffer, + from: u64 = 0, + end: u64 = 0, + + /// `capacity`: the global layer's longest context. + pub fn init(d: *const cuda.Driver, capacity: u32) !Context { + var c: Context = .{ .k = undefined, .v = undefined, .rings = .{ local_ring, capacity, local_ring }, .newest = undefined }; + var made: usize = 0; + errdefer for (0..made) |i| { + c.k[i].free(); + c.v[i].free(); + }; + for (c.rings, 0..) |ring, i| { + c.k[i] = try DeviceBuffer.alloc(d, @as(usize, ring) * kv * 2); + c.v[i] = DeviceBuffer.alloc(d, @as(usize, ring) * kv * 2) catch |e| { + c.k[i].free(); + return e; + }; + made += 1; + } + c.newest = try DeviceBuffer.alloc(d, hidden * 2); + return c; + } + + pub fn deinit(c: *Context) void { + c.newest.free(); + for (0..3) |i| { + c.k[i].free(); + c.v[i].free(); + } + } + + pub const Span = struct { from: u64, end: u64 }; + + /// Reject overlap and overflow before device work; a gap restarts the committed span. + pub fn admit(c: *const Context, start: u64, n: usize) !Span { + if (start < c.end) return error.DraftContextGap; + const from = if (start > c.end) start else c.from; + if (start + n - from > c.rings[1]) return error.DSparkContextFull; + return .{ .from = from, .end = start + n }; + } +}; + +test "a rejected absorb leaves the context's span whole and the next one lands" { + var c: Context = .{ .k = undefined, .v = undefined, .rings = .{ local_ring, 64, local_ring }, .newest = undefined, .from = 10, .end = 20 }; + try std.testing.expectError(error.DSparkContextFull, c.admit(100, 65)); + try std.testing.expectError(error.DraftContextGap, c.admit(19, 1)); + try std.testing.expectEqual(@as(u64, 10), c.from); + try std.testing.expectEqual(@as(u64, 20), c.end); + try std.testing.expectEqual(Context.Span{ .from = 10, .end = 74 }, try c.admit(20, 54)); + const s = try c.admit(100, 64); + try std.testing.expectEqual(@as(u64, 100), s.from); + try std.testing.expectEqual(@as(u64, 164), s.end); + c.from, c.end = .{ s.from, s.end }; + try std.testing.expectError(error.DraftContextGap, c.admit(163, 1)); + try std.testing.expectEqual(@as(u64, 164), c.end); +} + +/// The target's embedding and unembedding remain the plain server's exact weights. +pub const Target = struct { w: *const wts.Weights, lane: *const cuda.qmmf.Lane, unembed: Lane }; +pub const Head = @import("dspark_head.zig").Head; diff --git a/zig/src/families/inkling2/dspark_head.zig b/zig/src/families/inkling2/dspark_head.zig new file mode 100644 index 00000000000..7996bb84c6d --- /dev/null +++ b/zig/src/families/inkling2/dspark_head.zig @@ -0,0 +1,219 @@ +//! Inkling 2 Mini's shared DSpark pass: one projection and one batched kernel launch per layer across active streams. +const std = @import("std"); +const cuda = @import("cuda"); +const dspark = @import("dspark.zig"); +const dsp = @import("dspark_ops.zig"); +const ops = @import("ops.zig"); + +const DeviceBuffer = cuda.DeviceBuffer; +const H = dspark.hidden; +const Q = dspark.query; +const KV = dspark.kv; +const I = dspark.inter; +const R = dspark.rank; +const T = dspark.rows; +const max_streams = 16; + +pub const Head = struct { + gpa: std.mem.Allocator, + w: *const dspark.Weights, + k: *const dsp.Kernels, + t: dspark.Target, + glue: *const ops.Kernels, + d: *const cuda.Driver, + cap: usize, + buffers: std.ArrayList(DeviceBuffer) = .empty, + fused: u64 = 0, + ctx_kv: u64 = 0, + resid: u64 = 0, + x: u64 = 0, + qkv: u64 = 0, + q: u64 = 0, + po: u64 = 0, + pml: u64 = 0, + att: u64 = 0, + y: u64 = 0, + gu: u64 = 0, + act: u64 = 0, + context: u64 = 0, + state: u64 = 0, + latent: u64 = 0, + hidden: u64 = 0, + logits: u64 = 0, + picks: u64 = 0, + walk: u64 = 0, + table: u64 = 0, + at: u64 = 0, + part: u64 = 0, + + fn alloc(h: *Head, len: usize) !u64 { + var b = try DeviceBuffer.alloc(h.d, @max(len, 256)); + errdefer b.free(); + try h.buffers.append(h.gpa, b); + return b.ptr; + } + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, w: *const dspark.Weights, k: *const dsp.Kernels, glue: *const ops.Kernels, t: dspark.Target, cap: usize) !Head { + var h: Head = .{ .gpa = gpa, .w = w, .k = k, .glue = glue, .t = t, .d = d, .cap = cap }; + errdefer h.deinit(gpa); + const batch = max_streams * T; + const maxc = cap / dsp.chunk + 2; + var partial: usize = t.lane.partBytes(max_streams, t.unembed); + for (w.proj) |p| for ([_]cuda.qmmf.Weight{ p.qkv, p.ctx_kv, p.o, p.gu, p.down }) |weight| { + partial = @max(partial, t.lane.partBytes(batch, weight)); + }; + h.fused = try h.alloc(4 * dspark.absorb_rows * H * 2); + h.ctx_kv = try h.alloc(dspark.absorb_rows * 2 * KV * 2); + h.resid = try h.alloc(batch * H * 2); + h.x = try h.alloc(batch * H * 2); + h.qkv = try h.alloc(batch * (Q + 2 * KV) * 2); + h.q = try h.alloc(batch * Q * 2); + h.po = try h.alloc(max_streams * maxc * T * 24 * dsp.head_dim * 4); + h.pml = try h.alloc(max_streams * maxc * T * 24 * 2 * 4); + h.att = try h.alloc(batch * Q * 2); + h.y = try h.alloc(batch * H * 4); + h.gu = try h.alloc(batch * 2 * I * 2); + h.act = try h.alloc(batch * I * 2); + h.context = try h.alloc(max_streams * T * 3 * R * 4); + h.state = try h.alloc(max_streams * R * 2); + h.latent = try h.alloc(max_streams * R * 2); + h.hidden = try h.alloc(max_streams * H * 2); + h.logits = try h.alloc(max_streams * t.w.c.text.unpadded_vocab * 4); + h.picks = try h.alloc(max_streams * 16); + h.walk = try h.alloc(max_streams * T * 4); + h.table = try h.alloc(max_streams * @sizeOf(dsp.Stream)); + h.at = try h.alloc(batch * @sizeOf([2]i32)); + h.part = try h.alloc(partial); + return h; + } + + pub fn deinit(h: *Head, gpa: std.mem.Allocator) void { + for (h.buffers.items) |*b| b.free(); + h.buffers.deinit(gpa); + } + + fn gemm(h: *const Head, s: cuda.Stream, x: u64, rows: usize, weight: cuda.qmmf.Weight, out: u64, kind: cuda.qmmf.Out) !void { + try h.t.lane.matmulOut(s, x, weight.k, rows, weight, out, kind, h.part); + } + + /// Absorb committed rows only; a rejected span never changes the stream's published position. + pub fn absorb(h: *const Head, s: cuda.Stream, c: *dspark.Context, taps: u64, start: u64, n: usize) !void { + const span = try c.admit(start, n); + var at: usize = 0; + while (at < n) : (at += dspark.absorb_rows) { + const count: usize = @min(dspark.absorb_rows, n - at); + const input = taps + at * 4 * H * 2; + for (0..4) |f| { + try dsp.mix(h.k, s, input, h.w.alpha + f * 4 * 4, h.w.dflare + f * H * 2, h.fused + f * count * H * 2, count, 4, H, 1e-6); + } + try h.d.check(h.d.api.cuMemcpyDtoDAsync_v2(c.newest.ptr, h.fused + (3 * count + count - 1) * H * 2, H * 2, s.handle), "cuMemcpyDtoDAsync"); + for (h.w.proj, h.w.norms, 0..) |p, norms, layer| { + try h.gemm(s, h.fused + layer * count * H * 2, count, p.ctx_kv, h.ctx_kv, .bf16); + try dsp.qk(h.k, s, .{ + .x = h.ctx_kv, + .qw = 0, + .kw = norms.k_ctx, + .q = 0, + .kc = c.k[layer].ptr, + .vc = c.v[layer].ptr, + .ld = 2 * KV, + .hq = 0, + .hk = 8, + .ring = @intCast(c.rings[layer]), + .pos0 = @intCast(start + at), + .eps = 1e-6, + .theta = 1e6, + }, count); + } + } + c.from, c.end = .{ span.from, span.end }; + } + + /// A batched block pass shares weights; Q/K and attention use #4858's stream-table kernels. + pub fn draftMany(h: *const Head, s: cuda.Stream, contexts: []const *dspark.Context, pending: []const u32, max_depth: usize, out: []u32) !void { + const n = contexts.len; + if (n == 0 or n > max_streams or pending.len != n or out.len != n * T or max_depth == 0 or max_depth > dspark.depth) + return error.DSparkHoldGeometry; + const vocab = h.t.w.c.text.unpadded_vocab; + var table: [max_streams]dsp.Stream = undefined; + var at: [max_streams * T][2]i32 = undefined; + var walk: [max_streams * T]u32 = @splat(0); + for (contexts, pending, 0..) |c, token, stream| { + if (c.end <= c.from or c.end + T > h.cap or token >= h.t.w.c.text.vocab) return error.DSparkHoldGeometry; + walk[stream * T] = token; + const p: i32 = @intCast(c.end); + table[stream] = .{ .frnn = c.newest.ptr, .p = p }; + for (c.rings, 0..) |ring, layer| { + table[stream].kc[layer] = c.k[layer].ptr; + table[stream].vc[layer] = c.v[layer].ptr; + const window: u64 = if (layer == 1) ring else 1024; + table[stream].lo[layer] = @intCast(@max(c.from, c.end + T -| window)); + } + for (0..T) |row| at[stream * T + row] = .{ @intCast(stream), p + @as(i32, @intCast(row)) }; + } + try cuda.copy_source.enqueue(h.d, h.table, std.mem.sliceAsBytes(table[0..n]), s); + try cuda.copy_source.enqueue(h.d, h.at, std.mem.sliceAsBytes(at[0 .. n * T]), s); + try cuda.copy_source.enqueue(h.d, h.walk, std.mem.sliceAsBytes(walk[0 .. n * T]), s); + // Embed the first token exactly as the target does; masks are the remaining uncommitted rows. + for (0..n) |stream| { + try ops.embed(h.glue, s, h.walk + stream * T * 4, 1, h.t.w.embed, h.t.w.embed_norm, h.resid + stream * T * H * 2, H, h.t.w.c.text.eps); + for (1..T) |row| try h.d.check(h.d.api.cuMemcpyDtoDAsync_v2(h.resid + (stream * T + row) * H * 2, h.w.mask, H * 2, s.handle), "cuMemcpyDtoDAsync"); + } + try dsp.addNorm(h.k, s, h.resid, 0, 0, n * T * H, h.w.norms[0].input, h.x, n * T, H, 1e-6); + const tab: dsp.Table = .{ .dev = h.table, .host = table[0..n] }; + const row_ids: dsp.Rows = .{ .dev = h.at, .host = at[0 .. n * T] }; + for (h.w.proj, h.w.norms, 0..) |p, norms, layer| { + try h.gemm(s, h.x, n * T, p.qkv, h.qkv, .bf16); + try dsp.qkMany(h.k, s, .{ + .x = h.qkv, + .qw = norms.q, + .kw = norms.k, + .q = h.q, + .kc = 0, + .vc = 0, + .ld = Q + 2 * KV, + .hq = 24, + .hk = 8, + .ring = @intCast(contexts[0].rings[layer]), + .pos0 = 0, + .eps = 1e-6, + .theta = 1e6, + }, tab, row_ids, layer); + var maxc: usize = 1; + for (table[0..n]) |item| maxc = @max(maxc, dsp.chunks(@intCast(item.lo[layer]), @intCast(item.p + T - 1))); + try dsp.attendMany(h.k, s, .{ + .q = h.q, + .kc = 0, + .vc = 0, + .po = h.po, + .pml = h.pml, + .T = T, + .hq = 24, + .hk = 8, + .ring = @intCast(contexts[0].rings[layer]), + .lo = 0, + .hi = 0, + .c0 = 0, + .scale = 1.0 / @sqrt(@as(f32, dsp.head_dim)), + }, tab, layer, maxc, n * (h.cap / dsp.chunk + 2), h.att); + try h.gemm(s, h.att, n * T, p.o, h.y, .f32); + try dsp.addNorm(h.k, s, h.resid, h.y, 1, n * T * H, norms.post, h.x, n * T, H, 1e-6); + try h.gemm(s, h.x, n * T, p.gu, h.gu, .bf16); + try dsp.silu(h.k, s, h.gu, h.act, n * T, I); + try h.gemm(s, h.act, n * T, p.down, h.y, .f32); + try dsp.addNorm(h.k, s, h.resid, h.y, 1, n * T * H, if (layer < 2) h.w.norms[layer + 1].input else h.w.norm, h.x, n * T, H, 1e-6); + } + try dsp.ctxMany(h.k, s, h.x + H * 2, T * H, h.table, h.w.rnn, h.w.rnn_b, h.context, n, T - 1, H, R); + try h.d.check(h.d.api.cuMemsetD8Async(h.state, 0, n * R * 2, s.handle), "cuMemsetD8Async"); + for (0..max_depth) |step| { + try dsp.rnnMany(h.k, s, h.context + step * 3 * R * 4, (T - 1) * 3 * R, h.w.rnn, h.w.markov, h.walk, T, step, h.state, h.latent, n, R, H); + try dsp.miniHidden(h.k, s, h.x + (step + 1) * H * 2, T * H, h.latent, h.w.hidden_w, h.w.hidden_b, h.hidden, n, H, R); + try h.gemm(s, h.hidden, n, h.t.unembed, h.logits, .f32); + try ops.softcap(h.glue, s, h.logits, n * vocab, h.t.w.c.text.logit_cap); + try dsp.pickMany(h.k, s, h.logits, vocab, vocab, 0, h.table, step, h.picks, n); + try dsp.pickRows(h.k, s, h.picks, 1, n, h.walk, T, step); + } + try s.synchronize(); + try (DeviceBuffer{ .d = h.d, .ptr = h.walk, .len = n * T * 4, .borrowed = true }).download(0, std.mem.sliceAsBytes(out)); + } +}; diff --git a/zig/src/families/inkling2/dspark_ops.zig b/zig/src/families/inkling2/dspark_ops.zig new file mode 100644 index 00000000000..e4d02ec1bd2 --- /dev/null +++ b/zig/src/families/inkling2/dspark_ops.zig @@ -0,0 +1,490 @@ +//! The DSpark drafter's kernels (inkling2/dspark.cu): tap mix, norms, q/k prep, block attention, the Markov head. +const std = @import("std"); +const cuda = @import("cuda"); + +/// Keys a block attention chunk covers (absolute positions, so a row's bits never depend on the call). +pub const chunk = 1024; +/// Query rows x query heads of one key head a block attention call holds at most (dspark.cu's kMaxQ). +pub const max_q = 48; +/// The Markov rank the head's kernels hold (dspark.cu's 256-wide fold rows and rnn's shared rows). +pub const rank = 256; +/// The attention head width dspark.cu's kD fixes. +pub const head_dim = 128; +/// Rows a block drafts at most (dspark.cu's kMaxRows). +pub const max_rows = 8; + +/// A draft head these kernels would run wrong is refused: any other Markov rank or head_dim, or a longer block. +pub fn checkHead(markov_rank: usize, dim: usize, block: usize) !void { + if (markov_rank != rank or dim != head_dim or block == 0 or block > max_rows) return error.Inkling2DraftShape; +} + +/// dspark.cu's QkArgs, field for field. +pub const QkArgs = extern struct { + x: u64, + qw: u64, + kw: u64, + q: u64, + kc: u64, + vc: u64, + ld: i64, + hq: i32, + hk: i32, + ring: i32, + pos0: i32, + eps: f32, + theta: f32, +}; + +/// dspark.cu's AttnArgs, field for field. +pub const AttnArgs = extern struct { + q: u64, + kc: u64, + vc: u64, + po: u64, + pml: u64, + T: i32, + hq: i32, + hk: i32, + ring: i32, + lo: i32, + hi: i32, + c0: i32, + scale: f32, +}; + +pub const Kernels = struct { + mod: cuda.Module, + /// act_rows: the SiLU is core's tf_swiglu_rows in torch's form + rows: cuda.Module, + mix: cuda.Function, + addnorm: cuda.Function, + qk: cuda.Function, + attn: cuda.Function, + merge: cuda.Function, + silu: cuda.Function, + ctx: cuda.Function, + rnn: cuda.Function, + vocab: cuda.Function, + pick: cuda.Function, + vocab_rows: cuda.Function, + pick_rows: cuda.Function, + many: Many, + mini_tap: cuda.Function, + mini_hidden: cuda.Function, + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.inkling2_dspark); + errdefer mod.unload(); + var rows = try cuda.Module.load(d, cuda.kernels.act_rows); + errdefer rows.unload(); + return .{ + .mod = mod, + .rows = rows, + .mix = try mod.function("tf_ink2_dsp_mix"), + .addnorm = try mod.function("tf_ink2_dsp_addnorm"), + .qk = try mod.function("tf_ink2_dsp_qk"), + .attn = try mod.function("tf_ink2_dsp_attn"), + .merge = try mod.function("tf_ink2_dsp_merge"), + .silu = try rows.function("tf_swiglu_rows_expf"), + .ctx = try mod.function("tf_ink2_dsp_ctx"), + .rnn = try mod.function("tf_ink2_dsp_rnn"), + .vocab = try mod.function("tf_ink2_dsp_vocab"), + .pick = try mod.function("tf_ink2_dsp_pick_merge"), + .vocab_rows = try mod.function("tf_ink2_dsp_vocab_rows"), + .pick_rows = try mod.function("tf_ink2_dsp_pick_rows"), + .mini_tap = try mod.function("tf_ink2_mini_tap"), + .mini_hidden = try mod.function("tf_ink2_mini_hidden"), + .many = .{ + .qk = try mod.function("tf_ink2_dsp_qk_many"), + .attn = try mod.function("tf_ink2_dsp_attn_many"), + .merge = try mod.function("tf_ink2_dsp_merge_many"), + .ctx = try mod.function("tf_ink2_dsp_ctx_many"), + .rnn = try mod.function("tf_ink2_dsp_rnn_many"), + .pick = try mod.function("tf_ink2_dsp_pick_many"), + }, + }; + } + + pub fn unload(k: *Kernels) void { + k.rows.unload(); + k.mod.unload(); + k.* = undefined; + } +}; + +fn int(x: anytype) i32 { + return @intCast(x); +} + +fn go(f: cuda.Function, s: cuda.Stream, grid: cuda.Dim3, threads: u32, a: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = threads } }, s, a); +} + +/// out bf16 [rows][c] = RMSNorm(alpha . taps[row]) * w; taps bf16 [rows][n][c], alpha fp32 [n]. +pub fn mix(k: *const Kernels, s: cuda.Stream, taps: u64, alpha: u64, w: u64, out: u64, rows: usize, n: usize, c: usize, eps: f32) !void { + var a: cuda.Args = .{}; + for ([_]u64{ taps, alpha, w, out }) |v| a.add(v); + a.add(int(n)); + a.add(int(c)); + a.add(eps); + try go(k.mix, s, .{ .x = @intCast(rows) }, 512, &a); +} + +/// resid += `nparts` fp32 partials (`stride` elements apart, rank order); out = RMSNorm(resid) * w, both bf16. +pub fn addNorm(k: *const Kernels, s: cuda.Stream, resid: u64, parts: u64, nparts: usize, stride: usize, w: u64, out: u64, rows: usize, c: usize, eps: f32) !void { + var a: cuda.Args = .{}; + a.add(resid); + a.add(parts); + a.add(int(nparts)); + a.add(@as(i64, @intCast(stride))); + a.add(w); + a.add(out); + a.add(int(c)); + a.add(eps); + try go(k.addnorm, s, .{ .x = @intCast(rows) }, 512, &a); +} + +/// The q/k launch's refusals: a negative head count, no key head, no ring, or rows narrower than their heads. +pub fn checkQk(q: QkArgs) !void { + if (q.hq < 0 or q.hk <= 0 or q.ring <= 0 or q.ld < (q.hq + 2 * q.hk) * head_dim) return error.Inkling2DraftShape; +} + +pub fn qk(k: *const Kernels, s: cuda.Stream, q: QkArgs, rows: usize) !void { + try checkQk(q); + var a: cuda.Args = .{}; + a.add(q); + try go(k.qk, s, .{ .x = @intCast(rows), .y = @intCast(q.hq + q.hk) }, 64, &a); +} + +/// Chunks a block's keys [lo, hi] span. +pub fn chunks(lo: usize, hi: usize) usize { + return hi / chunk - lo / chunk + 1; +} + +/// Block attention over keys [a.lo, a.hi], then the chunks merged into `out` bf16 [T][hq][128]. +pub fn attend(k: *const Kernels, s: cuda.Stream, at: AttnArgs, out: u64) !void { + const lo: usize = @intCast(at.lo); + const hi: usize = @intCast(at.hi); + if (lo > hi or at.T * @divExact(at.hq, at.hk) > max_q) return error.Inkling2DraftShape; + if (at.ring <= 0 or hi - lo >= @as(usize, @intCast(at.ring))) return error.Inkling2DraftShape; // keys would alias + var x = at; + x.c0 = int(lo / chunk); + const n = chunks(lo, hi); + var a: cuda.Args = .{}; + a.add(x); + try go(k.attn, s, .{ .x = @intCast(n), .y = @intCast(at.hk) }, 256, &a); + var m: cuda.Args = .{}; + m.add(at.po); + m.add(at.pml); + m.add(int(n)); + m.add(at.T * at.hq); + m.add(out); + try go(k.merge, s, .{ .x = @intCast(at.T * at.hq) }, 128, &m); +} + +/// gu bf16 [rows][2 * inter] (gates, then ups) to bf16(silu(gate) * up) by core's tf_swiglu_rows_expf. +pub fn silu(k: *const Kernels, s: cuda.Stream, gu: u64, out: u64, rows: usize, inter: usize) !void { + if (inter % 64 != 0) return error.Inkling2DraftShape; + var a: cuda.Args = .{}; + a.add(gu); + a.add(@as(i64, @intCast(2 * inter))); + a.add(gu + 2 * inter); + a.add(@as(i64, @intCast(2 * inter))); + a.add(out); + a.add(@as(u64, 0)); + a.add(int(inter)); + try go(k.silu, s, .{ .x = @intCast(rows), .y = @intCast((inter / 8 + 255) / 256) }, 256, &a); +} + +/// The Markov head's context rows: fp32 [rows][3r] from the hidden rows and f_rnn. +pub fn ctx(k: *const Kernels, s: cuda.Stream, hidden: u64, frnn: u64, w: u64, bias: u64, out: u64, rows: usize, c: usize, r: usize) !void { + if (rows > max_rows or r != rank) return error.Inkling2DraftShape; + var a: cuda.Args = .{}; + for ([_]u64{ hidden, frnn, w, bias, out }) |v| a.add(v); + for ([_]i32{ int(rows), int(c), int(r) }) |v| a.add(v); + try go(k.ctx, s, .{ .x = @intCast((3 * r + 7) / 8) }, 256, &a); +} + +/// One recurrence step from walk[j]: the state in place and the step's latent. +pub fn rnn(k: *const Kernels, s: cuda.Stream, cx: u64, w: u64, w1: u64, walk: u64, j: usize, state: u64, latent: u64, r: usize, c: usize) !void { + if (r != rank) return error.Inkling2DraftShape; + var a: cuda.Args = .{}; + for ([_]u64{ cx, w, w1, walk }) |v| a.add(v); + a.add(int(j)); + a.add(state); + a.add(latent); + a.add(int(r)); + a.add(int(c)); + try go(k.rnn, s, .{ .x = 1 }, @intCast(r), &a); +} + +pub fn vocab(k: *const Kernels, s: cuda.Stream, base: u64, latent: u64, fold: u64, fbias: u64, cap: f32, valid: usize, nv: usize, out: u64) !void { + var a: cuda.Args = .{}; + for ([_]u64{ base, latent, fold, fbias }) |v| a.add(v); + a.add(cap); + a.add(int(valid)); + a.add(int(nv)); + a.add(out); + try go(k.vocab, s, .{ .x = @intCast((nv + 7) / 8) }, 256, &a); +} + +/// Every rank's (value, id), 16 bytes a rank, into walk[j + 1]: one warp, as MiniMax M3 launches the shared merge. +pub fn pick(k: *const Kernels, s: cuda.Stream, picks: u64, world: usize, walk: u64, j: usize) !void { + var a: cuda.Args = .{}; + a.add(picks); + a.add(int(world)); + a.add(int(16)); + a.add(walk); + a.add(int(j)); + try go(k.pick, s, .{ .x = 1 }, 32, &a); +} + +pub fn vocabRows(k: *const Kernels, s: cuda.Stream, base: u64, base_ld: usize, latent: u64, fold: u64, fbias: u64, cap: f32, valid: usize, nv: usize, rows: usize, out: u64) !void { + var a: cuda.Args = .{}; + a.add(base); + a.add(@as(i64, @intCast(base_ld))); + for ([_]u64{ latent, fold, fbias }) |v| a.add(v); + a.add(cap); + a.add(int(valid)); + a.add(int(nv)); + a.add(int(rows)); + a.add(out); + try go(k.vocab_rows, s, .{ .x = @intCast((nv + 7) / 8) }, 256, &a); +} + +/// Every stream's best pick across ranks (rank q's row r at (q * rows + r) * 16 bytes) into its walk, a block a stream. +pub fn pickRows(k: *const Kernels, s: cuda.Stream, picks: u64, world: usize, rows: usize, walk: u64, t: usize, j: usize) !void { + var a: cuda.Args = .{}; + a.add(picks); + for ([_]usize{ world, rows }) |v| a.add(int(v)); + a.add(walk); + for ([_]usize{ t, j }) |v| a.add(int(v)); + try go(k.pick_rows, s, .{ .x = @intCast(rows) }, 32, &a); +} + +/// The batched pass's kernels (dspark_many.cuh): every stream of a pass in one launch. +pub const Many = struct { + qk: cuda.Function, + attn: cuda.Function, + merge: cuda.Function, + ctx: cuda.Function, + rnn: cuda.Function, + pick: cuda.Function, +}; + +/// dspark_many.cuh's DspStream, field for field: a stream's caches by layer, f_rnn, anchor, keys, race. +pub const Stream = extern struct { + kc: [8]u64 = @splat(0), + vc: [8]u64 = @splat(0), + frnn: u64 = 0, + seed: u64 = 0, + p: i32 = 0, + race: i32 = 0, + inv_t: f32 = 0, + lo: [8]i32 = @splat(0), + pad: i32 = 0, +}; + +/// A stream table on the device and the host copy it was uploaded from, which the launchers check. +pub const Table = struct { dev: u64, host: []const Stream }; + +/// The rows of a batched q/k launch: (stream, position) pairs on the device and on the host. +pub const Rows = struct { dev: u64, host: []const [2]i32 }; + +/// A batched q/k launch keeps the one-stream refusals, and each row names a stream with caches at `layer`. +pub fn checkQkMany(q: QkArgs, tab: []const Stream, at: []const [2]i32, layer: usize) !void { + try checkQk(q); + if (layer >= 8 or at.len == 0) return error.Inkling2DraftShape; + for (at) |r| { + if (r[0] < 0 or r[0] >= tab.len or r[1] < 0) return error.Inkling2DraftShape; + const st = tab[@intCast(r[0])]; + if (st.kc[layer] == 0 or st.vc[layer] == 0) return error.Inkling2DraftShape; + } +} + +/// Each stream's window [lo, p + T - 1] fits the ring and `maxc` chunks; the partials hold `cap` chunks in all. +pub fn checkAttendMany(at: AttnArgs, tab: []const Stream, layer: usize, maxc: usize, cap: usize) !void { + if (at.T <= 0 or at.hk <= 0 or at.hq <= 0 or @rem(at.hq, at.hk) != 0) return error.Inkling2DraftShape; + if (at.T * @divExact(at.hq, at.hk) > max_q or at.ring <= 0) return error.Inkling2DraftShape; + if (layer >= 8 or tab.len == 0 or maxc == 0 or tab.len * maxc > cap) return error.Inkling2DraftShape; + for (tab) |st| { + const lo = st.lo[layer]; + const hi = @as(i64, st.p) + at.T - 1; + if (st.p < 0 or lo < 0 or lo > hi or hi - lo >= at.ring) return error.Inkling2DraftShape; // keys would alias + if (chunks(@intCast(lo), @intCast(hi)) > maxc or st.kc[layer] == 0 or st.vc[layer] == 0) return error.Inkling2DraftShape; + } +} + +/// q/k prep over several streams' rows: row r is stream at[r][0] at position at[r][1] (QkArgs' kc, vc, pos0 unused). +pub fn qkMany(k: *const Kernels, s: cuda.Stream, q: QkArgs, tab: Table, at: Rows, layer: usize) !void { + try checkQkMany(q, tab.host, at.host, layer); + var a: cuda.Args = .{}; + a.add(q); + a.add(tab.dev); + a.add(at.dev); + a.add(int(layer)); + try go(k.many.qk, s, .{ .x = @intCast(at.host.len), .y = @intCast(q.hq + q.hk) }, 64, &a); +} + +/// Every stream's block attention (at most `maxc` chunks each), then its merge into `out` [n][T][hq][128]. +pub fn attendMany(k: *const Kernels, s: cuda.Stream, at: AttnArgs, tab: Table, layer: usize, maxc: usize, cap: usize, out: u64) !void { + try checkAttendMany(at, tab.host, layer, maxc, cap); + const n = tab.host.len; + var a: cuda.Args = .{}; + a.add(at); + a.add(tab.dev); + a.add(int(layer)); + a.add(int(maxc)); + try go(k.many.attn, s, .{ .x = @intCast(maxc), .y = @intCast(at.hk), .z = @intCast(n) }, 256, &a); + var m: cuda.Args = .{}; + for ([_]u64{ at.po, at.pml, tab.dev }) |v| m.add(v); + for ([_]i32{ int(layer), at.T, int(maxc), at.T * at.hq }) |v| m.add(v); + m.add(out); + try go(k.many.merge, s, .{ .x = @intCast(at.T * at.hq), .y = @intCast(n) }, 128, &m); +} + +/// The Markov head's context rows of `n` streams (hidden rows `hstride` elements apart): fp32 [n][rows][3r]. +pub fn ctxMany(k: *const Kernels, s: cuda.Stream, hidden: u64, hstride: usize, st: u64, w: u64, bias: u64, out: u64, n: usize, rows: usize, c: usize, r: usize) !void { + if (rows > max_rows or r != rank) return error.Inkling2DraftShape; + var a: cuda.Args = .{}; + a.add(hidden); + a.add(@as(i64, @intCast(hstride))); + for ([_]u64{ st, w, bias, out }) |v| a.add(v); + for ([_]i32{ int(rows), int(c), int(r) }) |v| a.add(v); + try go(k.many.ctx, s, .{ .x = @intCast((3 * r + 7) / 8), .y = @intCast(n) }, 256, &a); +} + +/// One recurrence step of `n` streams' walks (ctx rows `cstride` floats apart, walks `t` apart). +pub fn rnnMany(k: *const Kernels, s: cuda.Stream, cx: u64, cstride: usize, w: u64, w1: u64, walk: u64, t: usize, j: usize, state: u64, latent: u64, n: usize, r: usize, c: usize) !void { + if (r != rank) return error.Inkling2DraftShape; + var a: cuda.Args = .{}; + a.add(cx); + a.add(@as(i64, @intCast(cstride))); + for ([_]u64{ w, w1, walk }) |v| a.add(v); + for ([_]usize{ t, j }) |v| a.add(int(v)); + a.add(state); + a.add(latent); + for ([_]usize{ r, c }) |v| a.add(int(v)); + try go(k.many.rnn, s, .{ .x = @intCast(n) }, @intCast(r), &a); +} + +/// Each of `n` streams' step pick on this rank (greedy over nv, or raced over valid) into `picks`, 16 bytes apart. +pub fn pickMany(k: *const Kernels, s: cuda.Stream, scores: u64, nv: usize, valid: usize, base: usize, st: u64, step: usize, picks: u64, n: usize) !void { + var a: cuda.Args = .{}; + a.add(scores); + for ([_]usize{ nv, valid, base }) |v| a.add(int(v)); + a.add(st); + a.add(int(step)); + a.add(picks); + try go(k.many.pick, s, .{ .x = @intCast(n) }, 1024, &a); +} + +/// Mini's four visit taps, row-interleaved, including the final post-norm row. +pub fn miniTap(k: *const Kernels, s: cuda.Stream, src: u64, dst: u64, rows: usize, channel: usize, width: usize) !void { + var a: cuda.Args = .{}; + for ([_]u64{ src, dst }) |v| a.add(v); + for ([_]i32{ int(rows), int(channel), int(width) }) |v| a.add(v); + try go(k.mini_tap, s, .{ .x = @intCast((width + 255) / 256), .y = @intCast(rows) }, 256, &a); +} + +/// Mini's hidden projection before the target unembedding; #4858's vocabulary fold is not its checkpoint arithmetic. +pub fn miniHidden(k: *const Kernels, s: cuda.Stream, y: u64, stride: usize, latent: u64, w: u64, bias: u64, out: u64, n: usize, width: usize, r: usize) !void { + var a: cuda.Args = .{}; + a.add(y); + a.add(@as(i64, @intCast(stride))); + for ([_]u64{ latent, w, bias, out }) |v| a.add(v); + for ([_]i32{ int(width), int(r) }) |v| a.add(v); + try go(k.mini_hidden, s, .{ .x = @intCast((width + 255) / 256), .y = @intCast(n) }, 256, &a); +} + +test "dspark ops: argument structs keep dspark.cu's layouts; chunks by absolute position" { + try std.testing.expectEqual(@as(usize, 6 * 8 + 8 + 4 * 4 + 2 * 4), @sizeOf(QkArgs)); + try std.testing.expectEqual(@as(usize, 5 * 8 + 8 * 4), @sizeOf(AttnArgs)); + try std.testing.expectEqual(@as(usize, 1), chunks(0, 1023)); + try std.testing.expectEqual(@as(usize, 2), chunks(1000, 1030)); +} + +test "dspark ops: a head, a block or a ring the kernels would run wrong is refused before a launch" { + const no = error.Inkling2DraftShape; + try checkHead(256, 128, 8); + try std.testing.expectError(no, checkHead(8, 128, 8)); // tiny-random's rank + try std.testing.expectError(no, checkHead(512, 128, 8)); + try std.testing.expectError(no, checkHead(256, 64, 8)); + try std.testing.expectError(no, checkHead(256, 128, 9)); + const k: Kernels = undefined; + const s: cuda.Stream = undefined; + try std.testing.expectError(no, silu(&k, s, 0, 0, 8, 4600)); // not a multiple of 64 columns + try std.testing.expectError(no, rnn(&k, s, 0, 0, 0, 0, 0, 0, 0, 512, 4608)); + try std.testing.expectError(no, ctx(&k, s, 0, 0, 0, 0, 0, 8, 4608, 128)); + try std.testing.expectError(no, ctx(&k, s, 0, 0, 0, 0, 0, 9, 4608, 256)); + try std.testing.expectError(no, ctxMany(&k, s, 0, 0, 0, 0, 0, 0, 2, 9, 4608, 256)); + try std.testing.expectError(no, rnnMany(&k, s, 0, 0, 0, 0, 0, 8, 0, 0, 0, 2, 512, 4608)); + const q: QkArgs = .{ .x = 0, .qw = 0, .kw = 0, .q = 0, .kc = 0, .vc = 0, .ld = 32 * 64, .hq = 24, .hk = 4, .ring = 4096, .pos0 = 0, .eps = 1e-6, .theta = 1e6 }; + try std.testing.expectError(no, qk(&k, s, q, 8)); // 64-wide heads + const at: AttnArgs = .{ .q = 0, .kc = 0, .vc = 0, .po = 0, .pml = 0, .T = 8, .hq = 24, .hk = 4, .ring = 4096, .lo = 0, .hi = 4096, .c0 = 0, .scale = 1 }; + try std.testing.expectError(no, attend(&k, s, at, 0)); // 4,097 keys in a 4,096-row ring +} + +test "dspark ops: a batched q/k launch keeps the one-stream refusals and checks its rows" { + const no = error.Inkling2DraftShape; + const k: Kernels = undefined; + const s: cuda.Stream = undefined; + var tab = [_]Stream{ .{}, .{} }; + for (&tab, 0..) |*st, i| { + st.kc[2] = 0x1000 * (i + 1); + st.vc[2] = 0x1000 * (i + 1) + 0x800; + } + const at = [_][2]i32{ .{ 0, 70 }, .{ 1, 4100 }, .{ 1, 4101 } }; + const q: QkArgs = .{ .x = 0, .qw = 0, .kw = 0, .q = 0, .kc = 0, .vc = 0, .ld = 32 * 128, .hq = 24, .hk = 4, .ring = 4096, .pos0 = 0, .eps = 1e-6, .theta = 1e6 }; + try checkQkMany(q, &tab, &at, 2); + const t: Table = .{ .dev = 0, .host = &tab }; + const r: Rows = .{ .dev = 0, .host = &at }; + var bad = q; + bad.ld = 32 * 64; + try std.testing.expectError(no, qkMany(&k, s, bad, t, r, 2)); // rows narrower than their heads + bad = q; + bad.ring = 0; + try std.testing.expectError(no, qkMany(&k, s, bad, t, r, 2)); + bad = q; + bad.hk = 0; + try std.testing.expectError(no, qkMany(&k, s, bad, t, r, 2)); + try std.testing.expectError(no, qkMany(&k, s, q, t, r, 8)); // the table holds 8 layers + try std.testing.expectError(no, qkMany(&k, s, q, t, r, 1)); // no caches at layer 1 + try std.testing.expectError(no, qkMany(&k, s, q, t, .{ .dev = 0, .host = &.{} }, 2)); + try std.testing.expectError(no, qkMany(&k, s, q, t, .{ .dev = 0, .host = &.{.{ 2, 70 }} }, 2)); // past the table + try std.testing.expectError(no, qkMany(&k, s, q, t, .{ .dev = 0, .host = &.{.{ -1, 70 }} }, 2)); + try std.testing.expectError(no, qkMany(&k, s, q, t, .{ .dev = 0, .host = &.{.{ 0, -1 }} }, 2)); +} + +test "dspark ops: a batched attention checks each window, the layer and the partials' room" { + const no = error.Inkling2DraftShape; + const k: Kernels = undefined; + const s: cuda.Stream = undefined; + var tab = [_]Stream{ .{ .p = 0 }, .{ .p = 70_000 }, .{ .p = 3000 } }; + for (&tab, [_]i32{ 0, 70_000 - 4088, 2500 }) |*st, lo| { + st.kc[3] = 0x1000; + st.vc[3] = 0x2000; + st.lo[3] = lo; + } + const at: AttnArgs = .{ .q = 0, .kc = 0, .vc = 0, .po = 0, .pml = 0, .T = 8, .hq = 24, .hk = 4, .ring = 4096, .lo = 0, .hi = 0, .c0 = 0, .scale = 1 }; + try checkAttendMany(at, &tab, 3, 5, 15); + const t: Table = .{ .dev = 0, .host = &tab }; + try std.testing.expectError(no, attendMany(&k, s, at, t, 3, 5, 14, 0)); // partials for 14 chunks, 15 needed + try std.testing.expectError(no, attendMany(&k, s, at, t, 3, 4, 15, 0)); // stream 1 spans 5 chunks + try std.testing.expectError(no, attendMany(&k, s, at, t, 8, 5, 15, 0)); + try std.testing.expectError(no, attendMany(&k, s, at, t, 2, 5, 15, 0)); // no caches at layer 2 + var bad = at; + bad.ring = 4095; + try std.testing.expectError(no, attendMany(&k, s, bad, t, 3, 5, 15, 0)); // stream 1's 4,096 keys alias + bad = at; + bad.T = 9; + try std.testing.expectError(no, attendMany(&k, s, bad, t, 3, 5, 15, 0)); // 54 query rows a key head + var late = tab; + late[2].lo[3] = 3008; + try std.testing.expectError(no, attendMany(&k, s, at, .{ .dev = 0, .host = &late }, 3, 5, 15, 0)); // lo past hi + late = tab; + late[0].p = -1; + try std.testing.expectError(no, attendMany(&k, s, at, .{ .dev = 0, .host = &late }, 3, 5, 15, 0)); + try std.testing.expectError(no, attendMany(&k, s, at, .{ .dev = 0, .host = &.{} }, 3, 5, 15, 0)); +} diff --git a/zig/src/families/inkling2/inkling2.zig b/zig/src/families/inkling2/inkling2.zig index f311dc17d35..807a36fdaea 100644 --- a/zig/src/families/inkling2/inkling2.zig +++ b/zig/src/families/inkling2/inkling2.zig @@ -10,6 +10,7 @@ pub const loop = @import("loop.zig"); pub const loop_model = @import("loop_model.zig"); pub const loop_math_cuda = @import("loop_math_cuda.zig"); pub const native = @import("cuda_native.zig"); +pub const dspark_ops = @import("dspark_ops.zig"); /// config.json's name in the release. pub const model_type = "inkling2"; @@ -25,4 +26,5 @@ test { _ = loop; _ = loop_model; _ = loop_math_cuda; + _ = dspark_ops; } diff --git a/zig/src/families/inkling2/loop_backend.zig b/zig/src/families/inkling2/loop_backend.zig index d594ac23e9d..3dc467ba59a 100644 --- a/zig/src/families/inkling2/loop_backend.zig +++ b/zig/src/families/inkling2/loop_backend.zig @@ -4,6 +4,7 @@ const cuda = @import("cuda"); const lanes = @import("lanes"); const engine = @import("loop_engine.zig"); const ops = @import("ops.zig"); +const dspark = @import("dspark.zig"); const Model = engine.Model; const Kernels = engine.Kernels; @@ -16,6 +17,8 @@ const Lane = struct { len: usize = 0, fill: ?usize = null, base: usize = 0, + tap_rows: usize = 0, + tap_row0: usize = 0, rows: std.ArrayList(u32) = .empty, last: u64, rule: u64, @@ -92,6 +95,43 @@ pub const Backend = struct { b.* = undefined; } + fn prepareFeatures(ptr: *anyopaque, taps: []const u32) anyerror!void { + const b = self(ptr); + const mtp = b.m.w.c.mtp orelse return error.UnsupportedInkling2Taps; + if (mtp.taps_n != dspark.taps.len or !std.mem.eql(u32, mtp.taps[0..mtp.taps_n], &dspark.taps) or + !std.mem.eql(u32, taps, &dspark.taps)) return error.UnsupportedInkling2Taps; + if (b.k.draft == null) return error.DSparkKernelsMissing; + try b.m.prepareTaps(); + } + + fn features(ptr: *anyopaque, s: *lanes.Stream, taps: []const u32, start: u64, count: u32) anyerror!be.Features { + const b = self(ptr); + if (!std.mem.eql(u32, taps, &dspark.taps) or b.m.s.taps == 0) return error.UnpreparedInkling2Taps; + const l = try b.laneOf(s); + if (start < l.base or count == 0 or start + count > l.base + l.tap_rows) return error.Inkling2TapsNotHeld; + const row_bytes = dspark.taps.len * dspark.hidden * 2; + return .{ + .buffer = b.m.s.taps, + .offset = (l.tap_row0 + start - l.base) * row_bytes, + .rows = count, + .row_bytes = row_bytes, + .space = .device, + .dtype = .bf16, + }; + } + + fn prefillFeatures(ptr: *anyopaque, s: *lanes.Stream, taps: []const u32, sink: be.FeatureSink) anyerror!void { + const b = self(ptr); + if (!std.mem.eql(u32, taps, &dspark.taps) or b.m.s.taps == 0) return error.UnpreparedInkling2Taps; + const l = try b.opening(s); + errdefer release(ptr, s); + while (true) { + const done = try b.chunk(s, l); + try sink.take(sink.ptr, s, try features(ptr, s, taps, l.base, @intCast(l.tap_rows)), l.base); + if (done) break; + } + } + pub fn backend(b: *Backend) be.Backend { return .{ .ptr = b, .vtable = &vtable }; } @@ -185,6 +225,9 @@ pub const Backend = struct { } const done = end == prompt.len; try b.m.forward(b.k, b.s, prompt[at..end], at, end - at - 1, @intFromBool(done), false); + l.base = at; + l.tap_rows = end - at; + l.tap_row0 = 0; if (done) try b.d.check(b.d.api.cuMemcpyDtoDAsync_v2(l.last, b.m.s.logits, b.m.w.c.text.unpadded_vocab * 4, b.s.handle), "cuMemcpyDtoDAsync"); l.len = end; l.fill = if (done) null else end; @@ -224,6 +267,9 @@ pub const Backend = struct { .first = first, .first_masked = firstMasked, .queue = queue, + .prepare_features = prepareFeatures, + .features = features, + .prefill_features = prefillFeatures, .read = read, .verify = verify, .keep = keep, @@ -272,6 +318,9 @@ pub const Backend = struct { const l = try b.laneOf(s); const token = try b.feed(value); if (position != l.len + 1) return error.PositionMismatch; + l.base = l.len; + l.tap_rows = 1; + l.tap_row0 = 0; try b.m.forward(b.k, b.s, &.{token}, l.len, 0, 1, false); l.len += 1; const h = b.next; @@ -297,6 +346,8 @@ pub const Backend = struct { try l.rows.append(b.gpa, w.pending); try l.rows.appendSlice(b.gpa, w.tokens); for (w.positions, 0..) |position, r| if (position != l.base + r + 1) return error.PositionMismatch; + l.tap_row0 = total; + l.tap_rows = n; chains[i] = .{ .slot = b.m.slot, .p0 = l.base, .tokens = l.rows.items }; total += n; } @@ -347,10 +398,17 @@ pub const Backend = struct { } pub fn restoreState(b: *Backend, owner: ?*anyopaque, saved: *const Model.Saved) !void { - const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); + const s: *lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoOwner)); const l = try b.laneOf(s); try b.m.restore(b.s, saved); l.len = saved.at; + if (l.fill != null) { + l.fill = saved.at; + s.fill_at.store(saved.at, .monotonic); + } + l.base = 0; + l.tap_rows = 0; + l.tap_row0 = 0; } pub fn dropState(b: *Backend, saved: *Model.Saved) void { diff --git a/zig/src/families/inkling2/loop_engine.zig b/zig/src/families/inkling2/loop_engine.zig index fd69bcd7a1b..836c0dc9b05 100644 --- a/zig/src/families/inkling2/loop_engine.zig +++ b/zig/src/families/inkling2/loop_engine.zig @@ -9,6 +9,7 @@ const attention = @import("kernels.zig"); const modelopt = @import("modelopt.zig"); const loop_math = @import("loop_math_cuda.zig"); const round = @import("loop_round.zig"); +const dspark = @import("dspark.zig"); pub const prompt_rows: usize = 2048; pub const window_rows: usize = 16; @@ -22,6 +23,7 @@ pub const Kernels = struct { loop: loop_math.Kernels, sample_mod: cuda.Module, draws: cuda.sample.Draws, + draft: ?dspark.Kernels = null, pub fn load(ctx: *const cuda.Context) !Kernels { const d = ctx.d; @@ -48,6 +50,7 @@ pub const Kernels = struct { pub fn deinit(k: *Kernels) void { k.sample_mod.unload(); + if (k.draft) |*draft| draft.unload(); k.loop.unload(); k.moe.unload(); k.attn.unload(); @@ -97,6 +100,7 @@ const Scratch = struct { moe_scratch: u64, hidden: u64, logits: u64, + taps: u64 = 0, // allocated only when a DSpark drafter attaches }; /// A stream's state (every visit's K/V rows and conv states, its rewind sites, its window's backup and history). @@ -294,6 +298,10 @@ pub const Model = struct { return m; } + pub fn prepareTaps(m: *Model) !void { + if (m.s.taps == 0) m.s.taps = try m.alloc(prompt_rows * dspark.taps.len * m.w.c.text.hidden * 2); + } + fn deinitBuffers(m: *Model) void { for (m.buffers.items) |*b| b.free(); m.buffers.deinit(m.gpa); diff --git a/zig/src/families/inkling2/loop_round.zig b/zig/src/families/inkling2/loop_round.zig index 22ac57aa41a..f4ed5b1af02 100644 --- a/zig/src/families/inkling2/loop_round.zig +++ b/zig/src/families/inkling2/loop_round.zig @@ -7,6 +7,7 @@ const attention = @import("kernels.zig"); const modelopt = @import("modelopt.zig"); const loop_math = @import("loop_math_cuda.zig"); const engine = @import("loop_engine.zig"); +const dspark = @import("dspark.zig"); const Model = engine.Model; const Kernels = engine.Kernels; @@ -81,7 +82,10 @@ pub fn forward(m: *Model, k: *const Kernels, s: cuda.Stream, chains: []const Cha var n_blocks: usize = 0; const lp = c.loop.?; - for (m.w.p.visits[0..m.w.p.n_visits]) |visit| { + for (m.w.p.visits[0..m.w.p.n_visits], 0..) |visit, vi| { + if (m.s.taps != 0) for (dspark.taps[0 .. dspark.taps.len - 1], 0..) |tap, channel| { + if (vi == tap) try @import("dspark_ops.zig").miniTap(&k.draft.?, s, partial, m.s.taps, rows, channel, h); + }; const layer = m.w.p.at(visit.layer); const lw = &m.w.layers[visit.layer]; if (visit.pass >= 2 and visit.layer == lp.core_start) { @@ -230,8 +234,10 @@ pub fn forward(m: *Model, k: *const Kernels, s: cuda.Stream, chains: []const Cha } } - if (heads == 0) return; + if (heads == 0 and m.s.taps == 0) return; try ops.mix(&k.glue, s, m.mixArgs(m.s.blocks[0..n_blocks], partial, m.w.output_query, .{ m.w.norm, m.w.norm, m.w.norm }, m.s.hidden, 1, true, rows)); + if (m.s.taps != 0) try @import("dspark_ops.zig").miniTap(&k.draft.?, s, m.s.hidden, m.s.taps, rows, dspark.taps.len - 1, h); + if (heads == 0) return; try ops.rowdot(&k.glue, s, m.s.hidden + head0 * h * 2, m.w.unembed, m.s.logits, heads, c.unpadded_vocab, h, false, false); try loop_math.roundBf16(&k.loop, s, m.s.logits, m.s.logits, heads * c.unpadded_vocab); try ops.softcap(&k.glue, s, m.s.logits, heads * c.unpadded_vocab, c.logit_cap); diff --git a/zig/tests/cuda/contract_inkling2.zig b/zig/tests/cuda/contract_inkling2.zig index 1ab486edf31..37ca77baf80 100644 --- a/zig/tests/cuda/contract_inkling2.zig +++ b/zig/tests/cuda/contract_inkling2.zig @@ -9,6 +9,7 @@ pub const Set = struct { gpa: std.mem.Allocator, attn: @import("contract_inkling2_attn.zig").Set = .{}, ops: @import("contract_inkling2_ops.zig").Set = .{}, + dspark: @import("contract_inkling2_dspark.zig").Set = .{}, experts: @import("contract_inkling2_experts.zig").Set = .{}, loop_math: @import("contract_inkling2_loop_math_extra.zig").Set = .{}, @@ -21,6 +22,8 @@ pub const Set = struct { errdefer set.attn.deinit(); try set.ops.init(gpu, s, a, list); errdefer set.ops.deinit(); + try set.dspark.init(gpu, s, a, list); + errdefer set.dspark.deinit(); try set.experts.init(gpu, s, a, list); errdefer set.experts.deinit(); try set.loop_math.init(gpu, s, a, list); @@ -30,6 +33,7 @@ pub const Set = struct { pub fn deinit(set: *Set) void { set.loop_math.deinit(); set.experts.deinit(); + set.dspark.deinit(); set.ops.deinit(); set.attn.deinit(); set.gpa.destroy(set); diff --git a/zig/tests/cuda/contract_inkling2_dspark.zig b/zig/tests/cuda/contract_inkling2_dspark.zig new file mode 100644 index 00000000000..15606ee1dda --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_dspark.zig @@ -0,0 +1,97 @@ +//! Inkling 2's DSpark drafter glue (inkling2/dspark.cu) under the contract, with controls. +const std = @import("std"); +const cuda = @import("cuda"); +const check = @import("check.zig"); +const g = @import("core").contract.gates; +const dk = @import("inkling2").dspark_ops; +const ref = @import("contract_minimax_glue_ref.zig"); +const norm = @import("contract_inkling2_dspark_norm.zig"); +const attn = @import("contract_inkling2_dspark_attn.zig"); +const head = @import("contract_inkling2_dspark_head.zig"); +const glue = @import("contract_inkling2_dspark_glue.zig"); +const pick = @import("contract_inkling2_ops_pick.zig"); +const opsref = @import("contract_inkling2_ops_ref.zig"); +const bm = @import("contract_inkling2_dspark_many.zig"); +const mini = @import("contract_inkling2_dspark_mini.zig"); + +/// The drafter's registrations, each control after the kernel it breaks (the caller's heap set holds them). +pub const Set = struct { + k: dk.Kernels = undefined, + mixes: [2]ref.Gated(norm.Mix) = undefined, + adds: [3]ref.Gated(norm.AddNorm) = undefined, + qks: [3]ref.Gated(norm.Qk) = undefined, + attends: [2]attn.Attend = undefined, + merges: [2]ref.Gated(attn.Merge) = undefined, + silus: [2]ref.Gated(glue.Silu) = undefined, + ctxs: [2]ref.Gated(head.Ctx) = undefined, + rnns: [2]ref.Gated(head.Rnn) = undefined, + vocabs: [4]head.Banded(head.Vocab) = undefined, + picks: [4]ref.Checked(glue.Pick) = undefined, + // Mini's batched pass (dspark_many.cuh), each with the control of the kernel it copies + qkms: [3]ref.Gated(norm.Qk) = undefined, + attms: [2]attn.Attend = undefined, + ctxms: [2]ref.Gated(head.Ctx) = undefined, + rnnms: [2]ref.Gated(head.Rnn) = undefined, + top1ms: [2]opsref.Checked(pick.Top1) = undefined, + racems: [2]opsref.Checked(pick.Race) = undefined, + // the batched kernels over 3+ streams against each stream's one-stream launch, each with a table or stride fault + twins: [8]bm.Many = undefined, + mini_taps: [2]ref.Checked(mini.Tap) = undefined, + mini_hiddens: [2]ref.Gated(mini.Hidden) = undefined, + + pub fn init(set: *Set, gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !void { + set.k = try dk.Kernels.load(gpu.d); + errdefer set.k.unload(); + const k = &set.k; + const rig: @import("contract_rig.zig").Rig = .{ .gpu = gpu, .s = s }; + for (&set.mixes, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .drop = i == 1 } }; + for (&set.adds, [_]norm.View{ .resid, .normed, .normed }, 0..) |*x, v, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .view = v, .short = i == 2 } }; + for (&set.qks, [_]norm.Form{ .draft, .absorb, .draft }, 0..) |*x, f, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .form = f, .late = i == 2 } }; + for (&set.attends, 0..) |*x, i| x.* = .{ .rig = rig, .k = k, .late = i == 1 }; + for (&set.merges, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .short = i == 1 } }; + for (&set.silus, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .swapped = i == 1 } }; + for (&set.ctxs, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .early = i == 1 } }; + for (&set.rnns, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .late = i == 1 } }; + for (&set.vocabs, 0..) |*x, i| x.* = .{ .inner = .{ .rig = rig, .k = .{ .kern = k, .short = i % 2 == 1, .rows = i >= 2 } } }; + for (&set.picks, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .alone = i % 2 == 1, .rows = i >= 2 } }; + for (&set.qkms, [_]norm.Form{ .draft, .absorb, .draft }, 0..) |*x, f, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .form = f, .late = i == 2, .many = true } }; + for (&set.attms, 0..) |*x, i| x.* = .{ .rig = rig, .k = k, .late = i == 1, .many = true }; + for (&set.ctxms, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .early = i == 1, .many = true } }; + for (&set.rnnms, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .late = i == 1, .many = true } }; + for (&set.top1ms, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = undefined, .short = i == 1, .many = k } }; + for (&set.racems, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = undefined, .late = i == 1, .many = k } }; + for (&set.twins, 0..) |*x, i| x.* = .{ .rig = rig, .k = k, .kind = @fromBackingInt(@intCast(i / 2)), .fault = i % 2 == 1, .arena = .init(gpu.gpa) }; + for (&set.mini_taps, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .fault = i == 1 } }; + for (&set.mini_hiddens, 0..) |*x, i| x.* = .{ .rig = rig, .k = .{ .kern = k, .fault = i == 1 } }; + for (&set.mixes) |*x| try list.append(a, x.kernel()); + for (&set.adds) |*x| try list.append(a, x.kernel()); + for (&set.qks) |*x| try list.append(a, x.kernel()); + for (&set.attends) |*x| try list.append(a, x.kernel()); + for (&set.merges) |*x| try list.append(a, x.kernel()); + for (&set.silus) |*x| try list.append(a, x.kernel()); + for (&set.ctxs) |*x| try list.append(a, x.kernel()); + for (&set.rnns) |*x| try list.append(a, x.kernel()); + for (&set.vocabs) |*x| try list.append(a, x.kernel()); + for (&set.picks) |*x| try list.append(a, x.kernel()); + inline for (.{ "qkms", "attms", "ctxms", "rnnms", "top1ms", "racems", "twins" }) |f| for (&@field(set, f)) |*x| try list.append(a, x.kernel()); + for (&set.mini_taps) |*x| try list.append(a, x.kernel()); + for (&set.mini_hiddens) |*x| try list.append(a, x.kernel()); + } + + pub fn deinit(set: *Set) void { + for (&set.mixes) |*x| x.deinit(); + for (&set.adds) |*x| x.deinit(); + for (&set.qks) |*x| x.deinit(); + for (&set.attends) |*x| x.deinit(); + for (&set.merges) |*x| x.deinit(); + for (&set.silus) |*x| x.deinit(); + for (&set.ctxs) |*x| x.deinit(); + for (&set.rnns) |*x| x.deinit(); + for (&set.vocabs) |*x| x.deinit(); + for (&set.picks) |*x| x.deinit(); + inline for (.{ "qkms", "attms", "ctxms", "rnnms", "top1ms", "racems", "twins" }) |f| for (&@field(set, f)) |*x| x.deinit(); + for (&set.mini_taps) |*x| x.deinit(); + for (&set.mini_hiddens) |*x| x.deinit(); + set.k.unload(); + } +}; diff --git a/zig/tests/cuda/contract_inkling2_dspark_attn.zig b/zig/tests/cuda/contract_inkling2_dspark_attn.zig new file mode 100644 index 00000000000..0833a3b1019 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_dspark_attn.zig @@ -0,0 +1,344 @@ +//! Inkling 2's DSpark block attention under the contract: tf_ink2_dsp_attn with its merge, and the merge alone. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const dk = @import("inkling2").dspark_ops; +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const sumIn = contract.rows.sumIn; +const Iv = ref.Iv; +const Sums = ref.Sums; +const D = 128; +const T = 8; // a block's rows +const hk = 4; // a TP=2 rank's key heads, 6 query heads each +const hq = 24; +const grp = hq / hk; +const scale: f32 = 1.0 / @sqrt(@as(f32, D)); // as the drafter passes it +const soft_why = "online softmax over 32-key tiles in fp32 (expf rescales): no input makes its sums exact in fp32"; + +/// A key's 128 products, then the row's keys, each tile's rescale and the chunks' merge. +fn attnDepth(s: c.Shape) usize { + return D + s.k + s.k / 32 + 16; +} + +/// T rows x 24 heads x 128 dims x the keys every row sees: a first block, a sliding window, a global prefix, 1M's edge. +pub fn attnSpec(late: bool, many: bool) c.Spec { + const served = &[_]c.Shape{ .{ .rows = T, .n = hq * D, .k = 8 }, .{ .rows = T, .n = hq * D, .k = 1032 }, .{ .rows = T, .n = hq * D, .k = 3000 }, .{ .rows = T, .n = hq * D, .k = 2500 } }; + const one = if (late) "inkling2 dspark control: block attention starts a key late" else "inkling2 dspark tf_ink2_dsp_attn + tf_ink2_dsp_merge (a block over keys [lo, hi])"; + const batched = if (late) "inkling2 dspark control: tf_ink2_dsp_attn_many starts a key late" else "inkling2 dspark tf_ink2_dsp_attn_many + tf_ink2_dsp_merge_many (a stream's block from the table)"; + const name = if (many) batched else one; + return .{ .name = name, .accum = .f32, .depth = attnDepth, .ops = 8, .out = .bf16, .served = served, .sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = soft_why } }; +} + +/// The window a shape's key count stands for: [lo, hi] and the ring the cache holds its keys in. +const Window = struct { lo: usize, hi: usize, ring: usize }; + +fn windowOf(keys: usize) Window { + return switch (keys) { + 1032 => .{ .lo = 68_976, .hi = 70_007, .ring = 4096 }, // a sliding layer at 70,000: the window wraps the ring + 2500 => .{ .lo = 1_046_076, .hi = 1_048_575, .ring = 8192 }, // the global layer's last chunks at 1M + else => .{ .lo = 0, .hi = keys - 1, .ring = 4096 }, + }; +} + +/// One block's queries over a key and value cache (the ring as the draft slot holds it). +pub const Attend = struct { + rig: rig_.Rig, + k: *const dk.Kernels, + /// control: the window starts one key late on the device (the reference keeps its first key) + late: bool = false, + /// tf_ink2_dsp_attn_many + tf_ink2_dsp_merge_many: one stream's block, its window and caches from a table + many: bool = false, + tab: u64 = 0, + st: [1]dk.Stream = .{.{}}, + shape: c.Shape = undefined, + win: Window = undefined, + q: []u16 = &.{}, + keys: []u16 = &.{}, // [ring][hk][D] + values: []u16 = &.{}, + tol: []f64 = &.{}, + in: [3]u64 = @splat(0), + po: u64 = 0, + pml: u64 = 0, + out: u64 = 0, + + pub fn deinit(self: *Attend) void { + self.free(); + self.rig.deinit(); + } + + fn free(self: *Attend) void { + const a = self.rig.gpu.gpa; + inline for (.{ "q", "keys", "values" }) |name| { + a.free(@field(self, name)); + @field(self, name) = &.{}; + } + a.free(self.tol); + self.tol = &.{}; + } + + pub fn kernel(self: *Attend) g.Kernel { + return .{ .spec = attnSpec(self.late, self.many), .ctx = self, .vt = &vt, .control = if (self.late) .shapes else null }; + } + + const vt = g.hooks(Attend); + + /// q in [-4, 4) (peaked: a lost key shows), k and v in [-1, 1); stress: 1/8 steps; non-finite: NaN q, inf k. + pub fn prepare(self: *Attend, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.n != hq * D or shape.rows == 0 or shape.rows > T or shape.k == 0) return false; + self.free(); + self.rig.reset(); + self.shape = shape; + self.win = windowOf(shape.k); + const a = self.rig.gpu.gpa; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + self.q = try a.alloc(u16, shape.rows * hq * D); + self.keys = try a.alloc(u16, self.win.ring * hk * D); + self.values = try a.alloc(u16, self.win.ring * hk * D); + for (self.q) |*v| v.* = c.toBf16(if (fill == .stress) 4 * grid(rng) else (rng.float(f32) * 2 - 1) * 4); + for ([_][]u16{ self.keys, self.values }) |x| for (x) |*v| { + v.* = c.toBf16(if (fill == .stress) grid(rng) else rng.float(f32) * 2 - 1); + }; + if (fill == .nonfinite) { + self.q[3] = c.toBf16(ref.nan); // row 0, head 0 + self.keys[((self.win.lo + 2) % self.win.ring * hk + 1) * D + 5] = c.toBf16(ref.inf); // key head 1, key 3 + } + self.in = .{ try self.rig.input(std.mem.sliceAsBytes(self.q)), try self.rig.input(std.mem.sliceAsBytes(self.keys)), try self.rig.input(std.mem.sliceAsBytes(self.values)) }; + const n = dk.chunks(self.win.lo, self.win.hi); + self.po = try self.rig.scratch(n * shape.rows * hq * D * 4); + self.pml = try self.rig.scratch(n * shape.rows * hq * 2 * 4); + self.out = try self.rig.output(shape.rows * hq * D * 2); + if (self.many) { + self.st[0] = .{ .p = @intCast(self.win.hi + 1 - shape.rows) }; + self.st[0].kc[0] = self.in[1]; + self.st[0].vc[0] = self.in[2]; + self.st[0].lo[0] = @intCast(self.win.lo + @intFromBool(self.late)); + self.tab = try self.rig.input(std.mem.sliceAsBytes(&self.st)); + } + return true; + } + + /// A value on a 1/8 grid in [-1, 1]: bf16-exact, so stress sums start from exact inputs. + fn grid(rng: std.Random) f32 { + return @as(f32, @floatFromInt(@as(i32, @intCast(rng.uintLessThan(u32, 17))) - 8)) / 8; + } + + pub fn run(self: *Attend) !void { + const w = self.win; + if (self.many) { + try dk.attendMany(self.k, self.rig.s, .{ .q = self.in[0], .kc = 0, .vc = 0, .po = self.po, .pml = self.pml, .T = @intCast(self.shape.rows), .hq = hq, .hk = hk, .ring = @intCast(w.ring), .lo = 0, .hi = 0, .c0 = 0, .scale = scale }, .{ .dev = self.tab, .host = &self.st }, 0, dk.chunks(w.lo, w.hi), dk.chunks(w.lo, w.hi), self.out); + return self.rig.s.synchronize(); + } + try dk.attend(self.k, self.rig.s, .{ .q = self.in[0], .kc = self.in[1], .vc = self.in[2], .po = self.po, .pml = self.pml, .T = @intCast(self.shape.rows), .hq = hq, .hk = hk, .ring = @intCast(w.ring), .lo = @intCast(w.lo + @intFromBool(self.late)), .hi = @intCast(w.hi), .c0 = 0, .scale = scale }, self.out); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Attend) usize { + return self.shape.rows * hq * D; + } + + fn at(self: *const Attend, x: []const u16, key: usize, h: usize, d: usize) f64 { + return c.fromBf16(x[((key % self.win.ring) * hk + h) * D + d]); + } + + /// Row r, head h's softmax(q k scale) v over [lo, hi], sums in `acc` (null: f64); `tol`: fp32 dots, exp, rescales. + fn attend(self: *Attend, r: usize, h: usize, acc: ?c.Accum, order: g.Order, o: []f64, tol: ?[]f64) !void { + const a = self.rig.gpu.gpa; + const kv = h / grp; + const lo = self.win.lo; + const n = self.win.hi + 1 - lo; + const s = try a.alloc(f64, 4 * n); + defer a.free(s); + const ds = s[n .. 2 * n]; + const p = s[2 * n .. 3 * n]; + const col = s[3 * n ..]; + var terms: [D]f64 = undefined; + var most = -std.math.inf(f64); + const sc: f64 = scale; + const qr = self.q[(r * hq + h) * D ..][0..D]; + for (0..n) |i| { + var abs: f64 = 0; + for (&terms, qr, 0..) |*x, qv, d| { + x.* = @as(f64, c.fromBf16(qv)) * self.at(self.keys, lo + i, kv, d); + abs += @abs(x.*); + } + s[i] = (if (acc) |k| sumIn(k, order, &terms) else sumIn(.none, .sequential, &terms)) * sc; + ds[i] = (abs * sc * (D + 2) + @abs(s[i]) * 2) * 0x1p-24 + 0x1p-60; + most = maxNan(most, s[i]); + } + for (p, s[0..n]) |*x, v| x.* = @exp(v - most); + const l = if (acc) |k| sumIn(k, order, p) else sumIn(.none, .sequential, p); + // fp32 sums of p and p v, a rescale a 32-key tile and one a chunk, each expf (2 ulps) of a rounded gap + const chain = @as(f64, @floatFromInt(n + 12 * (n / 32 + 1) + 12 * dk.chunks(lo, self.win.hi) + 32)) * 0x1p-24; + for (o, 0..) |*od, d| { + var spread: f64 = 0; + for (col, p, ds, s[0..n], 0..) |*x, w, e, sv, i| { + const v = self.at(self.values, lo + i, kv, d); + x.* = w * v; + spread += w * @abs(v) * (2 * e + @abs(sv - most) * 0x1p-23 + 0x1p-22 + chain); + } + od.* = (if (acc) |k| sumIn(k, order, col) else sumIn(.none, .sequential, col)) / l; + if (tol) |t| t[d] = @abs(od.*) * (0x1p-8 + chain) + spread / l + 0x1p-120; + } + } + + /// float64 o = sum p v / sum p, p = exp(s - max), over every key in [lo, hi]; bound as attend states. + pub fn reference(self: *Attend, want: []f64, mag: []f64) !void { + const a = self.rig.gpu.gpa; + a.free(self.tol); + self.tol = try a.alloc(f64, want.len); + for (0..self.shape.rows) |r| for (0..hq) |h| { + const o = (r * hq + h) * D; + try self.attend(r, h, null, .sequential, want[o..][0..D], self.tol[o..][0..D]); + }; + for (mag, want) |*m, w| m.* = @abs(w); + } + + pub fn bounds(self: *Attend, _: []const f64, _: []const f64, allow: []f64) !void { + for (allow, self.tol) |*l, t| l.* = if (std.math.isFinite(t)) t else std.math.floatMax(f64); + } + + pub fn simulate(self: *Attend, acc: c.Accum, order: g.Order, out: []f64) !void { + for (0..self.shape.rows) |r| for (0..hq) |h| { + const o = (r * hq + h) * D; + try self.attend(r, h, acc, order, out[o..][0..D], null); + for (out[o..][0..D]) |*v| v.* = c.fromBf16(c.toBf16(@floatCast(v.*))); + }; + } +}; + +/// max that keeps a NaN, as float64 arithmetic on the formula would. +fn maxNan(x: f64, y: f64) f64 { + return if (std.math.isNan(x) or std.math.isNan(y)) std.math.nan(f64) else @max(x, y); +} + +/// (row, head) pairs x 128 dims x chunks: a block's 192 pairs over 2-3 chunks, a 1M context's 1,025, one chunk. +pub fn mergeSpec(short: bool) c.Spec { + const served = &[_]c.Shape{ .{ .rows = T * hq, .n = D, .k = 2 }, .{ .rows = T * hq, .n = D, .k = 1025 }, .{ .rows = T * hq, .n = D, .k = 3 }, .{ .rows = T * hq, .n = D, .k = 1 } }; + const name = if (short) "inkling2 dspark control: the merge folds one chunk short" else "inkling2 dspark tf_ink2_dsp_merge (chunks folded in order)"; + return .{ .name = name, .accum = .f32, .depth = mergeDepth, .out = .bf16, .served = served, .sums = .{} }; +} + +fn mergeDepth(s: c.Shape) usize { + return s.k + 1; +} + +/// out = bf16(sum_c po_c w_c / sum_c l_c w_c), w_c = exp(m_c - max) (0 for an empty chunk, m -inf), max by fmaxf. +pub const Merge = struct { + kern: *const dk.Kernels, + /// control: launched over one chunk fewer + short: bool = false, + shape: c.Shape = undefined, + po: []f32 = &.{}, + pml: []f32 = &.{}, + in: [2]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const Merge) c.Spec { + return mergeSpec(self.short); + } + + pub fn control(self: *const Merge) ?g.Gate { + return if (self.short) .shapes else null; + } + + pub fn free(self: *Merge, a: std.mem.Allocator) void { + a.free(self.po); + a.free(self.pml); + self.po = &.{}; + self.pml = &.{}; + } + + /// Chunk maxima in [-4, 4) (one chunk in 7 empty), totals in [1, 64), sums within them; stress: maxima 0, integers. + pub fn prepare(self: *Merge, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != D or shape.k == 0) return false; + self.free(a); + self.shape = shape; + const nqt = shape.rows; + const ch = shape.k; + self.po = try a.alloc(f32, ch * nqt * D); + self.pml = try a.alloc(f32, ch * nqt * 2); + const half = (ch - 1) / 2; + for (0..ch) |cc| for (0..nqt) |rh| { + const ml = self.pml[(cc * nqt + rh) * 2 ..][0..2]; + const row = self.po[(cc * nqt + rh) * D ..][0..D]; + if (fill == .stress) { + ml.* = .{ 0, ref.int(rng, 1, 1000) }; + for (row) |*v| v.* = ref.int(rng, 1, 1000); + continue; + } + const empty = ch > 1 and cc % 7 == 3; + ml.* = if (empty) .{ -ref.inf, 0 } else .{ rng.float(f32) * 8 - 4, 1 + rng.float(f32) * 63 }; + for (row) |*v| v.* = if (empty) 0 else (rng.float(f32) * 2 - 1) * ml[1]; + }; + if (fill == .stress) for (0..half) |cc| for (0..nqt) |rh| for (0..D) |d| { + const mirror = half + (cc + 1) % half; // one step apart, so no replay cancels exactly + self.po[(mirror * nqt + rh) * D + d] = -self.po[(cc * nqt + rh) * D + d] + @as(f32, if (cc == 0 and d % 5 == 1) 1 else 0); + }; + if (fill == .nonfinite) { + self.po[3] = ref.nan; // pair 0, chunk 0 + self.pml[1 * 2] = ref.nan; // pair 1's chunk 0 maximum: its weight NaN + if (ch > 1) self.po[(nqt + 2) * D + 5] = ref.inf; // pair 2, chunk 1 + self.pml[3 * 2 + 1] = ref.inf; // pair 3's chunk 0 total: its every output 0 + } + self.in = .{ try ref.input(rig, self.po), try ref.input(rig, self.pml) }; + self.out = try rig.output(nqt * D * 2); + return true; + } + + pub fn run(self: *Merge, rig: *rig_.Rig) !void { + var m: cuda.Args = .{}; + m.add(self.in[0]); + m.add(self.in[1]); + m.add(@as(i32, @intCast(self.shape.k - @intFromBool(self.short)))); + m.add(@as(i32, @intCast(self.shape.rows))); + m.add(self.out); + try cuda.launch.launch(self.kern.merge, .{ .grid = .{ .x = @intCast(self.shape.rows) }, .block = .{ .x = 128 } }, rig.s, &m); + } + + pub fn count(self: *const Merge) usize { + return self.shape.rows * D; + } + + pub fn solve(self: *const Merge, a: std.mem.Allocator, s: Sums, out: []Iv) !void { + const nqt = self.shape.rows; + const ch = self.shape.k; + const buf = try a.alloc(Iv, 3 * ch); + defer a.free(buf); + const wt = buf[0..ch]; + const terms = buf[ch .. 2 * ch]; + const ls = buf[2 * ch ..]; + const scratch = try a.alloc(f64, ch); + defer a.free(scratch); + for (0..nqt) |rh| { + var mx = -std.math.inf(f64); + for (0..ch) |cc| { + const m: f64 = self.pml[(cc * nqt + rh) * 2]; + if (!std.math.isNan(m)) mx = @max(mx, m); // fmaxf: a NaN maximum is passed over + } + for (wt, 0..) |*w, cc| { + const m: f64 = self.pml[(cc * nqt + rh) * 2]; + w.* = if (m == -std.math.inf(f64)) Iv.of(0) else if (m == mx) Iv.of(1) else Iv.of(m).sub(Iv.of(mx)).exp(); + } + for (ls, wt, 0..) |*t, w, cc| t.* = weigh(Iv.of(self.pml[(cc * nqt + rh) * 2 + 1]), w); + const l = s.sum(ls, ch, scratch); + for (0..D) |d| { + for (terms, wt, 0..) |*t, w, cc| t.* = weigh(Iv.of(self.po[(cc * nqt + rh) * D + d]), w); + out[rh * D + d] = s.sum(terms, ch, scratch).div(l).bf(); + } + } + } + + /// x w in fp32: exact where w is 0 or 1 (exp(0) and an empty chunk), else one rounding. + fn weigh(x: Iv, w: Iv) Iv { + if (w.lo == w.hi and (w.m == 0 or w.m == 1)) return Iv.of(x.m * w.m); + return x.mul(w); + } +}; diff --git a/zig/tests/cuda/contract_inkling2_dspark_glue.zig b/zig/tests/cuda/contract_inkling2_dspark_glue.zig new file mode 100644 index 00000000000..458b7580aff --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_dspark_glue.zig @@ -0,0 +1,198 @@ +//! The DSpark SiLU, core's tf_swiglu_rows_expf, and the ranks' pick, tf_ink2_dsp_pick_merge, under the contract. +const std = @import("std"); +const core = @import("core"); +const dk = @import("inkling2").dspark_ops; +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Iv = ref.Iv; +const Sums = ref.Sums; + +const inter = 9216; // a TP=2 rank's FFN columns (18,432 / 2) + +/// A block's 8 rows x this rank's FFN columns: no sums. +pub fn siluSpec(swapped: bool) c.Spec { + const served = &[_]c.Shape{.{ .rows = 8, .n = inter, .k = 1 }}; + const name = if (swapped) "inkling2 dspark control: SiLU reads up as gate and gate as up" else "inkling2 dspark act_rows tf_swiglu_rows_expf (silu(gate) * up in fp32, rounded once)"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .bf16, .served = served }; +} + +/// out = bf16(g / (1 + expf(-g)) * u), gu bf16 [rows][2I] (gates, then ups). +pub const Silu = struct { + kern: *const dk.Kernels, + /// control: the device's rows hold ups then gates (the reference keeps gates first) + swapped: bool = false, + shape: c.Shape = undefined, + gu: []u16 = &.{}, + in: u64 = 0, + out: u64 = 0, + + pub fn spec(self: *const Silu) c.Spec { + return siluSpec(self.swapped); + } + + pub fn control(self: *const Silu) ?g.Gate { + return if (self.swapped) .shapes else null; + } + + pub fn free(self: *Silu, a: std.mem.Allocator) void { + a.free(self.gu); + self.gu = &.{}; + } + + /// Gates in [-8, 8), ups in [-4, 4); non-finite: a NaN gate, -Inf (silu NaN) and +Inf gates, an infinite up. + pub fn prepare(self: *Silu, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + self.free(a); + self.shape = shape; + const n = shape.n; + self.gu = try a.alloc(u16, shape.rows * 2 * n); + for (0..shape.rows) |r| for (0..n) |i| { + self.gu[r * 2 * n + i] = c.toBf16(rng.float(f32) * 16 - 8); + self.gu[r * 2 * n + n + i] = c.toBf16(rng.float(f32) * 8 - 4); + }; + if (fill == .nonfinite) { + const at = [_][2]usize{ .{ 0, 3 }, .{ 1, n / 2 }, .{ 2, n - 1 }, .{ 3, 2 * n - 1 } }; + const put = [_]f32{ ref.nan, -ref.inf, ref.inf, ref.inf }; + for (at, put) |p, v| if (p[0] < shape.rows) { + self.gu[p[0] * 2 * n + p[1]] = c.toBf16(v); + }; + } + const dev = try a.dupe(u16, self.gu); + defer a.free(dev); + if (self.swapped) for (0..shape.rows) |r| for (0..n) |i| { + std.mem.swap(u16, &dev[r * 2 * n + i], &dev[r * 2 * n + n + i]); + }; + self.in = try ref.input(rig, dev); + self.out = try rig.output(shape.rows * n * 2); + return true; + } + + pub fn run(self: *Silu, rig: *rig_.Rig) !void { + try dk.silu(self.kern, rig.s, self.in, self.out, self.shape.rows, self.shape.n); + } + + pub fn count(self: *const Silu) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Silu, _: std.mem.Allocator, _: Sums, out: []Iv) !void { + const n = self.shape.n; + for (0..self.shape.rows) |r| for (0..n) |i| { + const x = Iv.of(ref.bf(self.gu[r * 2 * n + i])); + const u = Iv.of(ref.bf(self.gu[r * 2 * n + n + i])); + out[r * n + i] = x.div(Iv.of(1).add(x.neg().exp())).mul(u).bf(); + }; + } +}; + +/// The kernel's rule, as the check below applies it independently of the kernel's loop. +const pick_rule = "walk[j + 1]: the largest value over the ranks, the lowest id among equal values (-Inf included); " ++ + "a NaN never wins; with every value NaN the id is 0x7fffffff"; + +/// Drafts (a launch each) x ranks (TP=2) x 1: every rank's (value, id) 16 bytes apart. +pub fn pickSpec(alone: bool, rows: bool) c.Spec { + if (rows) { + const rname = if (alone) "inkling2 dspark control: tf_ink2_dsp_pick_rows reads rank 0's entries alone" else "inkling2 dspark tf_ink2_dsp_pick_rows (every stream's best into its walk)"; + return .{ .name = rname, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = pick_rule }, .served = &.{ .{ .rows = 8, .n = 2, .k = 1 }, .{ .rows = 2, .n = 2, .k = 1 }, .{ .rows = 5, .n = 2, .k = 1 } } }; + } + const name = if (alone) "inkling2 dspark control: the pick reads rank 0's entry alone" else "inkling2 dspark tf_ink2_dsp_pick_merge (the ranks' best into the walk)"; + return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = pick_rule }, .served = &.{ .{ .rows = 7, .n = 2, .k = 1 }, .{ .rows = 1, .n = 2, .k = 1 } } }; +} + +const stride = 16; +const share = 100_608; // rank 1's ids start here + +pub const Pick = struct { + kern: *const dk.Kernels, + /// control: launched with one rank + alone: bool = false, + /// tf_ink2_dsp_pick_rows: the shape's rows as streams (rank q's row r at (q * rows + r) * 16 bytes), one launch + rows: bool = false, + shape: c.Shape = undefined, + vals: []f32 = &.{}, + ids: []i32 = &.{}, + dev: u64 = 0, + out: u64 = 0, + + pub fn spec(self: *const Pick) c.Spec { + return pickSpec(self.alone, self.rows); + } + + pub fn control(self: *const Pick) ?g.Gate { + return if (self.alone) .shapes else null; + } + + pub fn free(self: *Pick, a: std.mem.Allocator) void { + a.free(self.vals); + a.free(self.ids); + self.vals = &.{}; + self.ids = &.{}; + } + + /// Values on quarter steps of [-2, 2) (ties between ranks), rank 1 ahead at draft 0; non-finite: each rule's case. + pub fn prepare(self: *Pick, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != 2) return false; + self.free(a); + self.shape = shape; + const m = shape.rows * 2; + self.vals = try a.alloc(f32, m); + self.ids = try a.alloc(i32, m); + for (self.vals, self.ids, 0..) |*v, *id, i| { + v.* = ref.int(rng, -8, 7) / 4; + id.* = @intCast(rng.uintLessThan(u32, 99_450) + (i % 2) * share); + } + self.vals[1] = self.vals[0] + 0.25; + if (fill == .nonfinite) { + const put = [_][2]f32{ .{ ref.nan, 1 }, .{ ref.inf, ref.inf }, .{ -ref.inf, -ref.inf }, .{ ref.nan, ref.nan }, .{ 0.5, ref.nan } }; + for (put, 0..) |p, r| if (r < shape.rows) { + self.vals[2 * r] = p[0]; + self.vals[2 * r + 1] = p[1]; + }; + if (shape.rows > 1) self.ids[2] = share + 9; // draft 1: both +Inf, rank 1's id the lower + if (shape.rows > 1) self.ids[3] = 7; + } + const bytes = try a.alloc(u8, m * stride); + defer a.free(bytes); + @memset(bytes, 0x5a); + for (self.vals, self.ids, 0..) |v, id, i| { + const at = if (self.rows) (i % 2 * shape.rows + i / 2) * stride else i * stride; + std.mem.writeInt(u32, bytes[at..][0..4], @bitCast(v), .little); + std.mem.writeInt(i32, bytes[at + 4 ..][0..4], id, .little); + } + self.dev = try rig.input(bytes); + self.out = try rig.output((shape.rows + 1) * 4); + return true; + } + + pub fn run(self: *Pick, rig: *rig_.Rig) !void { + const world: usize = if (self.alone) 1 else 2; + if (self.rows) return dk.pickRows(self.kern, rig.s, self.dev, world, self.shape.rows, self.out, 1, 0); + for (0..self.shape.rows) |j| try dk.pick(self.kern, rig.s, self.dev + j * 2 * stride, world, self.out, j); + } + + pub fn count(self: *const Pick) usize { + return (self.shape.rows + 1) * 4; + } + + pub fn check(self: *const Pick, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { + if (ref.readI32(got, 0) != -1) return "walk[0] (the anchor) was written"; + for (0..self.shape.rows) |j| { + const vs = self.vals[2 * j ..][0..2]; + const is = self.ids[2 * j ..][0..2]; + var best: ?f32 = null; + for (vs) |v| if (!std.math.isNan(v)) { + best = if (best) |b| @max(b, v) else v; + }; + var id: i32 = 0x7fffffff; + if (best) |b| for (vs, is) |v, k| if (v == b) { + id = @min(id, k); + }; + const v = ref.readI32(got, j + 1); + if (v != id) return try std.fmt.bufPrint(msg, "draft {d}: id {d} where {d} is due", .{ j, v, id }); + } + return null; + } +}; diff --git a/zig/tests/cuda/contract_inkling2_dspark_head.zig b/zig/tests/cuda/contract_inkling2_dspark_head.zig new file mode 100644 index 00000000000..4b1e3c16d3a --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_dspark_head.zig @@ -0,0 +1,426 @@ +//! Inkling 2's DSpark Markov head under the contract: tf_ink2_dsp_ctx, tf_ink2_dsp_rnn and tf_ink2_dsp_vocab. +const std = @import("std"); +const core = @import("core"); +const dk = @import("inkling2").dspark_ops; +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Iv = ref.Iv; +const Sums = ref.Sums; + +const hidden = 4608; +const R = 256; // the Markov rank +const ld = 2 * R + 2 * hidden; // rnn_proj's row: [state, w1[prev], hidden, f_rnn] +const cap: f32 = 30; // final_logit_softcapping +const prev_rows = 4096; // w1's rows the walk's ids index (the model's: the whole vocabulary) + +/// tanhf (increasing), within libm_ulps. +fn tanh(a: Iv) Iv { + const rel: f64 = ref.libm_ulps * 0x1p-23; + const lo = std.math.tanh(a.lo); + const hi = std.math.tanh(a.hi); + return .{ .m = std.math.tanh(a.m), .lo = lo - @abs(lo) * rel - 0x1p-149, .hi = hi + @abs(hi) * rel + 0x1p-149 }; +} + +/// w x for a bf16 w and a range of bf16 values: every product exact in fp32, so no rounding spread. +fn scaled(x: Iv, w: f64) Iv { + const p = [2]f64{ x.lo * w, x.hi * w }; + return .{ .m = x.m * w, .lo = @min(p[0], p[1]), .hi = @max(p[0], p[1]) }; +} + +/// A kernel's outputs in float64 against the range its fp32 steps allow, where an output may be -Inf by its rule. +pub fn Banded(comptime K: type) type { + return struct { + const Self = @This(); + inner: ref.Gated(K), + rig: *rig_.Rig = undefined, + + pub fn deinit(self: *Self) void { + self.inner.deinit(); + } + + pub fn kernel(self: *Self) g.Kernel { + self.rig = &self.inner.rig; + return .{ .spec = self.inner.k.spec(), .ctx = self, .vt = &vt, .control = self.inner.k.control() }; + } + + const vt = g.hooks(Self); + + pub fn prepare(self: *Self, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + return self.inner.prepare(shape, fill, seed); + } + + pub fn run(self: *Self) !void { + try self.inner.run(); + } + + pub fn count(self: *Self) usize { + return self.inner.count(); + } + + pub fn reference(self: *Self, want: []f64, mag: []f64) !void { + try self.inner.reference(want, mag); + } + + pub fn bounds(self: *Self, want: []const f64, mag: []const f64, allow: []f64) !void { + try self.inner.bounds(want, mag, allow); + } + + pub fn simulate(self: *Self, acc: c.Accum, order: g.Order, out: []f64) !void { + try self.inner.simulate(acc, order, out); + } + }; +} + +/// A lane's chain over the 2 x hidden inputs (a warp an output), the warp's 5 shuffles, the bias. +fn ctxDepth(s: c.Shape) usize { + return (s.k + 31) / 32 + 5; +} + +/// Rows (a block's 7 drafting rows) x 3R outputs x 2 hidden inputs: rnn_proj's last columns on [hidden_row, f_rnn]. +pub fn ctxSpec(early: bool, many: bool) c.Spec { + const served = &[_]c.Shape{ .{ .rows = 7, .n = 3 * R, .k = 2 * hidden }, .{ .rows = 1, .n = 3 * R, .k = 2 * hidden }, .{ .rows = 8, .n = 3 * R, .k = 2 * hidden } }; + const one = if (early) "inkling2 dspark control: the Markov context reads rnn_proj from column 0" else "inkling2 dspark tf_ink2_dsp_ctx (bias + rnn_proj[:, 2R:] . [hidden, f_rnn])"; + const batched = if (early) "inkling2 dspark control: tf_ink2_dsp_ctx_many reads rnn_proj from column 0" else "inkling2 dspark tf_ink2_dsp_ctx_many (a stream's context, its f_rnn from the table)"; + const name = if (many) batched else one; + return .{ .name = name, .accum = .f32, .depth = ctxDepth, .out = .f32, .served = served, .sums = .{} }; +} + +pub const Ctx = struct { + kern: *const dk.Kernels, + /// control: the device's weight pointer 2R columns early, so it reads rnn_proj[:, 0:2C] + early: bool = false, + /// tf_ink2_dsp_ctx_many: one stream, its f_rnn read from a stream table + many: bool = false, + tab: u64 = 0, + shape: c.Shape = undefined, + h: []u16 = &.{}, + frnn: []u16 = &.{}, + w: []u16 = &.{}, + bias: []u16 = &.{}, + in: [4]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const Ctx) c.Spec { + return ctxSpec(self.early, self.many); + } + + pub fn control(self: *const Ctx) ?g.Gate { + return if (self.early) .shapes else null; + } + + pub fn free(self: *Ctx, a: std.mem.Allocator) void { + inline for (.{ "h", "frnn", "w", "bias" }) |f| { + a.free(@field(self, f)); + @field(self, f) = &.{}; + } + } + + /// Weights in [-0.5, 0.5), rows in [-2, 2); stress: integers to 15, f_rnn cancelling the rows one place apart. + pub fn prepare(self: *Ctx, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.rows > 8 or shape.n != 3 * R or shape.k != 2 * hidden) return false; + self.free(a); + self.shape = shape; + const rows = shape.rows; + self.h = try ref.bfs(a, rng, rows * hidden, -2, 2); + self.frnn = try ref.bfs(a, rng, hidden, -2, 2); + self.w = try ref.bfs(a, rng, 3 * R * ld, -0.5, 0.5); + self.bias = try ref.bfs(a, rng, 3 * R, -1, 1); + if (fill == .stress) { + for (0..hidden) |k| { + const v = ref.int(rng, 1, 15); + for (0..rows) |r| self.h[r * hidden + k] = c.toBf16(v); + self.frnn[(k + 1) % hidden] = c.toBf16(-v + @as(f32, if (k < 2) 1 else 0)); + } + for (0..3 * R) |o| for (0..hidden) |k| { + const v = ref.int(rng, 1, 15); + self.w[o * ld + 2 * R + k] = c.toBf16(v); + self.w[o * ld + 2 * R + hidden + (k + 1) % hidden] = c.toBf16(v); + }; + } + if (fill == .nonfinite) { + self.h[11] = c.toBf16(ref.nan); // row 0: every output NaN + self.h[hidden + 7] = c.toBf16(ref.inf); + self.h[3 * hidden - 1] = c.toBf16(-ref.inf); + self.bias[5] = c.toBf16(ref.nan); // output 5 NaN on every row + } + self.in = .{ try ref.input(rig, self.h), try ref.input(rig, self.frnn), try ref.input(rig, self.w), try ref.input(rig, self.bias) }; + self.out = try rig.output(rows * 3 * R * 4); + if (self.many) self.tab = try rig.input(std.mem.asBytes(&dk.Stream{ .frnn = self.in[1] })); + return true; + } + + pub fn run(self: *Ctx, rig: *rig_.Rig) !void { + const w = self.in[2] - @as(u64, if (self.early) 2 * R * 2 else 0); + if (self.many) return dk.ctxMany(self.kern, rig.s, self.in[0], 0, self.tab, w, self.in[3], self.out, 1, self.shape.rows, hidden, R); + try dk.ctx(self.kern, rig.s, self.in[0], self.in[1], w, self.in[3], self.out, self.shape.rows, hidden, R); + } + + pub fn count(self: *const Ctx) usize { + return self.shape.rows * 3 * R; + } + + pub fn solve(self: *const Ctx, a: std.mem.Allocator, s: Sums, out: []Iv) !void { + const terms = try a.alloc(Iv, 2 * hidden); + defer a.free(terms); + const scratch = try a.alloc(f64, 2 * hidden); + defer a.free(scratch); + for (0..self.shape.rows) |r| for (0..3 * R) |o| { + const w = self.w[o * ld + 2 * R ..][0 .. 2 * hidden]; + for (terms[0..hidden], w[0..hidden], self.h[r * hidden ..][0..hidden]) |*t, x, y| t.* = Iv.of(ref.bf(x) * ref.bf(y)); + for (terms[hidden..], w[hidden..], self.frnn) |*t, x, y| t.* = Iv.of(ref.bf(x) * ref.bf(y)); + out[r * 3 * R + o] = s.sum(terms, ctxDepth(self.shape), scratch).add(Iv.of(ref.bf(self.bias[o]))); + }; + } +}; + +/// A lane's 16 products of the 2R inputs, the warp's 5 shuffles, then ctx. +fn rnnDepth(_: c.Shape) usize { + return 16 + 5; +} + +/// Steps (one launch each, the state carried) x R x 2R: one step (gate 4's exact sums), a block's 7. +pub fn rnnSpec(late: bool, many: bool) c.Spec { + const served = &[_]c.Shape{ .{ .rows = 1, .n = R, .k = 2 * R }, .{ .rows = 7, .n = R, .k = 2 * R } }; + const one = if (late) "inkling2 dspark control: the recurrence reads the walk one pick late" else "inkling2 dspark tf_ink2_dsp_rnn (a GRU-style step at the bf16 points)"; + const batched = if (late) "inkling2 dspark control: tf_ink2_dsp_rnn_many reads the walk one pick late" else "inkling2 dspark tf_ink2_dsp_rnn_many (a stream's step, a block a stream)"; + const name = if (many) batched else one; + return .{ .name = name, .accum = .f32, .depth = rnnDepth, .out = .bf16, .in_place = true, .served = served, .sums = .{} }; +} + +/// Each step: raw = ctx + rnn_proj[:, :2R] . [state, w1[walk[j]]], the gates at bf16, the state in place, the latent. +pub const Rnn = struct { + kern: *const dk.Kernels, + /// control: launched on the walk one entry on, so each step reads the next pick's w1 row + late: bool = false, + /// tf_ink2_dsp_rnn_many: one stream a launch, as the batched pass launches it + many: bool = false, + shape: c.Shape = undefined, + ctx: []f32 = &.{}, + w: []u16 = &.{}, + w1: []u16 = &.{}, + walk: []i32 = &.{}, + state: []u16 = &.{}, + in: [4]u64 = @splat(0), + st: u64 = 0, + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const Rnn) c.Spec { + return rnnSpec(self.late, self.many); + } + + pub fn control(self: *const Rnn) ?g.Gate { + return if (self.late) .shapes else null; + } + + pub fn free(self: *Rnn, a: std.mem.Allocator) void { + inline for (.{ "ctx", "w", "w1", "walk", "state" }) |f| { + a.free(@field(self, f)); + @field(self, f) = &.{}; + } + } + + /// ctx in [-2, 2), weights in [-0.1, 0.1), state and w1 in [-1, 1); stress: integers, w1 cancelling the state. + pub fn prepare(self: *Rnn, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != R or shape.k != 2 * R) return false; + self.free(a); + self.shape = shape; + const steps = shape.rows; + self.ctx = try ref.f32s(a, rng, steps * 3 * R, -2, 2); + self.w = try ref.bfs(a, rng, 3 * R * ld, -0.1, 0.1); + self.w1 = try ref.bfs(a, rng, prev_rows * R, -1, 1); + self.state = try ref.bfs(a, rng, R, -1, 1); + self.walk = try a.alloc(i32, steps + 1); + for (self.walk) |*p| p.* = @intCast(rng.uintLessThan(u32, prev_rows)); + if (fill == .stress) { + const prev: usize = @intCast(self.walk[0]); + for (0..R) |k| { + const v = ref.int(rng, 1, 64); + self.state[k] = c.toBf16(v); + self.w1[prev * R + (k + 1) % R] = c.toBf16(-v + @as(f32, if (k == 0) 1 else 0)); + } + for (0..3 * R) |o| for (0..R) |k| { + const v = if (k == 0) ref.int(rng, 1, 2) else ref.int(rng, 1, 64); // raw = w[o][0] + ctx: unsaturated + self.w[o * ld + k] = c.toBf16(v); + self.w[o * ld + R + (k + 1) % R] = c.toBf16(v); + }; + for (self.ctx) |*v| v.* = ref.int(rng, -2, 2); + } + if (fill == .nonfinite) { + self.ctx[5] = ref.nan; // step 0's gate 5: the state's element 5 NaN, then every later output + self.ctx[R + 9] = -ref.inf; // a candidate tanh(-inf) = -1 + self.ctx[2 * R + 7] = ref.inf; // a latent tanh(inf) = 1 + } + self.in = .{ try ref.input(rig, self.ctx), try ref.input(rig, self.w), try ref.input(rig, self.w1), try ref.input(rig, self.walk) }; + self.st = try rig.output(R * 2); + self.out = try rig.output(steps * R * 2); + return true; + } + + pub fn run(self: *Rnn, rig: *rig_.Rig) !void { + try ref.restore(rig, self.st, std.mem.sliceAsBytes(self.state)); // updated in place: every run starts the same + const walk = self.in[3] + @as(u64, @intFromBool(self.late)) * 4; + if (self.many) { + for (0..self.shape.rows) |j| try dk.rnnMany(self.kern, rig.s, self.in[0] + j * 3 * R * 4, 0, self.in[1], self.in[2], walk, 0, j, self.st, self.out + j * R * 2, 1, R, hidden); + return; + } + for (0..self.shape.rows) |j| try dk.rnn(self.kern, rig.s, self.in[0] + j * 3 * R * 4, self.in[1], self.in[2], walk, j, self.st, self.out + j * R * 2, R, hidden); + } + + pub fn count(self: *const Rnn) usize { + return (1 + self.shape.rows) * R; + } + + pub fn solve(self: *const Rnn, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + var st: [R]Iv = undefined; + var terms: [2 * R]Iv = undefined; + var raw: [3 * R]Iv = undefined; + var scratch: [2 * R]f64 = undefined; + for (&st, self.state) |*v, x| v.* = Iv.of(ref.bf(x)); + for (0..self.shape.rows) |j| { + const prev: usize = @intCast(self.walk[j]); + for (&raw, 0..) |*o, i| { + const w = self.w[i * ld ..][0 .. 2 * R]; + for (terms[0..R], w[0..R], st) |*t, x, y| t.* = scaled(y, ref.bf(x)); + for (terms[R..], w[R..], self.w1[prev * R ..][0..R]) |*t, x, y| t.* = Iv.of(ref.bf(x) * ref.bf(y)); + o.* = s.sum(&terms, rnnDepth(self.shape), &scratch).add(Iv.of(self.ctx[j * 3 * R + i])); + } + const lat = out[R + j * R ..][0..R]; + for (0..R) |i| { + const gate = raw[i].bf().sigmoid().bf(); + const cand = tanh(raw[R + i].bf()).bf(); + const keep = gate.mul(st[i]).bf(); + const upd = Iv.of(1).sub(gate).bf().mul(cand).bf(); + st[i] = keep.add(upd).bf(); + lat[i] = tanh(raw[2 * R + i].bf()).bf(); + } + } + @memcpy(out[0..R], &st); + } +}; + +/// A lane's 8 products of the rank-256 dot, the warp's 5 shuffles. +fn vocabDepth(_: c.Shape) usize { + return 8 + 5; +} + +/// TP=2's vocabulary shares: rank 0 holds 100,608 real rows, rank 1 100,480 rows of which 99,450 are real. +fn validOf(n: usize) usize { + return if (n == 100_480) 99_450 else n; +} + +/// Steps (one launch each) x the rank's vocabulary rows x the rank-256 latent. +pub fn vocabSpec(short: bool, rows: bool) c.Spec { + const served = &[_]c.Shape{ .{ .rows = 7, .n = 100_608, .k = R }, .{ .rows = 1, .n = 100_480, .k = R }, .{ .rows = 2, .n = 3000, .k = R } }; + const streams = &[_]c.Shape{ .{ .rows = 8, .n = 100_608, .k = R }, .{ .rows = 2, .n = 100_480, .k = R }, .{ .rows = 5, .n = 3000, .k = R } }; + const name = if (short) "inkling2 dspark control: the vocabulary's last real row taken as padding" else "inkling2 dspark tf_ink2_dsp_vocab (softcap(base + fold . latent), -Inf past the real rows)"; + if (rows) { + const rname = if (short) "inkling2 dspark control: tf_ink2_dsp_vocab_rows told one real row fewer" else "inkling2 dspark tf_ink2_dsp_vocab_rows (every stream's step in one launch)"; + return .{ .name = rname, .accum = .f32, .depth = vocabDepth, .out = .f32, .served = streams, .sums = .{} }; + } + return .{ .name = name, .accum = .f32, .depth = vocabDepth, .out = .f32, .served = served, .sums = .{} }; +} + +/// out = softcap(bf16(base + bf16(fold_bias + fold . latent))) at bf16, -inf at padding rows. +pub const Vocab = struct { + kern: *const dk.Kernels, + /// control: launched with one real row fewer + short: bool = false, + /// tf_ink2_dsp_vocab_rows: the shape's rows as streams, in one launch + rows: bool = false, + shape: c.Shape = undefined, + base: []u16 = &.{}, + latent: []u16 = &.{}, + fold: []u16 = &.{}, + fbias: []u16 = &.{}, + in: [4]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const Vocab) c.Spec { + return vocabSpec(self.short, self.rows); + } + + pub fn control(self: *const Vocab) ?g.Gate { + return if (self.short) .shapes else null; + } + + pub fn free(self: *Vocab, a: std.mem.Allocator) void { + inline for (.{ "base", "latent", "fold", "fbias" }) |f| { + a.free(@field(self, f)); + @field(self, f) = &.{}; + } + } + + /// Base logits in [-40, 40) (past the cap), latents and fold in [-1, 1); stress: integers, halves cancelling. + pub fn prepare(self: *Vocab, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k != R) return false; + self.free(a); + self.shape = shape; + const n = shape.n; + const steps = shape.rows; + self.base = try ref.bfs(a, rng, steps * n, -40, 40); + self.latent = try ref.bfs(a, rng, steps * R, -1, 1); + self.fold = try ref.bfs(a, rng, n * R, -1, 1); + self.fbias = try ref.bfs(a, rng, n, -2, 2); + if (fill == .stress) { + for (self.base) |*v| v.* = c.toBf16(ref.int(rng, -4, 4)); + for (self.fbias) |*v| v.* = c.toBf16(ref.int(rng, -4, 4)); + for (0..steps) |j| for (0..R / 2) |k| { + const v = ref.int(rng, 1, 64); + self.latent[j * R + k] = c.toBf16(v); + self.latent[j * R + R / 2 + (k + 1) % (R / 2)] = c.toBf16(-v + @as(f32, if (k == 0) 1 else 0)); + }; + for (0..n) |v| for (0..R / 2) |k| { + // the dot is fold[v][0]: below the cap's knee + const x = if (k == 0) ref.int(rng, 1, 4) else ref.int(rng, 1, 64); + self.fold[v * R + k] = c.toBf16(x); + self.fold[v * R + R / 2 + (k + 1) % (R / 2)] = c.toBf16(x); + }; + } + if (fill == .nonfinite) { + self.fold[3 * R + 17] = c.toBf16(ref.nan); // row 3: NaN at every step + self.base[5] = c.toBf16(ref.inf); // step 0, row 5: tanh(inf) cap = 30 + self.fbias[7] = c.toBf16(-ref.inf); // row 7: -30 at every step + if (steps > 1) self.latent[R + 9] = c.toBf16(ref.nan); // step 1: every real row NaN + } + self.in = .{ try ref.input(rig, self.base), try ref.input(rig, self.latent), try ref.input(rig, self.fold), try ref.input(rig, self.fbias) }; + self.out = try rig.output(steps * n * 4); + return true; + } + + pub fn run(self: *Vocab, rig: *rig_.Rig) !void { + const n = self.shape.n; + const valid = validOf(n) - @intFromBool(self.short); + if (self.rows) return dk.vocabRows(self.kern, rig.s, self.in[0], n, self.in[1], self.in[2], self.in[3], cap, valid, n, self.shape.rows, self.out); + for (0..self.shape.rows) |j| try dk.vocab(self.kern, rig.s, self.in[0] + j * n * 2, self.in[1] + j * R * 2, self.in[2], self.in[3], cap, valid, n, self.out + j * n * 4); + } + + pub fn count(self: *const Vocab) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Vocab, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + const n = self.shape.n; + const valid = validOf(n); + var terms: [R]Iv = undefined; + var scratch: [R]f64 = undefined; + for (0..self.shape.rows) |j| for (0..n) |v| { + if (v >= valid) { + out[j * n + v] = Iv.of(-std.math.inf(f64)); + continue; + } + for (&terms, self.latent[j * R ..][0..R], self.fold[v * R ..][0..R]) |*t, x, y| t.* = Iv.of(ref.bf(x) * ref.bf(y)); + const b = s.sum(&terms, vocabDepth(self.shape), &scratch).add(Iv.of(ref.bf(self.fbias[v]))).bf(); + const x = Iv.of(ref.bf(self.base[j * n + v])).add(b).bf(); + out[j * n + v] = tanh(x.div(Iv.of(cap))).mul(Iv.of(cap)).bf(); + }; + } +}; diff --git a/zig/tests/cuda/contract_inkling2_dspark_many.zig b/zig/tests/cuda/contract_inkling2_dspark_many.zig new file mode 100644 index 00000000000..2a87708cd97 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_dspark_many.zig @@ -0,0 +1,346 @@ +//! The batched DSpark kernels over several streams: each stream's bytes must equal its own one-stream launch's. +const std = @import("std"); +const core = @import("core"); +const dk = @import("inkling2").dspark_ops; +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +const D = 128; +const T = 8; // a draft block's rows +const hq = 24; // a TP=2 rank's query heads +const hk = 4; +const nqt = T * hq; +const hidden = 4608; +const R = 256; // the Markov rank +const ld = 2 * R + 2 * hidden; // rnn_proj's row +const ring = 4096; // a sliding layer's cache rows +const layer = 3; // a later layer of the table: a launch reading layer 0 finds no caches +const prev_rows = 4096; // w1's rows the walks' ids index +const eps: f32 = 1e-6; +const theta: f32 = 1e6; +const scale: f32 = 1.0 / @sqrt(@as(f32, D)); +const rule = "every stream's bytes equal its own one-stream launch's on that stream's inputs"; + +/// The batched launch a registration checks. +pub const Kind = enum { qk, attn, ctx, rnn }; + +fn noDepth(_: c.Shape) usize { + return 0; +} + +const dw = (hq + 2 * hk) * D; +const aw = 2 * hk * D; +/// rows: streams; n: the call's width; k: the deepest end position, or the rows (ctx) and steps (rnn) a stream. +const qk_served = [_]c.Shape{ .{ .rows = 3, .n = dw, .k = 3007 }, .{ .rows = 4, .n = dw, .k = 70_008 }, .{ .rows = 3, .n = dw, .k = 1_048_576 }, .{ .rows = 3, .n = aw, .k = 2016 }, .{ .rows = 6, .n = aw, .k = 70_001 }, .{ .rows = 4, .n = aw, .k = 1_048_576 } }; +const attn_served = [_]c.Shape{ .{ .rows = 3, .n = hq * D, .k = 3007 }, .{ .rows = 4, .n = hq * D, .k = 70_008 }, .{ .rows = 3, .n = hq * D, .k = 1_048_576 } }; +const ctx_served = [_]c.Shape{ .{ .rows = 3, .n = 3 * R, .k = 7 }, .{ .rows = 4, .n = 3 * R, .k = 1 }, .{ .rows = 6, .n = 3 * R, .k = 8 } }; +const rnn_served = [_]c.Shape{ .{ .rows = 3, .n = R, .k = 7 }, .{ .rows = 4, .n = R, .k = 1 }, .{ .rows = 5, .n = R, .k = 3 } }; + +pub fn spec(kind: Kind, fault: bool) c.Spec { + const name = switch (kind) { + .qk => if (fault) "inkling2 dspark control: tf_ink2_dsp_qk_many with one row tagged as the next stream's" else "inkling2 dspark tf_ink2_dsp_qk_many over 3+ streams, each its own tf_ink2_dsp_qk", + .attn => if (fault) "inkling2 dspark control: tf_ink2_dsp_attn_many with two streams' key caches swapped in the table" else "inkling2 dspark tf_ink2_dsp_attn_many + merge over 3+ streams, each its own attend", + .ctx => if (fault) "inkling2 dspark control: tf_ink2_dsp_ctx_many told the packed hidden stride" else "inkling2 dspark tf_ink2_dsp_ctx_many over 3+ streams, each its own tf_ink2_dsp_ctx", + .rnn => if (fault) "inkling2 dspark control: tf_ink2_dsp_rnn_many told a walk stride one id short" else "inkling2 dspark tf_ink2_dsp_rnn_many over 3+ streams, each its own tf_ink2_dsp_rnn", + }; + const one = switch (kind) { + .qk => "each stream's own tf_ink2_dsp_qk", + .attn => "each stream's own tf_ink2_dsp_attn + tf_ink2_dsp_merge", + .ctx => "each stream's own tf_ink2_dsp_ctx", + .rnn => "each stream's own tf_ink2_dsp_rnn", + }; + const served: []const c.Shape = switch (kind) { + .qk => &qk_served, + .attn => &attn_served, + .ctx => &ctx_served, + .rnn => &rnn_served, + }; + return .{ .name = name, .accum = .none, .depth = noDepth, .out = .raw, .in_place = kind == .rnn, .replaces = one, .nan = .{ .stated = rule }, .served = served }; +} + +/// An output and the scratch its one-stream launches write instead; `init` is what both hold before a run. +const Pair = struct { out: u64, base: u64, len: usize, init: ?[]const u8 = null }; + +/// One batched launch over several streams, and the same streams launched one at a time. +pub const Many = struct { + rig: rig_.Rig, + k: *const dk.Kernels, + kind: Kind, + /// control: a wrong table entry (qk, attn) or a wrong stride (ctx, rnn) on the batched launch only + fault: bool = false, + arena: std.heap.ArenaAllocator, + shape: c.Shape = undefined, + n: usize = 0, + in: [6]u64 = @splat(0), + tab: dk.Table = .{ .dev = 0, .host = &.{} }, + rows: dk.Rows = .{ .dev = 0, .host = &.{} }, + /// per stream: its first row, position and rows (qk), or its window [lo, hi] and caches (attn) + first: []usize = &.{}, + lo: []usize = &.{}, + hi: []usize = &.{}, + caches: []u64 = &.{}, + pairs: std.ArrayList(Pair) = .empty, + maxc: usize = 0, + xld: usize = 0, + base: std.ArrayList(u8) = .empty, + + pub fn deinit(self: *Many) void { + self.base.deinit(self.rig.gpu.gpa); + self.arena.deinit(); + self.rig.deinit(); + } + + pub fn kernel(self: *Many) g.Kernel { + return .{ .spec = spec(self.kind, self.fault), .ctx = self, .vt = &vt, .control = if (self.fault) .shapes else null }; + } + + const vt = g.hooks(Many); + + pub fn prepare(self: *Many, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + _ = self.arena.reset(.free_all); + self.pairs = .empty; + if (shape.rows < 3 or shape.rows > 16) return false; + self.shape = shape; + self.n = shape.rows; + var prng = std.Random.DefaultPrng.init(seed); + const a = self.arena.allocator(); + return switch (self.kind) { + .qk => self.prepQk(a, fill, prng.random()), + .attn => self.prepAttn(a, fill, prng.random()), + .ctx => self.prepCtx(a, fill, prng.random()), + .rnn => self.prepRnn(a, fill, prng.random()), + }; + } + + /// An output poisoned as the rig poisons it, and its baseline twin. + fn twin(self: *Many, len: usize, init: ?[]const u8) !u64 { + const p: Pair = .{ .out = try self.rig.output(len), .base = try self.rig.scratch(len), .len = len, .init = init }; + try self.pairs.append(self.arena.allocator(), p); + if (init) |b| try ref.restore(&self.rig, p.out, b); + return p.out; + } + + fn hqOf(self: *const Many) usize { + return if (self.shape.n == dw) hq else 0; + } + + /// Streams laid out last first in the rows, a draft block each or 1 to 7 absorbed rows, ends far apart. + fn prepQk(self: *Many, a: std.mem.Allocator, fill: g.Fill, rng: std.Random) !bool { + if (self.shape.n != dw and self.shape.n != aw) return false; + const n = self.n; + const h = self.hqOf(); + self.first = try a.alloc(usize, n); + self.lo = try a.alloc(usize, n); + self.hi = try a.alloc(usize, n); + var total: usize = 0; + for (0..n) |i| { + self.hi[i] = if (h > 0) T else 1 + (3 * i + 2) % 7; // the stream's rows + const end = if (self.shape.k > i * 4999 + self.hi[i]) self.shape.k - i * 4999 else self.hi[i] + 37 * i; + self.lo[i] = end - self.hi[i]; + total += self.hi[i]; + } + const at = try a.alloc([2]i32, total); + var r: usize = 0; + var i = n; + while (i > 0) { + i -= 1; + self.first[i] = r; + for (0..self.hi[i]) |j| at[r + j] = .{ @intCast(i), @intCast(self.lo[i] + j) }; + r += self.hi[i]; + } + if (self.fault) at[self.first[1]][0] = 2; + self.xld = self.shape.n + 64; // padded rows: the launches must honour the stride + const x = try ref.bfs(a, rng, total * self.xld, -2, 2); + if (fill == .nonfinite) { + x[3] = c.toBf16(ref.nan); + x[self.xld + D + 9] = c.toBf16(ref.inf); + x[2 * self.xld + h * D + 70] = c.toBf16(-ref.inf); + } + self.in = .{ try ref.input(&self.rig, x), try ref.input(&self.rig, try ref.bfs(a, rng, D, 0.5, 1.5)), try ref.input(&self.rig, try ref.bfs(a, rng, D, 0.5, 1.5)), 0, 0, 0 }; + if (h > 0) _ = try self.twin(total * h * D * 2, null); + const st = try a.alloc(dk.Stream, n); + for (st) |*s| { + s.* = .{}; + s.kc[layer] = try self.twin(ring * hk * D * 2, null); + s.vc[layer] = try self.twin(ring * hk * D * 2, null); + } + self.tab = .{ .dev = try ref.input(&self.rig, st), .host = st }; + self.rows = .{ .dev = try ref.input(&self.rig, at), .host = at }; + return true; + } + + /// Windows of a whole ring, a block and a few keys, and 1,030 keys across a chunk edge, each in its own caches. + fn prepAttn(self: *Many, a: std.mem.Allocator, fill: g.Fill, rng: std.Random) !bool { + if (self.shape.n != hq * D or self.shape.k < 2 * T) return false; + const n = self.n; + self.lo = try a.alloc(usize, n); + self.hi = try a.alloc(usize, n); + self.caches = try a.alloc(u64, 2 * n); + const st = try a.alloc(dk.Stream, n); + const q = try a.alloc(u16, n * nqt * D); + for (q) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * 4); + if (fill == .nonfinite) q[3] = c.toBf16(ref.nan); + self.maxc = 0; + for (0..n) |i| { + self.hi[i] = if (self.shape.k > i * 1500 + 2 * T) self.shape.k - 1 - i * 1500 else T - 1 + 5 * i; + const keys: usize = switch (i % 3) { + 0 => ring, + 1 => T + 3 * i, + else => 1030 + i, + }; + self.lo[i] = self.hi[i] + 1 - @min(keys, self.hi[i] + 1); + self.maxc = @max(self.maxc, dk.chunks(self.lo[i], self.hi[i])); + const kv = try ref.bfs(a, rng, 2 * ring * hk * D, -1, 1); + if (fill == .nonfinite and i == 1) kv[((self.lo[i] + 2) % ring * hk + 1) * D + 5] = c.toBf16(ref.inf); + self.caches[2 * i] = try ref.input(&self.rig, kv[0 .. ring * hk * D]); + self.caches[2 * i + 1] = try ref.input(&self.rig, kv[ring * hk * D ..]); + st[i] = .{ .p = @intCast(self.hi[i] + 1 - T) }; + st[i].lo[layer] = @intCast(self.lo[i]); + st[i].kc[layer] = self.caches[2 * i]; + st[i].vc[layer] = self.caches[2 * i + 1]; + } + if (self.fault) std.mem.swap(u64, &st[1].kc[layer], &st[2].kc[layer]); + self.in = .{ try ref.input(&self.rig, q), try self.rig.scratch(n * self.maxc * nqt * D * 4), try self.rig.scratch(n * self.maxc * nqt * 2 * 4), try self.rig.scratch(self.maxc * nqt * D * 4), try self.rig.scratch(self.maxc * nqt * 2 * 4), 0 }; + _ = try self.twin(n * nqt * D * 2, null); + self.tab = .{ .dev = try ref.input(&self.rig, st), .host = st }; + return true; + } + + /// Each stream's hidden rows a padded stride apart, its own f_rnn from the table. + fn prepCtx(self: *Many, a: std.mem.Allocator, fill: g.Fill, rng: std.Random) !bool { + const rows = self.shape.k; + if (self.shape.n != 3 * R or rows == 0 or rows > dk.max_rows) return false; + const n = self.n; + self.xld = rows * hidden + 64; + const h = try ref.bfs(a, rng, n * self.xld, -2, 2); + const bias = try ref.bfs(a, rng, 3 * R, -1, 1); + if (fill == .nonfinite) { + h[11] = c.toBf16(ref.nan); + h[self.xld + 7] = c.toBf16(ref.inf); + bias[5] = c.toBf16(ref.nan); + } + self.in = .{ try ref.input(&self.rig, h), try ref.input(&self.rig, try ref.bfs(a, rng, n * hidden, -2, 2)), try ref.input(&self.rig, try ref.bfs(a, rng, 3 * R * ld, -0.5, 0.5)), try ref.input(&self.rig, bias), 0, 0 }; + const st = try a.alloc(dk.Stream, n); + for (st, 0..) |*s, i| s.* = .{ .frnn = self.in[1] + i * hidden * 2 }; + _ = try self.twin(n * rows * 3 * R * 4, null); + self.tab = .{ .dev = try ref.input(&self.rig, st), .host = st }; + return true; + } + + /// Each stream's context rows and walk a padded stride apart; its state updated in place, a latent a step. + fn prepRnn(self: *Many, a: std.mem.Allocator, fill: g.Fill, rng: std.Random) !bool { + const steps = self.shape.k; + if (self.shape.n != R or steps == 0 or steps > dk.max_rows - 1) return false; + const n = self.n; + self.xld = (steps + 1) * 3 * R; // ctx floats a stream: one spare row + const ctx = try ref.f32s(a, rng, n * self.xld, -2, 2); + if (fill == .nonfinite) { + ctx[5] = ref.nan; + ctx[self.xld + R + 9] = -ref.inf; + } + const walk = try a.alloc(i32, n * (steps + 2)); + for (walk) |*p| p.* = @intCast(rng.uintLessThan(u32, prev_rows)); + self.in = .{ try ref.input(&self.rig, ctx), try ref.input(&self.rig, try ref.bfs(a, rng, 3 * R * ld, -0.1, 0.1)), try ref.input(&self.rig, try ref.bfs(a, rng, prev_rows * R, -1, 1)), try ref.input(&self.rig, walk), 0, 0 }; + _ = try self.twin(n * R * 2, std.mem.sliceAsBytes(try ref.bfs(a, rng, n * R, -1, 1))); + _ = try self.twin(steps * n * R * 2, null); + return true; + } + + pub fn run(self: *Many) !void { + const s = self.rig.s; + const p = self.pairs.items; + const n = self.n; + switch (self.kind) { + .qk => { + const h = self.hqOf(); + try dk.qkMany(self.k, s, self.qkArgs(if (h > 0) p[0].out else 0, 0, 0, 0), self.tab, self.rows, layer); + }, + .attn => try dk.attendMany(self.k, s, self.attnArgs(self.in[0], 0, 0, self.in[1], self.in[2], 0, 0), self.tab, layer, self.maxc, n * self.maxc, p[0].out), + .ctx => { + const rows = self.shape.k; + const stride = if (self.fault) rows * hidden else self.xld; + try dk.ctxMany(self.k, s, self.in[0], stride, self.tab.dev, self.in[2], self.in[3], p[0].out, n, rows, hidden, R); + }, + .rnn => { + try ref.restore(&self.rig, p[0].out, p[0].init.?); + const wt = self.shape.k + 2 - @intFromBool(self.fault); + for (0..self.shape.k) |j| try dk.rnnMany(self.k, s, self.in[0] + j * 3 * R * 4, self.xld, self.in[1], self.in[2], self.in[3], wt, j, p[0].out, p[1].out + j * n * R * 2, n, R, hidden); + }, + } + try s.synchronize(); + } + + fn qkArgs(self: *const Many, q: u64, kc: u64, vc: u64, pos0: usize) dk.QkArgs { + return .{ .x = self.in[0], .qw = if (self.hqOf() > 0) self.in[1] else 0, .kw = self.in[2], .q = q, .kc = kc, .vc = vc, .ld = @intCast(self.xld), .hq = @intCast(self.hqOf()), .hk = hk, .ring = ring, .pos0 = @intCast(pos0), .eps = eps, .theta = theta }; + } + + fn attnArgs(_: *const Many, q: u64, kc: u64, vc: u64, po: u64, pml: u64, lo: usize, hi: usize) dk.AttnArgs { + return .{ .q = q, .kc = kc, .vc = vc, .po = po, .pml = pml, .T = T, .hq = hq, .hk = hk, .ring = ring, .lo = @intCast(lo), .hi = @intCast(hi), .c0 = 0, .scale = scale }; + } + + /// The streams one at a time through the one-stream kernels, into the outputs' twins, in the outputs' order. + pub fn replaced(self: *Many) ![]const u8 { + const gpa = self.rig.gpu.gpa; + const s = self.rig.s; + const p = self.pairs.items; + const n = self.n; + for (p) |x| { + if (x.init) |b| { + try ref.restore(&self.rig, x.base, b); + continue; + } + const poison = try gpa.alloc(u8, x.len); + defer gpa.free(poison); + @memset(poison, 0xff); + try ref.restore(&self.rig, x.base, poison); + } + switch (self.kind) { + .qk => { + const h = self.hqOf(); + const kv = @intFromBool(h > 0); + for (0..n) |i| { + var q = self.qkArgs(if (h > 0) p[0].base + self.first[i] * h * D * 2 else 0, p[kv + 2 * i].base, p[kv + 2 * i + 1].base, self.lo[i]); + q.x += self.first[i] * self.xld * 2; + try dk.qk(self.k, s, q, self.hi[i]); + } + }, + .attn => for (0..n) |i| { + const at = self.attnArgs(self.in[0] + i * nqt * D * 2, self.caches[2 * i], self.caches[2 * i + 1], self.in[3], self.in[4], self.lo[i], self.hi[i]); + try dk.attend(self.k, s, at, p[0].base + i * nqt * D * 2); + }, + .ctx => { + const rows = self.shape.k; + for (0..n) |i| try dk.ctx(self.k, s, self.in[0] + i * self.xld * 2, self.in[1] + i * hidden * 2, self.in[2], self.in[3], p[0].base + i * rows * 3 * R * 4, rows, hidden, R); + }, + .rnn => for (0..self.shape.k) |j| for (0..n) |i| { + const walk = self.in[3] + i * (self.shape.k + 2) * 4; + try dk.rnn(self.k, s, self.in[0] + (i * self.xld + j * 3 * R) * 4, self.in[1], self.in[2], walk, j, p[0].base + i * R * 2, p[1].base + (j * n + i) * R * 2, R, hidden); + }, + } + self.base.clearRetainingCapacity(); + for (p) |x| try self.base.appendSlice(gpa, try self.rig.bytes(x.base, x.len)); + return self.base.items; + } + + /// Gate 1's own check: the batched bytes, NaN and infinities included, equal the one-stream launches'. + pub fn check(self: *Many, _: g.Gate) !?[]const u8 { + const gpa = self.rig.gpu.gpa; + const got = try gpa.dupe(u8, try self.rig.outputBytes()); + defer gpa.free(got); + return if (std.mem.eql(u8, got, try self.replaced())) null else rule; + } + + pub fn count(self: *const Many) usize { + var bytes: usize = 0; + for (self.pairs.items) |x| bytes += x.len; + return bytes; + } + + pub fn reference(_: *Many, _: []f64, _: []f64) !void { + return error.ReplacementHasNoReference; + } +}; diff --git a/zig/tests/cuda/contract_inkling2_dspark_mini.zig b/zig/tests/cuda/contract_inkling2_dspark_mini.zig new file mode 100644 index 00000000000..8a0eebacd58 --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_dspark_mini.zig @@ -0,0 +1,151 @@ +//! Mini's visit-tap and hidden projection bridges under the DSpark CUDA contract. +const std = @import("std"); +const core = @import("core"); +const dk = @import("inkling2").dspark_ops; +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +/// The copy preserves every other channel, including non-finite BF16 words and tail columns. +pub const Tap = struct { + kern: *const dk.Kernels, + fault: bool = false, + shape: c.Shape = undefined, + src: []u16 = &.{}, + want: []u8 = &.{}, + input: u64 = 0, + output: u64 = 0, + + pub fn spec(self: *const Tap) c.Spec { + return .{ + .name = if (self.fault) "inkling2 dspark control: Mini tap writes the wrong channel" else "inkling2 dspark tf_ink2_mini_tap: interleaved visit rows preserve all four channels", + .accum = .none, + .depth = ref.noSums, + .out = .raw, + .nan = .{ .stated = "every BF16 bit copied exactly; all three other channels stay untouched" }, + .served = &.{ .{ .rows = 1, .n = 2304, .k = 0 }, .{ .rows = 4, .n = 2305, .k = 1 }, .{ .rows = 4, .n = 2304, .k = 3 } }, + }; + } + + pub fn control(self: *const Tap) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *Tap, a: std.mem.Allocator) void { + a.free(self.src); + a.free(self.want); + self.src = &.{}; + self.want = &.{}; + } + + pub fn prepare(self: *Tap, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k > 3) return false; + self.free(a); + self.shape = shape; + self.src = try a.alloc(u16, shape.rows * shape.n); + for (self.src) |*word| word.* = rng.int(u16); + if (fill == .nonfinite) { + self.src[0] = c.toBf16(ref.nan); + self.src[self.src.len - 1] = c.toBf16(ref.inf); + } + self.want = try a.alloc(u8, shape.rows * 4 * shape.n * 2); + @memset(self.want, 0xff); + for (0..shape.rows) |row| { + const dst = (row * 4 + shape.k) * shape.n * 2; + @memcpy(self.want[dst..][0 .. shape.n * 2], std.mem.sliceAsBytes(self.src[row * shape.n ..][0..shape.n])); + } + self.input = try ref.input(rig, self.src); + self.output = try rig.output(self.want.len); + return true; + } + + pub fn run(self: *Tap, rig: *rig_.Rig) !void { + try dk.miniTap(self.kern, rig.s, self.input, self.output, self.shape.rows, if (self.fault) (self.shape.k + 1) % 4 else self.shape.k, self.shape.n); + } + + pub fn count(self: *const Tap) usize { + return self.want.len; + } + + pub fn check(self: *const Tap, _: std.mem.Allocator, got: []const u8, _: *[200]u8) ?[]const u8 { + return if (std.mem.eql(u8, got, self.want)) null else "a tap row or an untouched channel changed"; + } +}; + +/// The fused Mini hidden_out adds target hidden to bias and the rank projection, then rounds BF16 once. +pub const Hidden = struct { + kern: *const dk.Kernels, + fault: bool = false, + shape: c.Shape = undefined, + stride: usize = 0, + y: []u16 = &.{}, + latent: []u16 = &.{}, + w: []u16 = &.{}, + bias: []u16 = &.{}, + input: [4]u64 = @splat(0), + output: u64 = 0, + + pub fn spec(self: *const Hidden) c.Spec { + return .{ + .name = if (self.fault) "inkling2 dspark control: Mini hidden reads the next hidden column" else "inkling2 dspark tf_ink2_mini_hidden: BF16 hidden_out before target unembedding", + .accum = .none, + .depth = ref.noSums, + .out = .bf16, + .nan = .{ .stated = "NaN and infinities follow the BF16 projection and sum" }, + .served = &.{ .{ .rows = 1, .n = 64, .k = 256 }, .{ .rows = 4, .n = 257, .k = 256 } }, + }; + } + + pub fn control(self: *const Hidden) ?g.Gate { + return if (self.fault) .shapes else null; + } + + pub fn free(self: *Hidden, a: std.mem.Allocator) void { + inline for (.{ "y", "latent", "w", "bias" }) |name| { + a.free(@field(self, name)); + @field(self, name) = &.{}; + } + } + + pub fn prepare(self: *Hidden, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.k != 256 or shape.n == 0) return false; + self.free(a); + self.shape = shape; + self.stride = shape.n + 3; + self.y = try ref.bfs(a, rng, shape.rows * self.stride, -1, 1); + self.latent = try ref.bfs(a, rng, shape.rows * shape.k, -0.5, 0.5); + self.w = try ref.bfs(a, rng, shape.n * shape.k, -0.5, 0.5); + self.bias = try ref.bfs(a, rng, shape.n, -1, 1); + if (fill == .stress) { + for (self.y) |*word| word.* = c.toBf16(ref.int(rng, -8, 8)); + for (self.w) |*word| word.* = c.toBf16(ref.int(rng, -8, 8)); + } + if (fill == .nonfinite) { + self.y[0] = c.toBf16(ref.nan); + self.bias[shape.n - 1] = c.toBf16(ref.inf); + } + self.input = .{ try ref.input(rig, self.y), try ref.input(rig, self.latent), try ref.input(rig, self.w), try ref.input(rig, self.bias) }; + self.output = try rig.output(shape.rows * shape.n * 2); + return true; + } + + pub fn run(self: *Hidden, rig: *rig_.Rig) !void { + try dk.miniHidden(self.kern, rig.s, self.input[0] + @as(u64, if (self.fault) 2 else 0), self.stride, self.input[1], self.input[2], self.input[3], self.output, self.shape.rows, self.shape.n, self.shape.k); + } + + pub fn count(self: *const Hidden) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Hidden, _: std.mem.Allocator, _: ref.Sums, out: []ref.Iv) !void { + const n = self.shape.n; + const rank = self.shape.k; + for (0..self.shape.rows) |row| for (0..n) |col| { + var v = ref.Iv.of(ref.bf(self.y[row * self.stride + col])).add(ref.Iv.of(ref.bf(self.bias[col]))); + for (0..rank) |i| v = v.add(ref.Iv.of(ref.bf(self.w[col * rank + i])).mul(ref.Iv.of(ref.bf(self.latent[row * rank + i])))); + out[row * n + col] = v.bf(); + }; + } +}; diff --git a/zig/tests/cuda/contract_inkling2_dspark_norm.zig b/zig/tests/cuda/contract_inkling2_dspark_norm.zig new file mode 100644 index 00000000000..911d84bd57b --- /dev/null +++ b/zig/tests/cuda/contract_inkling2_dspark_norm.zig @@ -0,0 +1,435 @@ +//! Inkling 2's DSpark norms under the contract: tf_ink2_dsp_mix, tf_ink2_dsp_addnorm and tf_ink2_dsp_qk. +const std = @import("std"); +const core = @import("core"); +const dk = @import("inkling2").dspark_ops; +const rig_ = @import("contract_rig.zig"); +const ref = @import("contract_minimax_glue_ref.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const Iv = ref.Iv; +const Sums = ref.Sums; + +const hidden = 4608; +const taps = 8; +const D = 128; +const eps: f32 = 1e-6; +const theta: f32 = 1e6; + +/// A thread's chain over the row (512 threads), the warp's 5 shuffles, warp 0's 5 over the partials, the square. +fn rowDepth(s: c.Shape) usize { + return (s.n + 511) / 512 + 5 + 5 + 1; +} + +/// x * y in fp32: exact for gate 4's integers (no spread), else one rounding. +fn times(s: Sums, x: Iv, y: Iv) Iv { + if (s.exact) return Iv.of(x.m * y.m); + return x.mul(y); +} + +fn square(s: Sums, v: Iv) Iv { + if (s.exact) return Iv.of(v.m * v.m); + const lo = @min(@abs(v.lo), @abs(v.hi)); + const hi = @max(@abs(v.lo), @abs(v.hi)); + return (Iv{ .m = v.m * v.m, .lo = if (v.lo <= 0 and v.hi >= 0) 0 else lo * lo, .hi = hi * hi }).mul(Iv.of(1)); +} + +/// RMSNorm of one row's fp32 values: the fp32 sum of squares, rsqrtf, then (v * r) * w rounded once to bf16. +fn normRow(s: Sums, x: []const Iv, w: []const u16, out: []Iv, scratch: []f64, sq: []Iv) void { + for (sq, x) |*q, v| q.* = square(s, v); + const total = s.sum(sq, rowDepth(.{ .rows = 1, .n = x.len, .k = 0 }), scratch); + const r = total.div(Iv.of(@floatFromInt(x.len))).add(Iv.of(eps)).rsqrt(); + for (out, x, w) |*o, v, wv| o.* = v.mul(r).mul(Iv.of(ref.bf(wv))).bf(); +} + +/// Norm weights as the checkpoint's plain multipliers: mostly in [0.5, 1.5), one in 97 four times larger. +fn weights(a: std.mem.Allocator, rng: std.Random, n: usize) ![]u16 { + const w = try a.alloc(u16, n); + for (w, 0..) |*v, i| v.* = c.toBf16((0.5 + rng.float(f32)) * (if (i % 97 == 3) @as(f32, 4) else 1)); + return w; +} + +/// bf16 values in [-2, 2), one in 64 ten times larger; stress: integers in [-lim, lim]. +fn values(a: std.mem.Allocator, rng: std.Random, n: usize, fill: g.Fill, lim: i32) ![]u16 { + const x = try a.alloc(u16, n); + for (x, 0..) |*v, i| v.* = c.toBf16(if (fill == .stress) ref.int(rng, -lim, lim) else (rng.float(f32) * 4 - 2) * (if (i % 64 == 7) @as(f32, 10) else 1)); + return x; +} + +/// Rows x hidden x taps: an absorb's prompt rows (to 2,048), a draft's context rows, and f_rnn's one row. +pub fn mixSpec(drop: bool) c.Spec { + const served = &[_]c.Shape{ .{ .rows = 16, .n = hidden, .k = taps }, .{ .rows = 1, .n = hidden, .k = taps }, .{ .rows = 7, .n = hidden, .k = taps }, .{ .rows = 2048, .n = hidden, .k = taps } }; + const name = if (drop) "inkling2 dspark control: the tap mix drops its last tap" else "inkling2 dspark tf_ink2_dsp_mix (alpha . taps in fp32, RMSNorm, rounded once)"; + return .{ .name = name, .accum = .f32, .depth = rowDepth, .out = .bf16, .served = served, .sums = .{} }; +} + +/// out[row] = RMSNorm(sum_t alpha[t] taps[row][t]) * w (vLLM's mix_rmsnorm). +pub const Mix = struct { + kern: *const dk.Kernels, + /// control: launched with one tap fewer (the head's input tap left out) + drop: bool = false, + shape: c.Shape = undefined, + x: []u16 = &.{}, + alpha: []f32 = &.{}, + w: []u16 = &.{}, + in: [3]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const Mix) c.Spec { + return mixSpec(self.drop); + } + + pub fn control(self: *const Mix) ?g.Gate { + return if (self.drop) .shapes else null; + } + + pub fn free(self: *Mix, a: std.mem.Allocator) void { + a.free(self.x); + a.free(self.alpha); + a.free(self.w); + self.x = &.{}; + self.alpha = &.{}; + self.w = &.{}; + } + + /// alpha a softmax row (positive, summing to 1); stress: small integers, so every mix is an exact integer. + pub fn prepare(self: *Mix, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.n != hidden or shape.k != taps or shape.rows == 0) return false; + self.free(a); + self.shape = shape; + const n = shape.n; + self.x = try values(a, rng, shape.rows * taps * n, fill, 4); + self.alpha = try a.alloc(f32, taps); + var total: f32 = 0; + for (self.alpha) |*v| { + v.* = 0.2 + rng.float(f32); + total += v.*; + } + const whole = [taps]f32{ 1, -1, 2, 1, -2, 1, 1, -1 }; + for (self.alpha, whole) |*v, x| v.* = if (fill == .stress) x else v.* / total; + self.w = try weights(a, rng, n); + if (fill == .nonfinite) { + const at = [_][3]usize{ .{ 0, 3, n / 3 }, .{ 1, 0, n / 2 }, .{ 2, 7, n - 1 }, .{ 3, 1, 0 }, .{ 3, 2, n - 1 } }; + const put = [_]f32{ ref.nan, ref.inf, -ref.inf, ref.inf, -ref.inf }; + for (at, put) |p, v| if (p[0] < shape.rows) { + self.x[(p[0] * taps + p[1]) * n + p[2]] = c.toBf16(v); + }; + } + self.in = .{ try ref.input(rig, self.x), try ref.input(rig, self.alpha), try ref.input(rig, self.w) }; + self.out = try rig.output(shape.rows * n * 2); + return true; + } + + pub fn run(self: *Mix, rig: *rig_.Rig) !void { + try dk.mix(self.kern, rig.s, self.in[0], self.in[1], self.in[2], self.out, self.shape.rows, @as(usize, taps) - @intFromBool(self.drop), self.shape.n, eps); + } + + pub fn count(self: *const Mix) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const Mix, a: std.mem.Allocator, s: Sums, out: []Iv) !void { + const n = self.shape.n; + const buf = try a.alloc(Iv, 2 * n); + defer a.free(buf); + const scratch = try a.alloc(f64, n); + defer a.free(scratch); + var terms: [taps]Iv = undefined; + for (0..self.shape.rows) |r| { + for (buf[0..n], 0..) |*m, i| { + for (&terms, 0..) |*t, k| t.* = times(s, Iv.of(ref.bf(self.x[(r * taps + k) * n + i])), Iv.of(self.alpha[k])); + m.* = s.sum(&terms, taps, scratch); + } + normRow(s, buf[0..n], self.w, out[r * n ..][0..n], scratch, buf[n..]); + } + } +}; + +/// Which output an addnorm registration checks: the residual written back, or the next norm's rows. +pub const View = enum { resid, normed }; + +/// A draft block's rows x hidden x ranks' partials (0: the first layer's norm, 2: after o and down at TP=2). +pub fn addSpec(v: View, short: bool) c.Spec { + const both = &[_]c.Shape{ .{ .rows = 8, .n = hidden, .k = 2 }, .{ .rows = 8, .n = hidden, .k = 0 } }; + const resid = &[_]c.Shape{.{ .rows = 8, .n = hidden, .k = 2 }}; + const name = if (short) "inkling2 dspark control: addnorm adds rank 0's partial alone" else if (v == .resid) "inkling2 dspark tf_ink2_dsp_addnorm, the residual written back" else "inkling2 dspark tf_ink2_dsp_addnorm, the next norm's rows"; + return .{ .name = name, .accum = .f32, .depth = rowDepth, .out = .bf16, .in_place = true, .served = if (v == .resid) resid else both, .sums = .{} }; +} + +/// resid (bf16) += the ranks' fp32 partials in rank order; out = RMSNorm of the unrounded sum * w. +pub const AddNorm = struct { + kern: *const dk.Kernels, + view: View, + /// control: launched with one partial where two are due + short: bool = false, + shape: c.Shape = undefined, + x: []u16 = &.{}, + parts: []f32 = &.{}, + w: []u16 = &.{}, + resid: u64 = 0, + in: [2]u64 = @splat(0), + out: u64 = 0, + + pub const sums = {}; + + pub fn spec(self: *const AddNorm) c.Spec { + return addSpec(self.view, self.short); + } + + pub fn control(self: *const AddNorm) ?g.Gate { + return if (self.short) .shapes else null; + } + + pub fn free(self: *AddNorm, a: std.mem.Allocator) void { + a.free(self.x); + a.free(self.parts); + a.free(self.w); + self.x = &.{}; + self.parts = &.{}; + self.w = &.{}; + } + + /// Partials in [-2, 2); stress: rank 0's integers near 2^16 cancelled by rank 1's (fp16 overflows, bf16 loses). + pub fn prepare(self: *AddNorm, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + if (shape.rows == 0 or shape.n != hidden or (shape.k != 0 and shape.k != 2)) return false; + self.free(a); + self.shape = shape; + const rows = shape.rows; + const n = shape.n; + self.x = try values(a, rng, rows * n, fill, 32); + self.parts = try ref.f32s(a, rng, 2 * rows * n, -2, 2); + if (fill == .stress) for (0..rows * n) |i| { + const big = ref.int(rng, 40000, 120000); + self.parts[i] = big; + self.parts[rows * n + i] = ref.int(rng, -8, 8) - big; + }; + self.w = try weights(a, rng, n); + if (fill == .nonfinite) { + const at = [_][2]usize{ .{ 0, n / 3 }, .{ 1, n / 2 }, .{ 2, n - 1 }, .{ 3, 0 }, .{ 3, n - 1 } }; + const put = [_]f32{ ref.nan, ref.inf, -ref.inf, ref.inf, -ref.inf }; + for (at, put) |p, v| if (p[0] < rows) { + self.x[p[0] * n + p[1]] = c.toBf16(v); + }; + self.parts[(rows - 1) * n + 5] = ref.nan; // the last row, rank 0 + } + self.in = .{ try ref.input(rig, self.parts), try ref.input(rig, self.w) }; + if (self.view == .resid) { + self.resid = try rig.output(rows * n * 2); + self.out = try rig.scratch(rows * n * 2); + } else { + self.resid = try rig.scratch(rows * n * 2); + self.out = try rig.output(rows * n * 2); + } + return true; + } + + pub fn run(self: *AddNorm, rig: *rig_.Rig) !void { + try ref.restore(rig, self.resid, std.mem.sliceAsBytes(self.x)); // updated in place: every run starts the same + const parts = self.shape.k - @intFromBool(self.short and self.shape.k > 0); + try dk.addNorm(self.kern, rig.s, self.resid, self.in[0], parts, self.shape.rows * self.shape.n, self.in[1], self.out, self.shape.rows, self.shape.n, eps); + } + + pub fn count(self: *const AddNorm) usize { + return self.shape.rows * self.shape.n; + } + + pub fn solve(self: *const AddNorm, a: std.mem.Allocator, s: Sums, out: []Iv) !void { + const n = self.shape.n; + const rows = self.shape.rows; + const k = self.shape.k; + const buf = try a.alloc(Iv, 2 * n); + defer a.free(buf); + const scratch = try a.alloc(f64, n); + defer a.free(scratch); + var terms: [2]Iv = undefined; + for (0..rows) |r| { + const row = buf[0..n]; + for (row, 0..) |*v, i| { + for (terms[0..k], 0..) |*t, q| t.* = Iv.of(self.parts[(q * rows + r) * n + i]); + const x = Iv.of(ref.bf(self.x[r * n + i])); + v.* = if (k == 0) x else x.add(s.sum(terms[0..k], k, scratch)); + } + if (self.view == .resid) { + for (out[r * n ..][0..n], row) |*o, v| o.* = v.bf(); + } else normRow(s, row, self.w, out[r * n ..][0..n], scratch, buf[n..]); + } + } +}; + +/// The kernel's calls: a draft block's q, k, v (24 query, 4 key heads a TP=2 rank), or an absorb's context k, v. +pub const Form = enum { draft, absorb }; + +fn qHeads(f: Form) usize { + return if (f == .draft) 24 else 0; +} + +const kv_heads = 4; + +fn width(f: Form) usize { + return (qHeads(f) + 2 * kv_heads) * D; +} + +/// The ring a call writes at its end position: a sliding layer's 4,096 rows, or the global layer's whole context. +fn ringOf(end: usize) usize { + return if (end > 100_000) 1_050_624 else 4096; +} + +/// A lane's two squares and their add, the warp's 5 shuffles, warp 0's 5 over the two partials. +fn headDepth(_: c.Shape) usize { + return 12; +} + +const dw = width(.draft); +const aw = width(.absorb); +const draft_served = [_]c.Shape{ .{ .rows = 8, .n = dw, .k = 3007 }, .{ .rows = 8, .n = dw, .k = 70_008 }, .{ .rows = 8, .n = dw, .k = 1_048_576 }, .{ .rows = 8, .n = dw, .k = 8 } }; +const absorb_served = [_]c.Shape{ .{ .rows = 16, .n = aw, .k = 2016 }, .{ .rows = 2048, .n = aw, .k = 4096 }, .{ .rows = 2048, .n = aw, .k = 1_048_576 }, .{ .rows = 1, .n = aw, .k = 70_001 } }; +/// The batched pass's absorbs: up to 16 streams' kept rows (7 each at most past the anchor) in one launch. +const absorb_many = [_]c.Shape{ .{ .rows = 16, .n = aw, .k = 2016 }, .{ .rows = 112, .n = aw, .k = 4096 }, .{ .rows = 56, .n = aw, .k = 1_048_576 }, .{ .rows = 1, .n = aw, .k = 70_001 } }; + +/// Rows x the row's heads x the call's end position (pos0 + rows): early, deep in a ring, and at the 1M edge. +pub fn qkSpec(f: Form, late: bool, many: bool) c.Spec { + const served: []const c.Shape = switch (f) { + .draft => &draft_served, + .absorb => if (many) &absorb_many else &absorb_served, + }; + const name = if (late) "inkling2 dspark control: q/k prep rotates its rows one position late" else switch (f) { + .draft => "inkling2 dspark tf_ink2_dsp_qk, a draft block's q, k, v", + .absorb => "inkling2 dspark tf_ink2_dsp_qk, an absorb's context k, v", + }; + const batched = if (late) "inkling2 dspark control: tf_ink2_dsp_qk_many rotates its rows one position late" else switch (f) { + .draft => "inkling2 dspark tf_ink2_dsp_qk_many, every stream's block q, k, v", + .absorb => "inkling2 dspark tf_ink2_dsp_qk_many, every stream's absorbed k, v", + }; + return .{ .name = if (many) batched else name, .accum = .f32, .depth = headDepth, .out = .bf16, .served = served, .sums = .{} }; +} + +/// Per (row, head): RMSNorm * w rounded to bf16, then neox RoPE at pos0 + row; key and value heads to the caches. +pub const Qk = struct { + kern: *const dk.Kernels, + form: Form, + /// control: the device rotates every row one position late (its cache rows land where they are due) + late: bool = false, + /// tf_ink2_dsp_qk_many: the rows' positions and the caches from a one-stream table + many: bool = false, + tabs: [2]u64 = @splat(0), + st: [1]dk.Stream = .{.{}}, + at: [128][2]i32 = undefined, + shape: c.Shape = undefined, + pos: usize = 0, + x: []u16 = &.{}, + w: [2][]u16 = .{ &.{}, &.{} }, + dev: [3]u64 = @splat(0), + outs: [3]u64 = @splat(0), + + pub const sums = {}; + + pub fn spec(self: *const Qk) c.Spec { + return qkSpec(self.form, self.late, self.many); + } + + pub fn control(self: *const Qk) ?g.Gate { + return if (self.late) .shapes else null; + } + + pub fn free(self: *Qk, a: std.mem.Allocator) void { + a.free(self.x); + self.x = &.{}; + for (&self.w) |*v| { + a.free(v.*); + v.* = &.{}; + } + } + + /// Heads in [-2, 2) (one in 64 ten times larger); stress: integers in [-64, 64] (the squares pass 2^16). + pub fn prepare(self: *Qk, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { + const wd = width(self.form); + if (shape.n != wd or shape.rows == 0 or shape.k < shape.rows or (self.many and shape.rows > 128)) return false; + const ring = ringOf(shape.k); + self.pos = shape.k - shape.rows; + const shift: usize = @intFromBool(self.late); + if ((self.pos + shift) % ring + shape.rows > ring) return false; + self.free(a); + self.shape = shape; + const rows = shape.rows; + self.x = try values(a, rng, rows * wd, fill, 64); + if (fill == .nonfinite) { + self.x[3] = c.toBf16(ref.nan); // row 0's first head: its every output NaN + self.x[wd + D + 9] = c.toBf16(ref.inf); + self.x[2 * wd + qHeads(self.form) * D + 70] = c.toBf16(-ref.inf); // row 2's first key head + self.x[3 * wd + wd - 5] = c.toBf16(ref.inf); // row 3's last value head, copied as it is + } + for (&self.w) |*w| w.* = try weights(a, rng, D); + self.dev = .{ try ref.input(rig, self.x), try ref.input(rig, self.w[0]), try ref.input(rig, self.w[1]) }; + const slot = (self.pos + shift) % ring; // the caches' base, so slot pos + row lands on the buffer's row + const hq = qHeads(self.form); + self.outs[0] = if (hq > 0) try rig.output(rows * hq * D * 2) else 0; + self.outs[1] = try rig.output(rows * kv_heads * D * 2) - slot * kv_heads * D * 2; + self.outs[2] = try rig.output(rows * kv_heads * D * 2) - slot * kv_heads * D * 2; + if (self.many) { + self.st[0] = .{}; + self.st[0].kc[0] = self.outs[1]; + self.st[0].vc[0] = self.outs[2]; + for (self.at[0..rows], 0..) |*x, r| x.* = .{ 0, @intCast(self.pos + shift + r) }; + self.tabs = .{ try rig.input(std.mem.sliceAsBytes(&self.st)), try rig.input(std.mem.sliceAsBytes(self.at[0..rows])) }; + } + return true; + } + + pub fn run(self: *Qk, rig: *rig_.Rig) !void { + const hq = qHeads(self.form); + const d = self.dev; + if (self.many) return dk.qkMany(self.kern, rig.s, .{ .x = d[0], .qw = if (hq > 0) d[1] else 0, .kw = d[2], .q = self.outs[0], .kc = 0, .vc = 0, .ld = @intCast(width(self.form)), .hq = @intCast(hq), .hk = kv_heads, .ring = @intCast(ringOf(self.shape.k)), .pos0 = 0, .eps = eps, .theta = theta }, .{ .dev = self.tabs[0], .host = &self.st }, .{ .dev = self.tabs[1], .host = self.at[0..self.shape.rows] }, 0); + try dk.qk(self.kern, rig.s, .{ .x = d[0], .qw = if (hq > 0) d[1] else 0, .kw = d[2], .q = self.outs[0], .kc = self.outs[1], .vc = self.outs[2], .ld = @intCast(width(self.form)), .hq = @intCast(hq), .hk = kv_heads, .ring = @intCast(ringOf(self.shape.k)), .pos0 = @intCast(self.pos + @intFromBool(self.late)), .eps = eps, .theta = theta }, self.shape.rows); + } + + pub fn count(self: *const Qk) usize { + return self.shape.rows * self.shape.n; + } + + /// One head's 128 outputs at row r: the norm (1 / sqrtf), then neox RoPE in fp32 at pos + r. + fn head(self: *const Qk, s: Sums, r: usize, hd: usize, w: []const u16, out: []Iv, scratch: []f64) void { + var x: [D]Iv = undefined; + var sq: [D]Iv = undefined; + var y: [D]Iv = undefined; + for (&x, 0..) |*v, d| v.* = Iv.of(ref.bf(self.x[r * self.shape.n + hd * D + d])); + for (&sq, x) |*q, v| q.* = square(s, v); + const ms = s.sum(&sq, headDepth(self.shape), scratch).div(Iv.of(D)).add(Iv.of(eps)); + const root: Iv = .{ .m = @sqrt(ms.m), .lo = @sqrt(ms.lo) * (1 - ref.unit), .hi = @sqrt(ms.hi) * (1 + ref.unit) }; + const inv = Iv.of(1).div(root); + for (&y, x, w) |*o, v, wv| o.* = v.mul(inv).mul(Iv.of(ref.bf(wv))).bf(); + const position: f64 = @floatFromInt(self.pos + r); + for (0..D / 2) |i| { + const e = @as(f64, @floatFromInt(2 * i)) / D; + const am = position * std.math.pow(f64, theta, -e); + // powf within 8 ulps (exactly 1 at i 0), the fp32 reciprocal and the product: half an ulp each + const rel: f64 = if (i == 0) 0 else 9 * 0x1p-23 + 0x1p-50; + const angle: Iv = .{ .m = am, .lo = am - am * rel, .hi = am + am * rel }; + const co = angle.trig(false); + const si = angle.trig(true); + out[i] = y[i].mul(co).sub(y[i + 64].mul(si)).bf(); + out[i + 64] = y[i + 64].mul(co).add(y[i].mul(si)).bf(); + } + } + + pub fn solve(self: *const Qk, _: std.mem.Allocator, s: Sums, out: []Iv) !void { + const hq = qHeads(self.form); + const rows = self.shape.rows; + var scratch: [D]f64 = undefined; + var o: usize = 0; + for (0..rows) |r| for (0..hq) |hd| { + self.head(s, r, hd, self.w[0], out[o..][0..D], &scratch); + o += D; + }; + for (0..rows) |r| for (0..kv_heads) |hd| { + self.head(s, r, hq + hd, self.w[1], out[o..][0..D], &scratch); + o += D; + }; + for (0..rows) |r| for (0..kv_heads) |hd| for (0..D) |d| { + out[o] = Iv.of(ref.bf(self.x[r * self.shape.n + (hq + kv_heads + hd) * D + d])); // the values as they are + o += 1; + }; + std.debug.assert(o == out.len); + } +}; diff --git a/zig/tests/cuda/contract_inkling2_ops_pick.zig b/zig/tests/cuda/contract_inkling2_ops_pick.zig index 28564cb375c..ad6436afef5 100644 --- a/zig/tests/cuda/contract_inkling2_ops_pick.zig +++ b/zig/tests/cuda/contract_inkling2_ops_pick.zig @@ -7,6 +7,7 @@ const ref = @import("contract_inkling2_ops_ref.zig"); const c = core.contract.spec; const g = core.contract.gates; const ops = ref.ops; +const dk = @import("inkling2").dspark_ops; /// A rank's view of the head (shape.k: 1 rank 0, 2 rank 1): its first id, its rows' stride, the real ids it holds. const Rank = struct { base: usize, stride: usize, n: usize }; @@ -20,11 +21,27 @@ const ranks = [_]c.Shape{ .{ .rows = 16, .n = ref.share, .k = 1 }, .{ .rows = 1, const top_rule = "the largest value and its lowest id plus the rank's base; a NaN never picked, -inf picked when all else is NaN, a row of NaNs (-inf, base)"; /// Rows x a rank's real ids x the rank: greedy draws of a window's rows, the drafter's single row. -pub fn top1Spec(short: bool) c.Spec { +pub fn top1Spec(short: bool, many: bool) c.Spec { const name = if (short) "control: inkling2 ops tf_ink2_top1 one id short" else "inkling2 ops tf_ink2_top1 (greedy pick, fp32 logits)"; + if (many) { + const m = if (short) "inkling2 dspark control: tf_ink2_dsp_pick_many greedy one id short" else "inkling2 dspark tf_ink2_dsp_pick_many, greedy (a stream's step pick a block)"; + return .{ .name = m, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = top_rule }, .served = ranks[0..3] }; + } return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = top_rule }, .served = if (short) ranks[0..2] else &ranks }; } +/// The batched pass's picks: a stream table (raced or not) and each row's (value, id) 16 bytes apart. +fn manyTable(rig: *rig_.Rig, rows: usize, race: bool, late: bool) !u64 { + var st: [128]dk.Stream = @splat(.{}); + for (st[0..rows], 0..) |*x, r| x.* = .{ .race = @intFromBool(race), .seed = seed, .inv_t = inv_t, .p = @intCast(pos0 + r + @intFromBool(late) - 1) }; + return rig.input(std.mem.sliceAsBytes(st[0..rows])); +} + +/// Where row r's value and id sit in the output: two arrays, or (value, id) 16 bytes apart (the batched pick). +fn slots(many: bool, rows: usize, r: usize) [2]usize { + return if (many) .{ 4 * r, 4 * r + 1 } else .{ r, rows + r }; +} + /// Values on 1/8 steps of [-64, 64) and padding past the real ids at 1000: equal maxima, and a read past n shows. fn logits(a: std.mem.Allocator, rng: std.Random, s: c.Shape, fill: g.Fill) ![]f32 { const rk = rank(s); @@ -63,13 +80,16 @@ fn scan(row: []const f32) struct { v: f32, i: usize } { pub const Top1 = struct { kern: *const ops.Kernels, short: bool = false, + /// tf_ink2_dsp_pick_many over greedy streams (its kernels) + many: ?*const dk.Kernels = null, shape: c.Shape = undefined, x: []f32 = &.{}, dev: u64 = 0, + tab: u64 = 0, out: [2]u64 = @splat(0), pub fn spec(self: *const Top1) c.Spec { - return top1Spec(self.short); + return top1Spec(self.short, self.many != null); } pub fn control(self: *const Top1) ?g.Gate { @@ -83,21 +103,28 @@ pub const Top1 = struct { pub fn prepare(self: *Top1, a: std.mem.Allocator, rig: *rig_.Rig, shape: c.Shape, fill: g.Fill, rng: std.Random) !bool { if (shape.rows == 0 or shape.n < 4 or shape.n > ref.share) return false; + if (self.many != null and (shape.k != 1 or shape.rows > 128)) return false; self.free(a); self.shape = shape; self.x = try logits(a, rng, shape, fill); self.dev = try ref.input(rig, self.x); + if (self.many != null) { + self.tab = try manyTable(rig, shape.rows, false, false); + self.out = .{ try rig.output(shape.rows * 16), 0 }; + return true; + } self.out = .{ try rig.output(shape.rows * 4), try rig.output(shape.rows * 4) }; return true; } pub fn run(self: *Top1, rig: *rig_.Rig) !void { const rk = rank(self.shape); + if (self.many) |m| return dk.pickMany(m, rig.s, self.dev, rk.stride - @intFromBool(self.short), rk.n, rk.base, self.tab, 0, self.out[0], self.shape.rows); try ops.top1(self.kern, rig.s, self.dev, self.shape.rows, rk.stride, rk.n - @intFromBool(self.short), rk.base, self.out[0], self.out[1]); } pub fn count(self: *const Top1) usize { - return self.shape.rows * 8; + return self.shape.rows * @as(usize, if (self.many != null) 16 else 8); } pub fn check(self: *const Top1, _: std.mem.Allocator, got: []const u8, msg: []u8) !?[]const u8 { @@ -105,8 +132,9 @@ pub const Top1 = struct { const rows = self.shape.rows; for (0..rows) |r| { const want = scan(self.x[r * rk.stride ..][0..rk.n]); - const v = ref.readF32(got, r); - const i = ref.readI32(got, rows + r); + const at = slots(self.many != null, rows, r); + const v = ref.readF32(got, at[0]); + const i = ref.readI32(got, at[1]); if (v != want.v or i != @as(i32, @intCast(want.i + rk.base))) return try std.fmt.bufPrint(msg, "row {d}: ({e}, {d}) where ({e}, {d}) is due", .{ r, v, i, want.v, want.i + rk.base }); } return null; @@ -121,8 +149,10 @@ const race_rule = "the largest bf16(x) / T + Gumbel(sample.cu's key at pos, id): "better beyond it; NaN never picked, the lowest +Inf first, a row of NaNs (-inf, base)"; /// One row a launch (the drafter's draw at a position) x a rank's real ids x the rank. -pub fn raceSpec(late: bool) c.Spec { - const name = if (late) "control: inkling2 ops tf_ink2_race1 keyed one position late" else "inkling2 ops tf_ink2_race1 (keyed Gumbel race, a launch a row)"; +pub fn raceSpec(late: bool, many: bool) c.Spec { + const one = if (late) "control: inkling2 ops tf_ink2_race1 keyed one position late" else "inkling2 ops tf_ink2_race1 (keyed Gumbel race, a launch a row)"; + const batched = if (late) "inkling2 dspark control: tf_ink2_dsp_pick_many raced one position late" else "inkling2 dspark tf_ink2_dsp_pick_many, raced (each stream's keys from the table)"; + const name = if (many) batched else one; const served = &[_]c.Shape{ .{ .rows = 4, .n = ref.share, .k = 1 }, .{ .rows = 1, .n = ref.share, .k = 1 }, .{ .rows = 2, .n = ref.share1_real, .k = 2 } }; return .{ .name = name, .accum = .none, .depth = ref.noSums, .out = .raw, .nan = .{ .stated = race_rule }, .served = if (late) served[0..2] else served }; } @@ -149,13 +179,16 @@ fn uniform(pos: u32, id: u32) f32 { pub const Race = struct { kern: *const ops.Kernels, late: bool = false, + /// tf_ink2_dsp_pick_many over raced streams (its kernels) + many: ?*const dk.Kernels = null, shape: c.Shape = undefined, x: []f32 = &.{}, dev: u64 = 0, + tab: u64 = 0, out: [2]u64 = @splat(0), pub fn spec(self: *const Race) c.Spec { - return raceSpec(self.late); + return raceSpec(self.late, self.many != null); } pub fn control(self: *const Race) ?g.Gate { @@ -176,12 +209,18 @@ pub const Race = struct { v.* /= 32; // logits within a few Gumbel widths, so the keys decide }; self.dev = try ref.input(rig, self.x); + if (self.many != null) { + self.tab = try manyTable(rig, shape.rows, true, self.late); + self.out = .{ try rig.output(shape.rows * 16), 0 }; + return true; + } self.out = .{ try rig.output(shape.rows * 4), try rig.output(shape.rows * 4) }; return true; } pub fn run(self: *Race, rig: *rig_.Rig) !void { const rk = rank(self.shape); + if (self.many) |m| return dk.pickMany(m, rig.s, self.dev, rk.stride, rk.n, rk.base, self.tab, 0, self.out[0], self.shape.rows); for (0..self.shape.rows) |r| { const pos = pos0 + r + @intFromBool(self.late); try ops.race1(self.kern, rig.s, self.dev + r * rk.stride * 4, rk.n, rk.base, seed, inv_t, pos, self.out[0] + r * 4, self.out[1] + r * 4); @@ -189,7 +228,7 @@ pub const Race = struct { } pub fn count(self: *const Race) usize { - return self.shape.rows * 8; + return self.shape.rows * @as(usize, if (self.many != null) 16 else 8); } /// The host's score of id i, and its margin: logf's error on both logs, the fp32 roundings around them. @@ -206,8 +245,9 @@ pub const Race = struct { for (0..rows) |r| { const row = self.x[r * rk.stride ..][0..rk.n]; const pos: u32 = @intCast(pos0 + r); - const v = ref.readF32(got, r); - const id = ref.readI32(got, rows + r) - @as(i32, @intCast(rk.base)); + const at = slots(self.many != null, rows, r); + const v = ref.readF32(got, at[0]); + const id = ref.readI32(got, at[1]) - @as(i32, @intCast(rk.base)); const top = scan(row); if (top.v == -std.math.inf(f32) and std.math.isNan(row[0])) { if (id != 0 or v != -std.math.inf(f32)) return try std.fmt.bufPrint(msg, "row {d} of NaNs: ({e}, {d})", .{ r, v, id }); diff --git a/zig/tests/cuda/contract_limits.zig b/zig/tests/cuda/contract_limits.zig index c69140766ff..25073f3e940 100644 --- a/zig/tests/cuda/contract_limits.zig +++ b/zig/tests/cuda/contract_limits.zig @@ -42,7 +42,7 @@ pub fn image(name: []const u8) error{UnknownContractImage}![]const u8 { inline for (.{ "qwen4_projection", "qwen4_hc", "qwen4_gdn", "qwen4_ple", "gemma4_ple" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "tree_round", "act_rows", "gdn_prep", "qk_rows", "norms", "moe", "experts", "qwen36_mtp", "nemotron_attention", "nemotron_route", "nemotron_latent", "qmm_group", "qmm_prefill", "lane_gemv", "prompt16", "qmmf", "ck_experts", "nvfp4_experts", "nvfp4_experts_tile", "nvfp4_experts32", "rank_sum", "prefill_attention", "vit", "embed_rows", "route_rows", "flashnext_gdn", "flashnext_batch", "flashnext_hc", "flashnext_attn", "flashnext_mtp", "qwen_vision", "exl3_linear", "exl3_experts", "exl3_candidate", "experts3", "experts3_prefill", "drama3", "drama3_fp8", "drama3_codec", "glm_mm", "glm_dflash", "glm_glue", "glm_ops", "glm_index", "nemotron_mamba", "sample", "qwen35", "qwen35_bf16_rows", "qwen35_keep", "qwen35_kv8", "w4a8_prefill", "qwen35_draft", "ck_lane", "gdn_train", "train_q4", "train_attn", "flashnext_train", "train", "attn_train", "qwen27_train", "tree_attention", "block_attention", "window_attention", "window_pages", "moe_glue", "dense_rows", "qmm", "flashnext_fact", "flashnext_hcf", "flashnext_fexp", "experts_rows", "nemotron_ops", "minimax_m3", "minimax_m3_attn", "experts_bf16", "nemo_audio", "moss_image", "glm_vision", "idol", "idol_decoder", "lfm3", "lfm2_moe", "lfm2", "dots_mocr", "muse_glue", "muse_attention", "muse_linear", "muse_experts2", "muse_dflash", "muse_dflash2", "ricursive", "ricursive_prep" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); - inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop_math", "inkling2_vision" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); + inline for (.{ "inkling2_attn", "inkling2_pattn", "inkling2_ops", "inkling2_rows", "inkling2_experts", "inkling2_modelopt", "inkling2_loop_math", "inkling2_vision", "inkling2_dspark" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "moss_image_decoder", "moss_image_encoder" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); inline for (.{ "zonos3", "zonos3_codec", "zonos3_encoder", "zonos3_teacher" }) |n| if (std.mem.eql(u8, name, n)) return @field(kk, n); if (std.mem.eql(u8, name, "contract_controls")) return if (options.controls) &controls.bytes else &.{}; diff --git a/zig/tests/cuda/inkling2_dspark_serving.zig b/zig/tests/cuda/inkling2_dspark_serving.zig new file mode 100644 index 00000000000..3f9feeddb76 --- /dev/null +++ b/zig/tests/cuda/inkling2_dspark_serving.zig @@ -0,0 +1,228 @@ +//! CUDA DSpark serving: greedy and sampled parity, chunked prompts and four shared target streams. +const std = @import("std"); +const lanes = @import("lanes"); +const ink = @import("inkling2"); +const check = @import("check.zig"); +const Backend = @FieldType(ink.native.Owned, "backend"); +const Saved = @FieldType(ink.native.Owned, "model").Saved; +const sampled: lanes.Sampling = .{ .seed = 42, .temperature = 0.8, .top_k = 64, .top_p = 0.95 }; + +const Result = struct { + ids: []u32, + proposed: u64, + cached: u32, + reuse_failed: bool, + accepted: u64, + + fn deinit(r: Result, gpa: std.mem.Allocator) void { + gpa.free(r.ids); + } +}; + +fn idsFrom(gpu: check.Gpu, path: []const u8, prefix: []const u8) ![]u32 { + const bytes = try std.Io.Dir.cwd().readFileAlloc(gpu.io, path, gpu.gpa, .limited(1 << 20)); + defer gpu.gpa.free(bytes); + const parsed = try std.json.parseFromSlice(std.json.Value, gpu.gpa, bytes, .{}); + defer parsed.deinit(); + const cases = parsed.value.object.get("cases") orelse return error.DSparkTestFixture; + for (cases.array.items) |case| { + const text = case.object.get("text") orelse continue; + if (!std.mem.startsWith(u8, text.string, prefix)) continue; + const saved = case.object.get("ids") orelse return error.DSparkTestFixture; + const ids = try gpu.gpa.alloc(u32, saved.array.items.len); + for (saved.array.items, ids) |number, *id| id.* = @intCast(number.integer); + return ids; + } + return error.DSparkTestFixture; +} + +fn generate(gpu: check.Gpu, backend: lanes.backend.Backend, facts: lanes.Model, prompt: []const u32, drafts: bool, sampling: ?lanes.Sampling, count: u32, reuse: lanes.stream.Reuse) !Result { + var stream = try lanes.Stream.init(gpu.gpa, .{ .id = "inkling-dspark", .prompt = prompt, .max_new = count, .drafts = drafts, .sampling = sampling, .reuse = reuse }); + defer stream.deinit(gpu.gpa); + var config = try lanes.Config.init(gpu.gpa, facts, ink.native.prompt_rows, ink.native.window_rows); + defer config.deinit(gpu.gpa); + config.timed = false; + config.lone_copies = false; + var clock: lanes.fake.FixedClock = .{}; + var runner = lanes.Engine.init(gpu.gpa, &config, backend, clock.clock()); + defer runner.deinit(); + try runner.addStream(&stream); + var steps: usize = 0; + while (!stream.finished) { + if (steps == 4096) return error.DSparkServingTimedOut; + try runner.step(); + steps += 1; + } + if (stream.reason != .length) return error.DSparkServingDidNotFinish; + return .{ .ids = try gpu.gpa.dupe(u32, stream.emitted()), .proposed = stream.drafted, .accepted = stream.accepted, .cached = stream.cached, .reuse_failed = stream.reuse_failed }; +} + +fn cohort(gpu: check.Gpu, backend: lanes.backend.Backend, facts: lanes.Model, prompts: [4][]const u32, drafts: bool, reuse: [4]lanes.stream.Reuse, count: u32) ![4]Result { + var streams: [4]lanes.Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*s| s.deinit(gpu.gpa); + for (prompts, 0..) |prompt, i| { + streams[i] = try lanes.Stream.init(gpu.gpa, .{ + .id = "inkling-dspark-cohort", + .prompt = prompt, + .max_new = count, + .drafts = drafts, + .sampling = if (i % 2 == 0) null else sampled, + .reuse = reuse[i], + }); + made += 1; + } + var config = try lanes.Config.init(gpu.gpa, facts, ink.native.prompt_rows, ink.native.window_rows); + defer config.deinit(gpu.gpa); + config.timed = false; + config.lone_copies = false; + var clock: lanes.fake.FixedClock = .{}; + var runner = lanes.Engine.init(gpu.gpa, &config, backend, clock.clock()); + defer runner.deinit(); + for (&streams) |*s| try runner.addStream(s); + var steps: usize = 0; + while (true) { + var live = false; + for (&streams) |*s| live = live or !s.finished; + if (!live) break; + if (steps == 4096) return error.DSparkServingTimedOut; + try runner.step(); + steps += 1; + } + var out: [4]Result = undefined; + var done: usize = 0; + errdefer for (out[0..done]) |r| r.deinit(gpu.gpa); + for (&streams, 0..) |*s, i| { + if (s.reason != .length) return error.DSparkServingDidNotFinish; + out[i] = .{ .ids = try gpu.gpa.dupe(u32, s.emitted()), .proposed = s.drafted, .accepted = s.accepted, .cached = s.cached, .reuse_failed = s.reuse_failed }; + done += 1; + } + return out; +} + +/// Capture the target's actual saved prompt state, not a synthetic cached-token count. +fn snapshot(gpu: check.Gpu, loaded: *ink.native.Loaded, prompt: []const u32, cut: u32) !*Saved { + const Keeper = struct { + target: *Backend, + saved: ?*Saved = null, + + fn at(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { + const k: *@This() = @ptrCast(@alignCast(ptr)); + k.saved = k.target.saveState(s, mark) catch null; + } + }; + var s = try lanes.Stream.init(gpu.gpa, .{ .id = "dspark-snapshot", .prompt = prompt, .max_new = 1, .reuse = .{ .marks = &.{cut} } }); + defer s.deinit(gpu.gpa); + defer loaded.backend.release(&s); + var keeper: Keeper = .{ .target = &loaded.target.backend }; + s.reuse.hook = .{ .ptr = &keeper, .at = Keeper.at }; + try loaded.backend.prefill(&s); + return keeper.saved orelse return error.DSparkSnapshotNotSaved; +} + +fn resumedAt(gpu: check.Gpu, loaded: *ink.native.Loaded, drafted: *lanes.drafted.Drafted, prompt: []const u32, cut: u32, sampling: ?lanes.Sampling) !void { + const saved = try snapshot(gpu, loaded, prompt, cut); + defer loaded.target.backend.dropState(saved); + const plain = try generate(gpu, loaded.backend, loaded.facts, prompt, false, sampling, 32, .{}); + defer plain.deinit(gpu.gpa); + const proposed = try generate(gpu, drafted.backend(), drafted.facts(loaded.facts), prompt, true, sampling, 32, .{ .saved = saved, .at = cut }); + defer proposed.deinit(gpu.gpa); + if (proposed.reuse_failed or proposed.cached != cut) return error.DSparkSnapshotNotRestored; + if (!std.mem.eql(u32, plain.ids, proposed.ids)) return error.DSparkChangedResumedTokens; + if (proposed.proposed == 0) return error.DSparkResumedNotExercised; + check.pass("Mini CUDA DSpark resumed target equality: cut {d}, {d} proposed", .{ cut, proposed.proposed }); +} + +pub fn run(gpu: check.Gpu, model: []const u8, ids_path: []const u8) !void { + const short = try idsFrom(gpu, ids_path, "def f("); + defer gpu.gpa.free(short); + const chat = try idsFrom(gpu, ids_path, "<|message_user|>"); + defer gpu.gpa.free(chat); + if (short.len < 16 or short.len > 512) return error.DSparkTestPromptLength; + const long = try gpu.gpa.alloc(u32, 2053); + defer gpu.gpa.free(long); + for (long, 0..) |*id, i| id.* = short[i % short.len]; + var loaded = try ink.native.open(gpu.gpa, gpu.io, gpu.ctx, model, null, .{ .context = 4096, .drafts = true }); + defer loaded.deinit(loaded.ctx); + const owned = try ink.native.openDrafter(gpu.gpa, gpu.io, loaded.ctx, model, 4); + defer owned.close(owned.ctx); + var drafted = try lanes.drafted.Drafted.init(gpu.gpa, loaded.backend, owned.drafter); + defer drafted.deinit(); + try owned.reserve(owned.ctx, 1); + for ([5][]const u32{ short, long, short, chat, chat }, 0..) |prompt, case| { + const count: u32 = if (case == 1) 24 else 96; + const sampling: ?lanes.Sampling = if (case == 2 or case == 3) sampled else null; + const plain = try generate(gpu, loaded.backend, loaded.facts, prompt, false, sampling, count, .{}); + defer plain.deinit(gpu.gpa); + const proposed = try generate(gpu, drafted.backend(), drafted.facts(loaded.facts), prompt, true, sampling, count, .{}); + defer proposed.deinit(gpu.gpa); + if (!std.mem.eql(u32, plain.ids, proposed.ids)) return error.DSparkChangedTokens; + if (proposed.proposed == 0 or (sampling == null and proposed.accepted == 0)) return error.DSparkNotExercised; + check.pass("Mini CUDA DSpark target equality: case {d}, {d} proposed, {d} accepted", .{ case, proposed.proposed, proposed.accepted }); + } + try resumedAt(gpu, &loaded, &drafted, short, @intCast(short.len / 2), null); + try resumedAt(gpu, &loaded, &drafted, chat, @intCast(chat.len - 1), sampled); + try resumedAt(gpu, &loaded, &drafted, long, 2048, sampled); + try loaded.reserve(loaded.ctx, 4); + try owned.reserve(owned.ctx, 4); + const prompts = [4][]const u32{ short, chat, long, short[3..] }; + const plain = try cohort(gpu, loaded.backend, loaded.facts, prompts, false, .{ .{}, .{}, .{}, .{} }, 32); + defer for (plain) |r| r.deinit(gpu.gpa); + const proposed = try cohort(gpu, drafted.backend(), drafted.facts(loaded.facts), prompts, true, .{ .{}, .{}, .{}, .{} }, 32); + defer for (proposed) |r| r.deinit(gpu.gpa); + var accepted: u64 = 0; + for (plain, proposed) |want, got| { + if (!std.mem.eql(u32, want.ids, got.ids)) return error.DSparkChangedConcurrentTokens; + accepted += got.accepted; + } + if (accepted == 0) return error.DSparkConcurrentNotExercised; + check.pass("Mini CUDA DSpark four-stream greedy/sampled target equality, {d} accepted", .{accepted}); + // Identical prompts and sampling settings must give the same draft acceptance in separate batched slots. + const identical = [4][]const u32{ short, short, short, short }; + const repeated = try cohort(gpu, drafted.backend(), drafted.facts(loaded.facts), identical, true, .{ .{}, .{}, .{}, .{} }, 64); + defer for (repeated) |r| r.deinit(gpu.gpa); + for ([_][2]usize{ .{ 0, 2 }, .{ 1, 3 } }) |pair| { + const first = repeated[pair[0]]; + const second = repeated[pair[1]]; + if (!std.mem.eql(u32, first.ids, second.ids) or first.proposed != second.proposed or first.accepted != second.accepted) + return error.DSparkBatchChangedProposal; + } + if (repeated[0].accepted == 0 or repeated[1].accepted == 0) return error.DSparkBatchNotExercised; + check.pass("Mini CUDA DSpark identical four-stream proposals match per sampling mode", .{}); + const code_cut: u32 = @intCast(short.len / 2); + const chat_cut: u32 = @intCast(chat.len - 1); + const code_saved = try snapshot(gpu, &loaded, short, code_cut); + defer loaded.target.backend.dropState(code_saved); + const chat_saved = try snapshot(gpu, &loaded, chat, chat_cut); + defer loaded.target.backend.dropState(chat_saved); + const long_saved = try snapshot(gpu, &loaded, long, 2048); + defer loaded.target.backend.dropState(long_saved); + const reuse = [4]lanes.stream.Reuse{ + .{ .saved = code_saved, .at = code_cut }, + .{ .saved = chat_saved, .at = chat_cut }, + .{ .saved = long_saved, .at = 2048 }, + .{}, + }; + const resumed = try cohort(gpu, drafted.backend(), drafted.facts(loaded.facts), prompts, true, reuse, 32); + defer for (resumed) |r| r.deinit(gpu.gpa); + for (resumed, plain, 0..) |got, want, i| { + if (!std.mem.eql(u32, got.ids, want.ids)) return error.DSparkChangedResumedConcurrentTokens; + if (got.reuse_failed or (i < 3 and got.cached != reuse[i].at)) return error.DSparkConcurrentSnapshotNotRestored; + } + check.pass("Mini CUDA DSpark four-stream resumed greedy/sampled target equality", .{}); + // A closed drafter must release its CUDA module and permit a fresh head on the same target. + var rebound = try ink.native.open(gpu.gpa, gpu.io, gpu.ctx, model, null, .{ .context = 512, .drafts = true }); + defer rebound.deinit(rebound.ctx); + const first_head = try ink.native.openDrafter(gpu.gpa, gpu.io, rebound.ctx, model, 1); + first_head.close(first_head.ctx); + const next_head = try ink.native.openDrafter(gpu.gpa, gpu.io, rebound.ctx, model, 1); + defer next_head.close(next_head.ctx); + var next_drafted = try lanes.drafted.Drafted.init(gpu.gpa, rebound.backend, next_head.drafter); + defer next_drafted.deinit(); + const next_plain = try generate(gpu, rebound.backend, rebound.facts, short, false, null, 32, .{}); + defer next_plain.deinit(gpu.gpa); + const next_proposed = try generate(gpu, next_drafted.backend(), next_drafted.facts(rebound.facts), short, true, null, 32, .{}); + defer next_proposed.deinit(gpu.gpa); + if (!std.mem.eql(u32, next_plain.ids, next_proposed.ids) or next_proposed.accepted == 0) return error.DSparkReattachChangedTokens; + check.pass("Mini CUDA DSpark reattached head preserves target tokens", .{}); +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index b5ebe8ba616..1c5c69acdf7 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -423,6 +423,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "kolibri-layers")) return kolibri_layer_tests.layers(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "kolibri-full")) return kolibri_tests.full(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2)); if (std.mem.eql(u8, cmd, "inkling2-serving")) return @import("inkling2_serving_tests.zig").run(gpu, try arg(rest, 0), try arg(rest, 1)); + if (std.mem.eql(u8, cmd, "inkling2-dspark-serving")) return @import("inkling2_dspark_serving.zig").run(gpu, try arg(rest, 0), try arg(rest, 1)); if (std.mem.eql(u8, cmd, "kolibri-pages")) return @import("kolibri_pages_tests.zig").pages(gpu, rest); if (std.mem.eql(u8, cmd, "kolibri-greedy")) return kolibri_tests.greedy(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); if (std.mem.eql(u8, cmd, "kolibri-logits")) return kolibri_tests.logits(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), if (rest.len > 3) rest[3] else null);