diff --git a/docs/drafter-release.md b/docs/drafter-release.md index c2818a72ae8..21cc85d8c52 100644 --- a/docs/drafter-release.md +++ b/docs/drafter-release.md @@ -2,8 +2,9 @@ A drafter release is a folder that a server can check against the target it loaded before it drafts a single token. It says which target the drafter was trained against, how that target turns tokens into rows and rows into logits, -which of the target's rows the drafter reads, and the drafter's own shape. The format is version 1. It describes one -architecture, the block drafter, and is read by `zig/src/core/drafter_release.zig` and `drafter_layout.zig`. +which of the target's rows the drafter reads, and the drafter's own shape. The format is version 1. It describes two +architectures, the block drafter and EAGLE-3 (`eagle3`), and is read by `zig/src/core/drafter_release.zig` and +`drafter_layout.zig`. Releases published before it are read into the same checks (see "Published before version 1"). A release holds three files: @@ -86,7 +87,8 @@ loaded target reports, and refuses the release on the first one that differs, na ### drafter and serving The block drafter's shape. Row 0 of a block is a chain head on the anchor's own row; rows 1 to `block - 1` are drafted -in the same pass. `pred_rank` and `spine_rank` are 0 when the predecessor head or the spine is absent. `hidden` must +in the same pass. An `eagle3` drafter drafts one row a pass (`block` 1, no predecessor head or spine): each chain step +reads its own last output in place of the fused taps, and `serving.depth` is 1 to 8. `pred_rank` and `spine_rank` are 0 when the predecessor head or the spine is absent. `hidden` must equal `target.hidden`, because the target's head reads the drafter's rows. `serving` holds defaults a server may override: `depth` (1 to `block`), and the formats the body and the head slice are converted to at load (`bf16`, `fp8` or `nvfp4`). @@ -103,12 +105,14 @@ Every tensor is bf16, f16 or f32. D is `drafter.hidden`, T is `target.hidden`, A | `target.head_bias` | [V] | `head_bias` is true | | `fuse.weight` | [D, len(taps) x T] | always | | `fc.weight` | [D, T + D] | always: cat(embedding of the token after the row, fused row) | -| `mask` | [D] | always | -| `layers.i.{q,k,v,ck,cv}.weight` | [A, D] | each layer | +| `mask` | [D] | block drafter | +| `layers.i.{q,k,v}.weight` | [A, D] | each layer | +| `layers.i.{ck,cv}.weight` | [A, D] | each layer, block drafter | | `layers.i.o.weight` | [D, A] | each layer | | `layers.i.{gate,up}.weight` | [ffn, D] | each layer | | `layers.i.down.weight` | [D, ffn] | each layer | -| `layers.i.{n1,n2,nc}.w` | [D] | each layer | +| `layers.i.{n1,n2}.w` | [D] | each layer | +| `layers.i.nc.w` | [D] | each layer, block drafter | | `out_norm.w` | [D] | always | | `pred_h.weight`, `pred_e.weight`, `pred_out.weight` | [R, D], [R, T], [D, R] | `pred_rank` R > 0 | | `spine_n.i.w`, `spine_a.i.weight`, `spine_u.i.weight` | [D], [S, D], [D, S] | `spine_rank` S > 0, i < layers - 1 | @@ -142,8 +146,23 @@ format. Its `config.json` counts taps from 0 (44, 47, 49), has no adapter, and i and neither target tensor. Re-exported with the embedding and its 60,614 head rows, and without `inp.weight`, its 66 tensors pass the layout check above. +## Published before version 1 + +Kolibri-1's two drafters on the Hub were published before this format: `josch15366/Kolibri-1-EAGLE3-drafter` +(`kolibri1-eagle3-drafter`) and `josch15366/Kolibri-1-block-drafter` (`kolibri1-block-drafter`). +`zig/src/core/drafter_published.zig` reads such a folder into a version 1 `Config` and then runs the same `validate`, +`check`, `parseVocab` and tensor checks: + +- taps count from 0 there (44, 47, 49): each becomes id + 1 (45, 48, 50); normed, bf16; +- `target` names a repo only; it must equal the loaded target's, and the adapter is the loaded target's; +- the embedding and head rows are not in the file: the server takes them from the target it loaded; +- the EAGLE-3 release names its layer `blocks.0.*` and stores its norms as f32; the block release holds an unused + `inp.weight`, admitted by name; any other tensor is refused; +- `window` (2,048, the training window) and the weights' file name are fixed; the block release's `serving` keeps its + values, the EAGLE-3 release serves depth 2 in bf16. + ## Not in version 1 - Weights stored as FP8 or NVFP4. The release stores floats; `serving` converts them at load. - A tap that merges several residual streams. `stream` has one value until a family needs another. -- Drafter architectures other than the block drafter. +- Drafter architectures other than the block drafter and EAGLE-3. diff --git a/docs/recipes/kolibri-1.md b/docs/recipes/kolibri-1.md index b36b5483de2..98f4fe3b698 100644 --- a/docs/recipes/kolibri-1.md +++ b/docs/recipes/kolibri-1.md @@ -2,7 +2,7 @@ This page describes the native engine. `kolibri1` serves Aleph Alpha's Kolibri-1, a research checkpoint, on one NVIDIA GPU through the lane host. It is a draft family: plain decoding and copy drafts from the prompt's own text are -in; the EAGLE-3 drafter is the next step and is not loaded here. +in, and `--drafter` loads the published EAGLE-3 drafter (off unless asked). ## Checkpoint @@ -44,8 +44,8 @@ rounds run eager. Both give a row the same bits. stream: at a 32k window 1.29 GiB a stream, at 64k 1.92 GiB. Each sliding layer's ring holds a pass and its window (8,768 keys). - The prompt cache keeps a stream's state at any row: full layers' keys up to it and each sliding layer's last 512. -- Drafts: the lane core's copy drafts verify in windows of up to 16 rows. There is no draft head yet, so a request - for head drafts and `--drafter` are refused by name. +- Drafts: the lane core's copy drafts verify in windows of up to 16 rows. `--drafter DIR` adds the EAGLE-3 drafter + (below); a request for the model's own draft head is refused by name, as it has none. - Refused at load: other quantizations, `norm_topk_prob`, other layer kinds, a config with a vision tower, shapes the shared kernels do not take, `--vision`, `--precision` and a captured kernel set (`TENSORFOLD_CUDA_KERNELS`). @@ -82,6 +82,42 @@ GB10, greedy, served by `tensorfold-native` with copy drafts on: Cold prompts (`bench_cache.py --require-cold --repeats 3`, `--prompt-cache-gib 0`, median of the cold requests): 2,048 tokens 0.97 s, 8,192 tokens 3.72 s, 32,768 tokens 16.8 s, 64,000 tokens 37.8 s to the first token. -## Next - -- The EAGLE-3 drafter through the lane core's drafter interface. +## EAGLE-3 drafter + +`--drafter DIR` loads `josch15366/Kolibri-1-EAGLE3-drafter` at revision `6430e5dc7453dd4ea57022a4cde46178afe89094` +(`model.safetensors` sha256 `5f1f38bf3d303faa119e7348f1a6ba4128db9d4febfc23eaaf9310e7a3c7187e`). Its model card +releases the weights under Apache-2.0 and notes that part of its German training text (`mayflowergmbh/alpaca-gpt4_de`) +states no licence and derives from CC BY-NC 4.0 data; TensorFold's licence does not cover the weights. It is one +decoder layer over Kolibri's layers 45, 48 and 50, a 32,768-token draft vocabulary, bf16. It runs on the shared CUDA +operators (no kernels of its own) through the lane core's drafter interface, two drafts a round. Every draft is +verified by the target, so replies are the same tokens as without it, greedy and seeded, at any stream count. +`--drafter-bits` takes 0 or 4 (the default); both serve the release as published. + +Refused at load, by name, before any request is queued: a release of another architecture (the block drafter +`josch15366/Kolibri-1-block-drafter` is not served on CUDA), a release for another target, a draft vocabulary or +tensor shape that does not match the release's config, a stream opened before the drafter, and a CUDA memory budget +that leaves less than the drafter's weights, scratch and caches need (computed from its config before anything is +allocated: about 0.44 GiB with one stream, plus a 23 MiB slot for each further stream a fixed `--parallel` asks, plus +the first stream's paged window). `--parallel 1`, `2` and `3` time the rounds their slots can take. + +GB10, 24 prompts of 256 tokens, a distinct prompt per stream. Each stream count ran alone, every run on a freshly +started server (page cache dropped before each start): a noise floor from a round of main against itself, then 3 +rounds of A-B-B-A with main's copy drafts as A. Every run of both arms gave the same replies. + +| cell | copy drafts | with `--drafter` | median gap | noise floor | rounds worse | +| --- | ---: | ---: | ---: | ---: | ---: | +| 1 stream, greedy, tok/s | 51.3 | 65.7 | +27.9 % | 0.33 % | 0 of 3 | +| 1 stream, default sampling, tok/s | 52.7 | 65.8 | +24.4 % | 0.02 % | 0 of 3 | +| 4 streams, tok/s | 109.3 | 114.1 | +4.1 % | 0.02 % | 0 of 3 | +| 8 streams, tok/s | 140.5 | 138.8 | -1.1 % | 0.53 % | 3 of 3 | +| cold 7,899-token prompt, first token, s | 3.635 | 1.976 | +45.7 % | 0.04 % | 0 of 3 | +| same prompt, first to second token, s | 0.021 | 0.079 | -283 % | 2.38 % | 3 of 3 | + +Tokens a round: 1.07 with copy drafts; with the drafter 1.96, 1.54 and 1.63 at 1, 4 and 8 streams. + +The drafter absorbs a prompt's rows after its first token, before its first draft: the first token comes 1.66 s +sooner, the second 58 ms later, so the second token of a cold prompt still lands 1.6 s sooner (2.05 against 3.66 s). +At 8 streams the absorb pass of each round (it reads the drafter's weights, about 1 ms) costs more than the drafts +gain. A prompt-cache hit keeps its restore: the drafter's state is rebuilt from the prompt's first row when the +prompt fits its 2,048-row window and the restore lies within the target's sliding window (512 rows); other restores +inside the drafter's window draft fillers, and their replies are a cold prompt's. diff --git a/docs/supported-models.md b/docs/supported-models.md index d1b18a74f39..181cf074abd 100644 --- a/docs/supported-models.md +++ b/docs/supported-models.md @@ -50,7 +50,7 @@ Conversions are explicitly marked: their upstream weights need the linked conver | Step-5-Preview, converted affine | `hf download stepfun-ai/Step-5-Preview --local-dir ~/models/step5-preview-fp8` | One 256 GB Mac; text 166.9 GiB, MTP adds 2.5 GiB and vision 3.7 GiB. | [Convert and serve](recipes/step-5-preview.md). The documented 256 GB setup serves converted affine weights; converting the upstream FP8 download needs Python and mlx. | | MiniMax-M3.1-Flash, community affine 3/4-bit | `hf download BobClawblaw/MiniMax-M3.1-Flash-MLX-mix34 --revision 9524999057e0d277d26438606e033e2191fb465c --local-dir ~/models/MiniMax-M3.1-Flash-MLX-mix34`
`hf download BobClawblaw/MiniMax-M3.1-Flash-MLX-mix256k --revision 916e7ca1044f1c3e7566163096243c940327224d --local-dir ~/models/MiniMax-M3.1-Flash-MLX-mix256k` | One 256 GB M5 Ultra; 203.7 GiB (32,768-token window) or 189.2 GiB (147,456), plus caches. | [MiniMax-M3.1-Flash](recipes/minimax-m3.1-flash.md). Set `MINIMAX_LOAD_LIMIT_GB`; images with `--vision`. Community checkpoints: lossy conversions of MiniMax's NVFP4 release (KL 0.244 / 0.295). MiniMax Community License. | | Recursive Flint 40B-A2.5B, MLX INT4 | `hf download RecursiveSI/flint-int4 --revision 3b93f9053b530488405ae9fca51d4900d6ce21f0 --local-dir ~/models/flint-int4` | One M5 Mac; M5 Ultra checked; 21.4 GiB resident plus caches. M1-M4 untested. | [Flint](recipes/flint.md). Text and tools; always reasons. Optional `incoai/Flint-DFlash2` through `--drafter` on M5, up to four streams. | -| Kolibri-1, block FP8 (research) | `tensorfold pull Aleph-Alpha/Kolibri-1@e52eb4627d11516b0c01de49210ab5a4e4061444` | One NVIDIA GPU; GB10 measured; 78.9 GB checkpoint. | [Kolibri](recipes/kolibri-1.md). Text only; copy drafts, no EAGLE-3/neural drafter. | +| Kolibri-1, block FP8 (research) | `tensorfold pull Aleph-Alpha/Kolibri-1@e52eb4627d11516b0c01de49210ab5a4e4061444` | One NVIDIA GPU; GB10 measured; 78.9 GB checkpoint. | [Kolibri](recipes/kolibri-1.md). Text only; copy drafts, EAGLE-3 drafter with `--drafter`. | | Liquid AI d1-3B, decisions | Not documented yet. | Native CUDA; RAM minimum not published. | [API section](run-guide.md#serve-flags). `/v1/systemone` and `/v1/decisions`. | | Fish Audio Drama 3, speech | Not documented yet. | Native Metal or CUDA; GB10 measured. | [Release audio instructions](../CHANGELOG.md#110), [reference voices and dialogue speakers](drama-http-voices.md). `/v1/audio/speech` with [sampling controls](speech-sampling.md); checkpoint and `codec.pth` required. | | Drama 3 pruned NVFP4, speech | `hf download plotarmordev/drama-3-NVFP4-Pruned --revision 494db08481db952f834b2241bce63fb3dfa72554 --local-dir drama-3-NVFP4-Pruned` | Native Metal or CUDA; roughly 21 GiB checkpoint plus runtime state. Not a minimum-RAM or cross-backend quality claim. | Packed experts, BF16 dense/tower weights and FP32 accumulation; no conversion. [Serve and check it](drama-3-nvfp4.md); the [measured receipt](receipts/drama3-pruned-main/README.md) covers Metal and a GB10. | diff --git a/zig/build/lane_halt_host.zig b/zig/build/lane_halt_host.zig index 5b2308768f5..f102658ba4f 100644 --- a/zig/build/lane_halt_host.zig +++ b/zig/build/lane_halt_host.zig @@ -28,6 +28,8 @@ pub fn steps(b: *std.Build) void { b.step("test-lane-lone-host", "Existing lone-driver handoff and reclaim with a fake backend").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{"lone driver"} })).step); b.step("test-lane-api-host", "Shared lane host and engine API CPU regressions").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api })).step); b.step("test-shared-price-learning-host", "Independent plain prices and signed row learning together without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lanes, .filters = &.{ "shared combined prices:", "shared price modes:" } })).step); + b.step("test-hold-pass-host", "A drafter's timed hold pass priced against copy rounds under a legacy cap, without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lanes, .filters = &.{"hold pass:"} })).step); + b.step("test-lazy-absorb-host", "Depth-0 rows owed to a drafter and absorbed before its next hold, as eager absorbing, without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lanes, .filters = &.{"lazy absorb:"} })).step); b.step("test-wait-reasons-host", "Stored wait reasons in the load ledger with a fake backend and planner").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = api, .filters = &.{"wait reason ledger:"} })).step); const spares = b.step("test-cache-spares-host", "Fallback and guarded keeps preserve cache retention"); for ([_][]const u8{ "lane_cache_promise_test.zig", "prompt_cache_promised_test.zig" }) |file| { diff --git a/zig/kernels/cuda/dense_rows.cu b/zig/kernels/cuda/dense_rows.cu index bb6a33c351a..9ff2724b090 100644 --- a/zig/kernels/cuda/dense_rows.cu +++ b/zig/kernels/cuda/dense_rows.cu @@ -54,10 +54,58 @@ __device__ __forceinline__ void tile(const __nv_bfloat16* x, int64_t x_stride, c } } +// tile's sums, RR rows x CC columns a warp: each sum's k order and shuffle tree, so tile's bits +template +__device__ __forceinline__ void block_tile(const __nv_bfloat16* x, int64_t x_stride, const __nv_bfloat16* w, float* out, + int64_t out_stride, int rows, int n, int k) { + const int lane = threadIdx.x & 31; + const int c0 = blockIdx.x * CC; + const int r0 = (blockIdx.y * WARPS + (threadIdx.x >> 5)) * RR; + if (r0 >= rows) return; + float acc[RR][CC]; +#pragma unroll + for (int r = 0; r < RR; ++r) +#pragma unroll + for (int c = 0; c < CC; ++c) acc[r][c] = 0.f; + for (int k0 = lane * VEC; k0 < k; k0 += 32 * VEC) { + float wf[CC][VEC]; +#pragma unroll + for (int c = 0; c < CC; ++c) { + const int col = c0 + c < n ? c0 + c : n - 1; // a column past n: computed, never stored + unpack(*reinterpret_cast(w + static_cast(col) * k + k0), wf[c]); + } +#pragma unroll + for (int r = 0; r < RR; ++r) { + if (r0 + r >= rows) break; + float xf[VEC]; + unpack(*reinterpret_cast(x + (r0 + r) * x_stride + k0), xf); +#pragma unroll + for (int c = 0; c < CC; ++c) +#pragma unroll + for (int i = 0; i < VEC; ++i) acc[r][c] = __fmaf_rn(xf[i], wf[c][i], acc[r][c]); + } + } +#pragma unroll + for (int r = 0; r < RR; ++r) +#pragma unroll + for (int c = 0; c < CC; ++c) { + float v = acc[r][c]; + for (int m = 16; m > 0; m >>= 1) v = __fadd_rn(v, __shfl_xor_sync(0xFFFFFFFFu, v, m)); + if (lane == 0 && r0 + r < rows && c0 + c < n) out[(r0 + r) * out_stride + c0 + c] = v; + } +} + } // namespace tf_dense using namespace tf_dense; +// A prompt's rows: tf_dense_rows' sums, 8 rows x 8 columns a warp (grid: n / 8 column groups, rows / 64). +extern "C" __global__ void __launch_bounds__(WARPS * 32) tf_dense_rows_tiled(const __nv_bfloat16* x, long long x_stride, + const __nv_bfloat16* w, float* out, + long long out_stride, int rows, int n, int k) { + block_tile<8, 8>(x, x_stride, w, out, out_stride, rows, n, k); +} + #define TF_DENSE_ROWS(RT) \ extern "C" __global__ void __launch_bounds__(WARPS * 32) tf_dense_rows_##RT( \ const __nv_bfloat16* x, long long x_stride, const __nv_bfloat16* w, float* out, long long out_stride, \ diff --git a/zig/src/core/contract/registry_shared_attention.zig b/zig/src/core/contract/registry_shared_attention.zig index bc691dbe60b..424c4c8aec4 100644 --- a/zig/src/core/contract/registry_shared_attention.zig +++ b/zig/src/core/contract/registry_shared_attention.zig @@ -1,7 +1,7 @@ //! The shared attention, sigmoid routing and dense-row CUDA launch records; values retained from their fixtures. const std = @import("std"); const wattn_symbol = "_ZN16tf_window_prompt12wattn_kernelILi128ELi8ELi{d}ELi8EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiifii"; -pub fn records(comptime Record: type) [41]Record { +pub fn records(comptime Record: type) [42]Record { return .{ .{ .launch = .{ .name = "tree attention tf_tree_paths", .symbol = "tf_tree_paths", .image = "tree_attention", .threads = 128 }, .usage = .{ .{ .regs = 32, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 40, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 }, .{ .regs = 30, .static = 0, .bound = 0 } } }, .{ .launch = .{ .name = "tree attention tf_tree_shared", .symbol = "tf_tree_shared", .image = "tree_attention", .threads = 128, .dynamic = 65536, .opt_in = true }, .usage = .{ .{ .regs = 202, .static = 0, .bound = 128 }, .{ .regs = 202, .static = 0, .bound = 128 }, .{ .regs = 202, .static = 0, .bound = 128 }, .{ .regs = 212, .static = 0, .bound = 128 }, .{ .regs = 212, .static = 0, .bound = 128 } } }, @@ -44,6 +44,7 @@ pub fn records(comptime Record: type) [41]Record { .{ .launch = .{ .name = "dense rows tf_dense_rows_4", .symbol = "tf_dense_rows_4", .image = "dense_rows", .threads = 256 }, .usage = .{ .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 38, .static = 0, .bound = 256 }, .{ .regs = 45, .static = 0, .bound = 256 }, .{ .regs = 45, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "dense rows tf_dense_rows_16", .symbol = "tf_dense_rows_16", .image = "dense_rows", .threads = 256 }, .usage = .{ .{ .regs = 79, .static = 0, .bound = 256 }, .{ .regs = 79, .static = 0, .bound = 256 }, .{ .regs = 79, .static = 0, .bound = 256 }, .{ .regs = 98, .static = 0, .bound = 256 }, .{ .regs = 98, .static = 0, .bound = 256 } } }, .{ .launch = .{ .name = "dense rows tf_dense_rows_32", .symbol = "tf_dense_rows_32", .image = "dense_rows", .threads = 256 }, .usage = .{ .{ .regs = 127, .static = 0, .bound = 256 }, .{ .regs = 127, .static = 0, .bound = 256 }, .{ .regs = 127, .static = 0, .bound = 256 }, .{ .regs = 180, .static = 0, .bound = 256 }, .{ .regs = 180, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "dense rows tf_dense_rows_tiled", .symbol = "tf_dense_rows_tiled", .image = "dense_rows", .threads = 256 }, .usage = .{ .{ .regs = 153, .static = 0, .bound = 256 }, .{ .regs = 153, .static = 0, .bound = 256 }, .{ .regs = 153, .static = 0, .bound = 256 }, .{ .regs = 188, .static = 0, .bound = 256 }, .{ .regs = 188, .static = 0, .bound = 256 } } }, }; } diff --git a/zig/src/core/drafter_layout.zig b/zig/src/core/drafter_layout.zig index a9b9fb2de82..e875654b8da 100644 --- a/zig/src/core/drafter_layout.zig +++ b/zig/src/core/drafter_layout.zig @@ -1,4 +1,4 @@ -//! A block-drafter release's tensors: the names and shapes its config.json implies, and a release folder read whole. +//! A drafter release's tensors: the names and shapes its config.json implies, and a release folder read whole. const std = @import("std"); const Io = std.Io; @@ -25,14 +25,17 @@ pub fn expected(a: std.mem.Allocator, c: *const Config) ![]Want { if (t.head_bias) try out.append(a, one("target.head_bias", v)); try out.append(a, two("fuse.weight", d, c.taps.ids.len * @as(usize, t.hidden))); // the taps, concatenated try out.append(a, two("fc.weight", d, @as(usize, t.hidden) + d)); // cat(embed(token after the row), fused row) - try out.append(a, one("mask", d)); // block rows 1.. start from it + const block = c.architecture == .@"block-drafter"; // eagle3: a row's keys come from its own q/k/v, no mask row + if (block) try out.append(a, one("mask", d)); // block rows 1.. start from it + const projections: []const []const u8 = if (block) &.{ "q", "k", "v", "ck", "cv" } else &.{ "q", "k", "v" }; + const norms: []const []const u8 = if (block) &.{ "n1", "n2", "nc" } else &.{ "n1", "n2" }; for (0..s.layers) |i| { - for ([_][]const u8{ "q", "k", "v", "ck", "cv" }) |p| try out.append(a, two(try layer(a, i, p, "weight"), att, d)); + for (projections) |p| try out.append(a, two(try layer(a, i, p, "weight"), att, d)); try out.append(a, two(try layer(a, i, "o", "weight"), d, att)); try out.append(a, two(try layer(a, i, "gate", "weight"), s.ffn, d)); try out.append(a, two(try layer(a, i, "up", "weight"), s.ffn, d)); try out.append(a, two(try layer(a, i, "down", "weight"), d, s.ffn)); - for ([_][]const u8{ "n1", "n2", "nc" }) |p| try out.append(a, one(try layer(a, i, p, "w"), d)); + for (norms) |p| try out.append(a, one(try layer(a, i, p, "w"), d)); } try out.append(a, one("out_norm.w", d)); if (s.pred_rank > 0) { @@ -48,19 +51,41 @@ pub fn expected(a: std.mem.Allocator, c: *const Config) ![]Want { return out.items; } +/// How a file names the format's tensors: the format's own names, or a layout published before it. +pub const Names = struct { + layers: []const u8 = "layers", // prefix of layer i's tensors ("blocks" in an eagle3 release published before v1) + own_target: bool = false, // the target's embed and head come from the loaded target, not from the file + unused: []const []const u8 = &.{}, // tensors the file may hold that no drafter reads (named, never guessed) + + /// The file's name for the format's `name` (`a` owns it). + pub fn of(n: Names, a: std.mem.Allocator, name: []const u8) ![]const u8 { + if (!std.mem.startsWith(u8, name, "layers.") or std.mem.eql(u8, n.layers, "layers")) return name; + return std.fmt.allocPrint(a, "{s}{s}", .{ n.layers, name["layers".len..] }); + } +}; + /// The weights' header holds exactly the tensors `c` implies, each float (bf16, f16 or f32) at its shape. pub fn checkWeights(a: std.mem.Allocator, c: *const Config, header: safetensors.Header, why: *Why) !void { - const want = try expected(a, c); - for (want) |w| { - const e = header.get(w.name) orelse return refuse(why, "{s} has no {s}", .{ c.weights, w.name }); - if (e.dtype != .bf16 and e.dtype != .f16 and e.dtype != .f32) return refuse(why, "{s} is {s}; the format stores bf16, f16 or f32", .{ w.name, @tagName(e.dtype) }); - if (e.rank != w.rank or !std.mem.eql(usize, e.shape[0..e.rank], w.shape[0..w.rank])) return refuse(why, "{s} is {any}; config.json implies {any}", .{ w.name, e.shape[0..e.rank], w.shape[0..w.rank] }); + return checkWeightsNamed(a, c, header, .{}, why); +} + +/// checkWeights under `names`: the target's tensors left out when it supplies them, `unused` ones admitted by name. +pub fn checkWeightsNamed(a: std.mem.Allocator, c: *const Config, header: safetensors.Header, names: Names, why: *Why) !void { + var held: std.StringHashMapUnmanaged(void) = .empty; + for (try expected(a, c)) |w| { + if (names.own_target and std.mem.startsWith(u8, w.name, "target.")) continue; + const name = try names.of(a, w.name); + try held.put(a, name, {}); + const e = header.get(name) orelse return refuse(why, "{s} has no {s}", .{ c.weights, name }); + if (e.dtype != .bf16 and e.dtype != .f16 and e.dtype != .f32) return refuse(why, "{s} is {s}; the format stores bf16, f16 or f32", .{ name, @tagName(e.dtype) }); + if (e.rank != w.rank or !std.mem.eql(usize, e.shape[0..e.rank], w.shape[0..w.rank])) return refuse(why, "{s} is {any}; config.json implies {any}", .{ name, e.shape[0..e.rank], w.shape[0..w.rank] }); } - if (header.count() != want.len) for (header.keys()) |name| { - for (want) |w| { - if (std.mem.eql(u8, w.name, name)) break; + for (header.keys()) |name| { + if (held.contains(name)) continue; + for (names.unused) |u| { + if (std.mem.eql(u8, u, name)) break; } else return refuse(why, "{s} holds {s}, which the format does not name", .{ c.weights, name }); - }; + } } /// A release folder read and checked whole: config.json, the draft vocabulary and the weights' header. @@ -92,7 +117,7 @@ pub const Release = struct { }; /// A safetensors file's header, read without mapping its data. -fn readHeader(a: std.mem.Allocator, io: Io, dir: Io.Dir, name: []const u8, why: *Why) !safetensors.Header { +pub fn readHeader(a: std.mem.Allocator, io: Io, dir: Io.Dir, name: []const u8, why: *Why) !safetensors.Header { var f = try dir.openFile(io, name, .{}); defer f.close(io); const len = try f.length(io); diff --git a/zig/src/core/drafter_published.zig b/zig/src/core/drafter_published.zig new file mode 100644 index 00000000000..26601050eed --- /dev/null +++ b/zig/src/core/drafter_published.zig @@ -0,0 +1,131 @@ +//! A drafter release published before format v1 (Kolibri-1's two on the Hub) as a v1 Config, under the same checks. + +const std = @import("std"); +const Io = std.Io; +const release = @import("drafter_release.zig"); +const layout = @import("drafter_layout.zig"); +const Why = release.Why; + +/// Context rows a published drafter attends to: the window both were trained with (not in their config.json). +pub const window: u32 = 2048; +/// The weights' file name in a published release (not in their config.json). +pub const weights = "model.safetensors"; + +/// A published config.json's architecture and what it is in the format. +const Arch = struct { name: []const u8, as: release.Architecture, names: layout.Names }; +const archs = [_]Arch{ + .{ .name = "kolibri1-eagle3-drafter", .as = .eagle3, .names = .{ .layers = "blocks", .own_target = true } }, + .{ .name = "kolibri1-block-drafter", .as = .@"block-drafter", .names = .{ .own_target = true, .unused = &.{"inp.weight"} } }, +}; + +/// The published config.json, field for field (unknown fields refused). +const Published = struct { + architecture: []const u8, + target: []const u8, + drafter: struct { + hidden: u32, + heads: u32, + head_dim: u32, + ffn: u32, + layers: u32, + taps: u32, + eps: f64, + theta: f64, + block: u32 = 1, + chain_ctx: bool = false, + row0_chain: bool = false, + pred_rank: u32 = 0, + spine_rank: u32 = 0, + }, + taps: []const u32, // 0-based layers whose normed outputs the drafter reads + draft_vocab: []const u8, + draft_vocab_size: u32, + serving: ?struct { depth: u32, quant: release.Weight, head: release.Weight } = null, + training_tokens: ?u64 = null, + training_steps: ?u64 = null, +}; + +/// The target a published release names by repo, with the adapter of the target the server loaded. +pub const Target = struct { repo: []const u8, adapter: release.Adapter }; + +/// A published release read whole: its Config in the format's terms, its draft vocabulary, how the file names tensors. +pub const Release = struct { + manifest: release.Manifest, + vocab: []u32, + names: layout.Names, + + pub fn open(gpa: std.mem.Allocator, io: Io, dir: Io.Dir, target: Target, why: *Why) !Release { + const text = try dir.readFileAlloc(io, "config.json", gpa, .limited(1 << 20)); + defer gpa.free(text); + var arena: std.heap.ArenaAllocator = .init(gpa); + errdefer arena.deinit(); + const got = try parse(arena.allocator(), text, target, why); + var m: release.Manifest = .{ .arena = arena, .config = got.config }; + try release.validate(&m.config, why); + try release.check(&m.config, target.adapter, why); + const vt = try dir.readFileAlloc(io, m.config.draft_vocab.file, gpa, .limited(64 << 20)); + defer gpa.free(vt); + const vocab = try release.parseVocab(&m.config, gpa, vt, why); + errdefer gpa.free(vocab); + var scratch: std.heap.ArenaAllocator = .init(gpa); + defer scratch.deinit(); + const header = try layout.readHeader(scratch.allocator(), io, dir, weights, why); + try layout.checkWeightsNamed(scratch.allocator(), &m.config, header, got.names, why); + return .{ .manifest = m, .vocab = vocab, .names = got.names }; + } + + pub fn deinit(r: *Release, gpa: std.mem.Allocator) void { + gpa.free(r.vocab); + r.manifest.deinit(); + r.* = undefined; + } +}; + +/// Whether `text` is a published config.json (its architecture one of `archs`); a v1 release says "format". +pub fn declared(text: []const u8) bool { + const Probe = struct { architecture: []const u8 = "" }; + var buf: [4096]u8 = undefined; + var fba: std.heap.FixedBufferAllocator = .init(&buf); + const p = std.json.parseFromSliceLeaky(Probe, fba.allocator(), text, .{ .ignore_unknown_fields = true }) catch return false; + for (archs) |a| if (std.mem.eql(u8, a.name, p.architecture)) return true; + return false; +} + +/// The published `text` as the format's Config over `target` (names in `a`); validate and check still run after. +pub fn parse(a: std.mem.Allocator, text: []const u8, target: Target, why: *Why) !struct { config: release.Config, names: layout.Names } { + const p = std.json.parseFromSliceLeaky(Published, a, text, .{ .allocate = .alloc_always }) catch |e| { + why.set("config.json does not parse as a published drafter release ({s})", .{@errorName(e)}); + return error.BadDrafterRelease; + }; + const arch = for (archs) |x| { + if (std.mem.eql(u8, x.name, p.architecture)) break x; + } else return refuse(why, "architecture \"{s}\" is not a published drafter release ({s} or {s})", .{ p.architecture, archs[0].name, archs[1].name }); + if (!std.mem.eql(u8, p.target, target.repo)) return refuse(why, "the release drafts for {s}; the loaded target is {s}", .{ p.target, target.repo }); + const s = p.drafter; + if (s.taps != p.taps.len) return refuse(why, "drafter taps {d}, but {d} layers listed", .{ s.taps, p.taps.len }); + if (arch.as == .@"block-drafter" and !(s.chain_ctx and s.row0_chain)) return refuse(why, "a block drafter serves with chain_ctx and row0_chain only", .{}); + const ids = try a.alloc(u32, p.taps.len); + for (ids, p.taps) |*id, layer| id.* = layer + 1; // a layer's output is the stream after layer + 1 layers + const t = target.adapter; + const serving: release.Serving = if (p.serving) |v| .{ .depth = v.depth, .body = v.quant, .head = v.head } else .{ .depth = 2, .body = .bf16, .head = .bf16 }; + return .{ .config = .{ + .format = release.format, + .version = release.version, + .architecture = arch.as, + .target = .{ .repo = p.target, .revision = "", .layers = t.layers, .hidden = t.hidden, .vocab = t.vocab, .embed_scale = t.embed_scale, .tied = t.tied, .softcap = t.softcap, .head_bias = t.head_bias }, + .taps = .{ .ids = ids, .stream = .residual, .normed = true, .dtype = .bf16, .row_bytes = @intCast(ids.len * @as(usize, t.hidden) * 2) }, + .drafter = .{ .hidden = s.hidden, .heads = s.heads, .head_dim = s.head_dim, .ffn = s.ffn, .layers = s.layers, .block = s.block, .window = window, .eps = s.eps, .theta = s.theta, .pred_rank = s.pred_rank, .spine_rank = s.spine_rank }, + .draft_vocab = .{ .file = p.draft_vocab, .size = p.draft_vocab_size }, + .weights = weights, + .serving = serving, + }, .names = arch.names }; +} + +fn refuse(why: *Why, comptime fmt: []const u8, args: anytype) error{BadDrafterRelease} { + why.set(fmt, args); + return error.BadDrafterRelease; +} + +test { + _ = @import("drafter_published_test.zig"); +} diff --git a/zig/src/core/drafter_published_test.zig b/zig/src/core/drafter_published_test.zig new file mode 100644 index 00000000000..307bee8a20d --- /dev/null +++ b/zig/src/core/drafter_published_test.zig @@ -0,0 +1,160 @@ +//! Small published release folders (EAGLE-3 and block shapes) open, or are refused naming what is wrong. + +const std = @import("std"); +const release = @import("drafter_release.zig"); +const layout = @import("drafter_layout.zig"); +const published = @import("drafter_published.zig"); +const Why = release.Why; +const gpa = std.testing.allocator; +const io = std.testing.io; + +const adapter: release.Adapter = .{ .layers = 6, .hidden = 8, .vocab = 16, .embed_scale = 1.0, .tied = false, .softcap = null, .head_bias = false }; +const target: published.Target = .{ .repo = "test/small", .adapter = adapter }; + +const eagle = + \\{"architecture": "kolibri1-eagle3-drafter", "target": "test/small", + \\ "drafter": {"hidden": 8, "heads": 2, "head_dim": 4, "ffn": 16, "eps": 1e-06, "theta": 10000.0, "layers": 1, "taps": 3}, + \\ "taps": [2, 4, 5], "draft_vocab": "draft_vocab.json", "draft_vocab_size": 5, + \\ "training_tokens": 10, "training_steps": 2} +; + +const block = + \\{"architecture": "kolibri1-block-drafter", "target": "test/small", + \\ "drafter": {"hidden": 8, "heads": 2, "head_dim": 4, "ffn": 16, "layers": 2, "taps": 3, "block": 4, + \\ "eps": 1e-06, "theta": 10000.0, "chain_ctx": true, "row0_chain": true, "pred_rank": 2, "spine_rank": 2}, + \\ "taps": [2, 4, 5], "draft_vocab": "draft_vocab.json", "draft_vocab_size": 5, + \\ "serving": {"depth": 2, "quant": "fp8", "head": "nvfp4"}, "training_tokens": 10, "training_steps": 2} +; + +const Case = struct { config: []const u8 = eagle, vocab: []const u8 = "[3, 1, 4, 15, 9]", skip: ?[]const u8 = null, extra: ?[]const u8 = null, f32_norms: bool = false }; + +/// A safetensors image of every tensor `config` implies under its published names (bf16 zeros; norms f32 if asked). +fn image(a: std.mem.Allocator, case: Case) ![]u8 { + var why: Why = .{}; + const got = try published.parse(a, case.config, target, &why); + var h: std.Io.Writer.Allocating = .init(a); + try h.writer.writeByte('{'); + var at: usize = 0; + var first = true; + var names: std.ArrayList([]const u8) = .empty; + var shapes: std.ArrayList([2]usize) = .empty; + var ranks: std.ArrayList(u8) = .empty; + for (try layout.expected(a, &got.config)) |w| { + if (std.mem.startsWith(u8, w.name, "target.")) continue; + const name = try got.names.of(a, w.name); + if (case.skip != null and std.mem.eql(u8, name, case.skip.?)) continue; + try names.append(a, name); + try shapes.append(a, w.shape); + try ranks.append(a, w.rank); + } + if (case.extra) |e| { + try names.append(a, e); + try shapes.append(a, .{ 8, 8 }); + try ranks.append(a, 2); + } + for (names.items, shapes.items, ranks.items) |name, sh, rank| { + const wide = case.f32_norms and rank == 1; + const n = (if (wide) @as(usize, 4) else 2) * sh[0] * (if (rank == 2) sh[1] else 1); + if (!first) try h.writer.writeByte(','); + first = false; + const dt = if (wide) "F32" else "BF16"; + if (rank == 2) { + try h.writer.print("\"{s}\":{{\"dtype\":\"{s}\",\"shape\":[{d},{d}],\"data_offsets\":[{d},{d}]}}", .{ name, dt, sh[0], sh[1], at, at + n }); + } else try h.writer.print("\"{s}\":{{\"dtype\":\"{s}\",\"shape\":[{d}],\"data_offsets\":[{d},{d}]}}", .{ name, dt, sh[0], at, at + n }); + at += n; + } + try h.writer.writeAll(",\"__metadata__\":{\"format\":\"pt\"}}"); + const out = try a.alloc(u8, 8 + h.written().len + at); + @memset(out, 0); + std.mem.writeInt(u64, out[0..8], h.written().len, .little); + @memcpy(out[8..][0..h.written().len], h.written()); + return out; +} + +fn openCase(case: Case, why: *Why) !published.Release { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const bytes = image(arena.allocator(), case) catch try image(arena.allocator(), .{}); // a refused config: any image + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = case.config }); + try tmp.dir.writeFile(io, .{ .sub_path = "draft_vocab.json", .data = case.vocab }); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = bytes }); + return published.Release.open(gpa, io, tmp.dir, target, why); +} + +fn expectRefused(case: Case, words: []const []const u8) !void { + var why: Why = .{}; + if (openCase(case, &why)) |r| { + var rr = r; + rr.deinit(gpa); + return error.TestUnexpectedResult; + } else |e| try std.testing.expect(e == error.BadDrafterRelease or e == error.AdapterMismatch); + for (words) |word| if (std.mem.indexOf(u8, why.text(), word) == null) { + std.debug.print("refusal \"{s}\" does not name \"{s}\"\n", .{ why.text(), word }); + return error.TestUnexpectedResult; + }; +} + +/// `base` with `from` replaced by `to` refused, naming each of `words`. +fn expectEdited(base: []const u8, from: []const u8, to: []const u8, words: []const []const u8) !void { + const text = try std.mem.replaceOwned(u8, gpa, base, from, to); + defer gpa.free(text); + try std.testing.expect(!std.mem.eql(u8, text, base)); + try expectRefused(.{ .config = text }, words); +} + +test "an EAGLE-3 release opens: taps after layers 3, 5, 6; one row a pass; layer names under blocks; f32 norms" { + var why: Why = .{}; + var r = try openCase(.{ .f32_norms = true }, &why); + defer r.deinit(gpa); + const c = r.manifest.config; + try std.testing.expectEqual(release.Architecture.eagle3, c.architecture); + try std.testing.expectEqualSlices(u32, &.{ 3, 5, 6 }, c.taps.ids); + try std.testing.expectEqual(@as(u32, 3 * 8 * 2), c.taps.row_bytes); + try std.testing.expectEqual(@as(u32, 1), c.drafter.block); + try std.testing.expectEqual(published.window, c.drafter.window); + try std.testing.expectEqual(release.Serving{ .depth = 2, .body = .bf16, .head = .bf16 }, c.serving); + try std.testing.expectEqualSlices(u32, &.{ 3, 1, 4, 15, 9 }, r.vocab); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + try std.testing.expectEqualStrings("blocks.0.q.weight", try r.names.of(arena.allocator(), "layers.0.q.weight")); + try std.testing.expect(published.declared(eagle) and published.declared(block)); +} + +test "a block release opens with its serving defaults, and its unused inp.weight is admitted by name" { + var why: Why = .{}; + var r = try openCase(.{ .config = block, .extra = "inp.weight" }, &why); + defer r.deinit(gpa); + const c = r.manifest.config; + try std.testing.expectEqual(release.Architecture.@"block-drafter", c.architecture); + try std.testing.expectEqual(release.Serving{ .depth = 2, .body = .fp8, .head = .nvfp4 }, c.serving); + try std.testing.expectEqual(@as(u32, 4), c.drafter.block); + try expectRefused(.{ .extra = "inp.weight" }, &.{ "inp.weight", "does not name" }); // EAGLE-3 ships none +} + +test "a published release with the wrong layout is refused, naming what is wrong" { + try expectEdited(eagle, "kolibri1-eagle3-drafter", "kolibri1-mtp", &.{ "kolibri1-mtp", "not a published drafter release" }); + try expectEdited(eagle, "\"layers\": 1,", "\"layers\": 1, \"rope\": 1,", &.{"does not parse"}); + try expectEdited(eagle, "\"taps\": 3}", "\"taps\": 2}", &.{ "taps 2", "3 layers" }); + try expectEdited(eagle, "\"layers\": 1,", "\"layers\": 1, \"block\": 4,", &.{ "eagle3", "block 1" }); + try expectEdited(block, "\"chain_ctx\": true", "\"chain_ctx\": false", &.{"chain_ctx"}); + try expectEdited(eagle, "[2, 4, 5]", "[2, 4, 6]", &.{ "tap 7", "6 layers" }); + try expectRefused(.{ .skip = "blocks.0.q.weight" }, &.{"has no blocks.0.q.weight"}); + try expectRefused(.{ .config = block, .skip = "layers.1.ck.weight" }, &.{"has no layers.1.ck.weight"}); + try expectRefused(.{ .extra = "target.head" }, &.{ "target.head", "does not name" }); // the head is the target's +} + +test "a release for another target, or with a vocabulary that does not fit it, is refused by name" { + try expectEdited(eagle, "\"target\": \"test/small\"", "\"target\": \"test/other\"", &.{ "test/other", "test/small" }); + try expectEdited(eagle, "\"hidden\": 8", "\"hidden\": 16", &.{ "hidden 16", "target's 8" }); + try expectRefused(.{ .vocab = "[3, 1, 4, 15]" }, &.{ "4 ids", "says 5" }); + try expectRefused(.{ .vocab = "[3, 1, 4, 15, 16]" }, &.{ "16", "vocab of 16" }); + try expectRefused(.{ .vocab = "[3, 1, 4, 3, 9]" }, &.{"3 appears twice"}); + try expectEdited(eagle, "\"draft_vocab_size\": 5", "\"draft_vocab_size\": 17", &.{"17 outside 1..16"}); +} + +test "a v1 release is not a published one" { + try std.testing.expect(!published.declared("{\"format\": \"tensorfold-drafter\", \"version\": 1}")); + try std.testing.expect(!published.declared("not json")); +} diff --git a/zig/src/core/drafter_release.zig b/zig/src/core/drafter_release.zig index 45b2638fa5e..9a60db655b3 100644 --- a/zig/src/core/drafter_release.zig +++ b/zig/src/core/drafter_release.zig @@ -73,7 +73,7 @@ pub const Target = struct { } }; -/// The block drafter's shape: row 0 a chain head on the anchor's own row, rows 1.. drafted in the same pass. +/// block-drafter: row 0 a chain head on the anchor's row, rows 1.. in the same pass; eagle3: one row a pass (block 1). pub const Shape = struct { hidden: u32, // equals target.hidden: the target's head reads the drafter's rows heads: u32, @@ -92,7 +92,10 @@ pub const Vocab = struct { file: []const u8, size: u32 }; // the target's ids th pub const Weight = enum { bf16, fp8, nvfp4 }; pub const Serving = struct { depth: u32, body: Weight, head: Weight }; // defaults a server may override -pub const Architecture = enum { @"block-drafter" }; +pub const Architecture = enum { @"block-drafter", eagle3 }; + +/// Chain steps an eagle3 release may serve a round (its cache keeps this many rows past the context). +pub const most_chain: u32 = 8; /// config.json, field for field. pub const Config = struct { @@ -154,10 +157,16 @@ pub fn validate(c: *const Config, why: *Why) !void { if (s.hidden != t.hidden) return refuse(why, "drafter hidden {d} differs from the target's {d}, whose head reads it", .{ s.hidden, t.hidden }); if (s.heads == 0 or s.head_dim == 0 or s.head_dim % 2 != 0) return refuse(why, "drafter heads {d} x head_dim {d}: both positive, head_dim even", .{ s.heads, s.head_dim }); if (s.ffn == 0 or s.layers == 0 or s.window == 0) return refuse(why, "drafter ffn, layers and window must be positive", .{}); - if (s.block < 2) return refuse(why, "drafter block {d}: a block drafts at least 2 positions", .{s.block}); + const most = switch (c.architecture) { + .@"block-drafter" => if (s.block < 2) return refuse(why, "drafter block {d}: a block drafts at least 2 positions", .{s.block}) else s.block, + .eagle3 => if (s.block != 1 or s.pred_rank != 0 or s.spine_rank != 0) + return refuse(why, "an eagle3 drafter drafts one row a pass: block 1, no pred_rank or spine_rank", .{}) + else + most_chain, + }; if (!(s.eps > 0) or !std.math.isFinite(s.eps)) return refuse(why, "drafter eps {d} is not a positive number", .{s.eps}); if (!(s.theta > 0) or !std.math.isFinite(s.theta)) return refuse(why, "drafter theta {d} is not a positive number", .{s.theta}); - if (c.serving.depth == 0 or c.serving.depth > s.block) return refuse(why, "serving depth {d} outside 1..{d}", .{ c.serving.depth, s.block }); + if (c.serving.depth == 0 or c.serving.depth > most) return refuse(why, "serving depth {d} outside 1..{d}", .{ c.serving.depth, most }); if (c.draft_vocab.size == 0 or c.draft_vocab.size > t.vocab) return refuse(why, "draft vocab of {d} outside 1..{d}", .{ c.draft_vocab.size, t.vocab }); for ([_][]const u8{ c.draft_vocab.file, c.weights }) |name| if (!plainName(name)) return refuse(why, "\"{s}\" is not a file name in the release folder", .{name}); } diff --git a/zig/src/core/lanes/backend.zig b/zig/src/core/lanes/backend.zig index 38b57f855cc..72f099558d7 100644 --- a/zig/src/core/lanes/backend.zig +++ b/zig/src/core/lanes/backend.zig @@ -140,6 +140,8 @@ pub const Backend = struct { prepare_features: ?*const fn (ptr: *anyopaque, taps: []const u32) anyerror!void = null, /// Cache rows [start, start + count) of the prepared taps, within what `Features` says is held (null: none). features: ?*const fn (ptr: *anyopaque, s: *Stream, taps: []const u32, start: u64, count: u32) anyerror!Features = null, + /// The first prompt position whose taps the target keeps for the stream's first draft, past its last chunk's. + prompt_held: ?*const fn (ptr: *anyopaque, s: *Stream) ?u64 = null, /// The prompt pass handing `sink` each chunk's tapped rows as it makes them (null: features() after the pass). prefill_features: ?*const fn (ptr: *anyopaque, s: *Stream, taps: []const u32, sink: FeatureSink) anyerror!void = null, /// The first token's logprob row (the prompt's last row) for a stream with `logprobs`; null: not given. diff --git a/zig/src/core/lanes/config.zig b/zig/src/core/lanes/config.zig index bd5f34207b4..cbdf0c2b533 100644 --- a/zig/src/core/lanes/config.zig +++ b/zig/src/core/lanes/config.zig @@ -60,6 +60,7 @@ pub const Model = struct { plain_streams: u32 = 0, // a shared round with this many streams or more drafts none (0: off) copy_first: bool = false, // a copy ahead takes the round: the head holds no drafts for it (a drafter's own pass) hold_costs: []const @import("hold_price.zig").HoldCost = &.{}, // a drafter's own hold pass, timed at load + absorb_ms: f64 = 0, // a lazy drafter's absorb pass (Facts.absorb_ms): paid by rounds that hold drafts head_trees: bool = false, // the head drafts trees of lanes (DraftRequest.lanes) and holds them join_tail: bool = false, // a prompt in pieces leaves its last token for the next shared round's window (Backend.join) piece_runs: bool = false, // a round's pieces go to the backend in one call (Backend.pieces: one forward over them) @@ -208,6 +209,7 @@ pub const Config = struct { .copy_first = m.copy_first and !m.context_copies, .floor_rates = m.floor_rates, .hold_costs = m.hold_costs, + .absorb_ms = m.absorb_ms, }, .draft_step_ms = m.draft_step_ms, .shared_drafts = m.shared_drafts, diff --git a/zig/src/core/lanes/deep_chain_test.zig b/zig/src/core/lanes/deep_chain_test.zig index fc04e852164..588e35f0ef4 100644 --- a/zig/src/core/lanes/deep_chain_test.zig +++ b/zig/src/core/lanes/deep_chain_test.zig @@ -45,6 +45,22 @@ test "a lone stream asks for most_drafts on a high first-draft acceptance and st try std.testing.expectEqual(@as(i64, 1), try r.headDepth(&who(&t), null, probe)); } +test "a stream with one token left drafts none, through the head rule and the depth rule alike" { + var unused: u8 = 0; + const probe: depth.Probe = .{ .ptr = &unused, .copy = NoCopy.copy }; + var r = rule(&high, 3); + defer r.deinit(); + var s: ?depth.State = null; + defer if (s) |*x| x.deinit(std.testing.allocator); + var w = who(&s); + w.draft_room = 1; + try std.testing.expectEqual(@as(i64, 0), try r.headDepth(&w, null, probe)); + try std.testing.expectEqual(@as(i64, 0), try r.headDepth(&w, 3, probe)); + try std.testing.expectEqual(@as(i64, 0), try r.depth(w)); + w.draft_room = 2; + try std.testing.expectEqual(@as(i64, 1), try r.headDepth(&w, null, probe)); +} + test "streams that share a round chain at most the shared cap each" { var unused: u8 = 0; const probe: depth.Probe = .{ .ptr = &unused, .copy = NoCopy.copy }; diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index 9048dc58e5d..abc1b0e7616 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -164,7 +164,7 @@ pub const Rule = struct { /// The most expected tokens a ms, probing one depth farther every `depth_probe_every` rounds. pub fn depth(r: *Rule, who: Who) !i64 { - const most = @min(@as(i64, r.most_drafts), @max(1, who.draft_room - 1)); + const most = @min(@as(i64, r.most_drafts), who.draft_room - 1); if (most <= 0) return 0; if (r.confidence_floor != null and !who.sampled and !r.k.floor_rates) return most; const p = try r.rates(who); @@ -267,7 +267,8 @@ pub const Rule = struct { /// Python `_head_depth`: the next round's head drafts for a stream (0 when forced, 1 or none with a copy ahead). pub fn headDepth(r: *Rule, who: *const Who, budget: ?i64, probe: Probe) !i64 { - const d: i64 = if (who.finished) 0 else if (budget) |b| b else if (r.granted_depth) + // one token left: a verify of the pending row alone gives it + const d: i64 = if (who.finished or who.draft_room <= 1) 0 else if (budget) |b| b else if (r.granted_depth) try r.grantDepth(who.*) else if (r.node_probabilities and !((who.sampled or r.k.floor_rates) and r.confidence_floor != null)) @min(@as(i64, r.most_drafts), @max(1, who.draft_room - 1)) @@ -326,7 +327,7 @@ pub const Rule = struct { var rows: f64 = @floatFromInt(streams); var tokens = rows; const plain = r.shared_costs.get(@intCast(streams)) orelse return; - const probe_ms = if (probes > 0) holdMs(r.k.hold_costs, probes, deepest) else 0; + const probe_ms = if (probes > 0) holdMs(r.k.hold_costs, probes, deepest) + r.k.absorb_ms else 0; var best = tokens / (plain + (if (paired) |p| p.plain else fixed) + probe_ms); var keep: usize = 0; for (order[0..m], 1..) |i, k| { @@ -335,7 +336,7 @@ pub const Rule = struct { deepest = @max(deepest, out[i]); const verify = r.shared_costs.get(@intFromFloat(@ceil(rows))) orelse break; const extra = (if (paired) |p| p.row else r.row_cost.extraMs(streams, sampled)) * (rows - @as(f64, @floatFromInt(streams))); - const now = tokens / (verify + (if (extra < 0) @max(extra, plain - verify) else extra) + fixed + holdMs(r.k.hold_costs, k + probes, deepest)); + const now = tokens / (verify + (if (extra < 0) @max(extra, plain - verify) else extra) + fixed + holdMs(r.k.hold_costs, k + probes, deepest) + r.k.absorb_ms); if (now > best) { best = now; keep = k; @@ -562,6 +563,7 @@ test { _ = @import("shared_price_learning_test.zig"); _ = @import("shared_price_8_test.zig"); _ = @import("shared_price_modes_test.zig"); + _ = @import("shared_hold_pass_test.zig"); } test { diff --git a/zig/src/core/lanes/depth_constants.zig b/zig/src/core/lanes/depth_constants.zig index 45cd577b14b..898452e3fb6 100644 --- a/zig/src/core/lanes/depth_constants.zig +++ b/zig/src/core/lanes/depth_constants.zig @@ -16,4 +16,5 @@ pub const Constants = struct { copy_first: bool = false, // a copy ahead takes the next round whole: the head drafts none for it (else one) floor_rates: bool = false, // under a confidence floor a greedy stream keeps its rates' depth too (else it drafts the most) hold_costs: []const @import("hold_price.zig").HoldCost = &.{}, // a drafter's own hold pass by blocks and depth: granted holds must pay for it + absorb_ms: f64 = 0, // a lazy drafter's absorb pass: a round holding drafts pays it, a round of copies not }; diff --git a/zig/src/core/lanes/drafted.zig b/zig/src/core/lanes/drafted.zig index 1581b79bef3..1f1ba1af444 100644 --- a/zig/src/core/lanes/drafted.zig +++ b/zig/src/core/lanes/drafted.zig @@ -14,6 +14,10 @@ const Lane = struct { tree_first: ?u32 = null, // the first token of the grown tree read back this round, until a verify carries it offered: u32 = 0, // the grown tree's nodes the last verify carried, told to the drafter with its kept rows stepped: ?u64 = null, // a prompt pass going a step at a time: the prompt rows the drafter has been given + owed_from: u64 = 0, // the first kept row the drafter has not absorbed (owed_n of them, depth-0 rounds') + owed_n: u32 = 0, + owed_follow: [dr.owed_max]u32 = undefined, // the token after each owed row, as its round gave it + prompt_from: ?u64 = null, // a lazy drafter's prompt chunks from here wait in the target, absorbed at the last }; pub const Drafted = struct { @@ -72,7 +76,7 @@ pub const Drafted = struct { }; pub fn backend(x: *Drafted) be.Backend { const planned = if (x.drafter.proposal_head) |service| service.mode != .legacy and x.drafter.vtable.hold_planned != null and x.drafter.vtable.clear_proposals != null else false; - return .{ .proposal_head = x.drafter.proposal_head, .ptr = x, .round_observer = x.target.round_observer, .first_before_draft = x.target.first_before_draft, .keep_full_lone = x.target.keep_full_lone, .penalties = x.target.penalties, .chunk_invariant = x.target.chunk_invariant, .warm_images = x.target.warm_images, .vtable = vtableFor(planned, x.target.vtable.prefill_step != null and x.target.vtable.reports_fill and x.target.vtable.features != null, x.target.vtable.cancel_prefill != null, x.first_rows) }; + return .{ .proposal_head = x.drafter.proposal_head, .ptr = x, .round_observer = x.target.round_observer, .first_before_draft = x.target.first_before_draft or x.drafter.lazy, .keep_full_lone = x.target.keep_full_lone, .penalties = x.target.penalties, .chunk_invariant = x.target.chunk_invariant, .warm_images = x.target.warm_images, .vtable = vtableFor(planned, x.target.vtable.prefill_step != null and x.target.vtable.reports_fill and x.target.vtable.features != null, x.target.vtable.cancel_prefill != null, x.first_rows) }; } const cancellable: [4]be.Backend.VTable = blk: { @@ -118,6 +122,7 @@ pub const Drafted = struct { m.head_trees = d.trees; m.copy_first = d.copy_first; m.hold_costs = d.hold_costs; + m.absorb_ms = if (d.lazy_rows > 0) d.absorb_ms else 0; if (d.chances and x.drafter.vtable.chances != null) { // a chain's drafts priced by the drafter's own chances; the next hold as deep as the grant and its slack m.draft_probabilities = d.confidence_floor == null; @@ -157,6 +162,24 @@ pub const Drafted = struct { return @ptrCast(@alignCast(ptr)); } + /// A reply of one token is the first token alone: no draft reads its prompt, so nothing is absorbed. + fn drafting(s: *const Stream) bool { + return s.max_new > 1; + } + + /// Where the target's prompt pass started: the restore, or below it where the pass re-ran the kept rows. + fn passFrom(s: *const Stream) u32 { + return s.rebuilt orelse s.cached; + } + + /// A fresh_only drafter's slot holds no restored row: unless the pass re-ran its reach, holds are fillers. + fn restored(x: *const Drafted, s: *const Stream) bool { + const from = passFrom(s); + if (!x.drafter.fresh_only or from == 0) return false; + const reach = x.drafter.facts().prompt_reach; // 0: unbounded + return reach == 0 or from > (s.prompt().len -| 1) -| reach; + } + /// The target's prompt pass, then the drafter absorbs its rows but the last; a later failure releases both. fn prefill(ptr: *anyopaque, s: *Stream) anyerror!void { const x = self(ptr); @@ -174,11 +197,16 @@ pub const Drafted = struct { try x.drafter.open(s); x.lanes.putAssumeCapacity(s, .{}); const ids = s.prompt(); - const from: usize = s.cached; - if (ids.len < from + 2) return; - const n: u32 = @intCast(ids.len - 1 - from); - const f = try x.target.features(s, x.drafter.taps(), from, n); - try x.drafter.absorb(&.{.{ .stream = s, .features = f, .start = from, .follow = ids[from + 1 ..] }}); + const from: usize = passFrom(s); + if (ids.len < from + 2 or !drafting(s) or x.restored(s)) return; + try x.absorbPrompt(s, from, ids.len - 1); + } + + /// Prompt rows [from, to) but the last, cut to those the drafter's reach reads: before the first token is out. + fn absorbPrompt(x: *Drafted, s: *Stream, kept: u64, to: u64) !void { + const reach = x.drafter.facts().prompt_reach; + const from = if (reach > 0) @max(kept, (s.prompt().len - 1) -| reach) else kept; + if (to > from) try take(x, s, try x.target.features(s, x.drafter.taps(), from, @intCast(to - from)), from); } /// A step of the target's prompt pass, then the drafter absorbs its rows (as `take`); it opens at the first step. @@ -194,19 +222,35 @@ pub const Drafted = struct { x.lanes.putAssumeCapacity(s, .{}); } const lane = x.lanes.getPtr(s).?; - const from = lane.stepped orelse s.cached; // a resumed pass starts at its kept state - const to: u64 = if (done) s.prompt().len else s.fill_at.load(.monotonic); + const from = lane.stepped orelse passFrom(s); // a resumed pass starts at its kept state, or re-runs it + const to: u64 = if (done) s.prompt().len else if (s.fed > 0) s.fed else s.fill_at.load(.monotonic); lane.stepped = if (done) null else to; - if (to > from) try take(x, s, try x.target.features(s, x.drafter.taps(), from, @intCast(to - from)), from); + if (!drafting(s) or x.restored(s)) return done; + if (to > from and !done and x.waits(s, from)) { + if (lane.prompt_from == null) lane.prompt_from = from; // absorbed with the last chunk's rows + } else if (to > from) { + const kept = lane.prompt_from orelse from; + lane.prompt_from = null; + try x.absorbPrompt(s, kept, to); + } return done; } + /// A lazy drafter's earlier chunk rows wait for the last chunk's where the target holds them (prompt_held). + fn waits(x: *Drafted, s: *Stream, from: u64) bool { + const d = x.drafter.facts(); + if (d.lazy_rows == 0) return false; + const query = x.target.vtable.prompt_held orelse return false; + const kept = query(x.target.ptr, s) orelse return false; + return d.prompt_reach > 0 and kept <= @max(from, (s.prompt().len - 1) -| d.prompt_reach); + } + /// A prompt chunk's rows but the prompt's last (absorbed with the first token, as `prefill` leaves it). fn take(ptr: *anyopaque, s: *Stream, f: be.Features, start: u64) anyerror!void { const x = self(ptr); const ids = s.prompt(); const last = ids.len - 1; - if (start >= last) return; + if (start >= last or !drafting(s)) return; var rows = f; rows.rows = @intCast(@min(f.rows, last - start)); try x.drafter.absorb(&.{.{ .stream = s, .features = rows, .start = start, .follow = ids[@intCast(start + 1)..][0..rows.rows] }}); @@ -301,15 +345,32 @@ pub const Drafted = struct { x.absorbs.clearRetainingCapacity(); x.holds.clearRetainingCapacity(); try x.firsts.resize(x.gpa, requests.len); + const d = x.drafter.facts(); + const lazy = @min(d.lazy_rows, dr.owed_max); for (requests, x.firsts.items) |r, *tok| { - if (r.lanes != null and !x.drafter.facts().trees) return error.TreesNotBuilt; + if (r.lanes != null and !d.trees) return error.TreesNotBuilt; const lane = x.lanes.getPtr(r.stream) orelse return error.NotDrafting; lane.filler = 0; // a new request supersedes fillers a copy round left unused + if (x.restored(r.stream)) { // no absorb or hold: fillers until a rebuilt state; the first token still read + if (r.rows == null) tok.* = try x.firstToken(r); + lane.filler = r.depth; + continue; + } var pending: u32 = undefined; if (r.rows) |rows| { // a tree's kept path names the window's rows out of order: the features of all up to its last var prefix = true; for (rows, 0..) |row, i| prefix = prefix and row == i; + const next = lane.owed_from + lane.owed_n == r.start; // owed rows end where this verify began + const defer_ = prefix and r.depth == 0 and lane.offered == 0 and lane.owed_n + rows.len <= lazy and (lane.owed_n == 0 or next); + if (lane.owed_n > 0 and !defer_) try x.payDebt(r.stream, lane, next); + if (defer_) { // absorbed before the stream's next hold, with the rows of that round + if (lane.owed_n == 0) lane.owed_from = r.start; + @memcpy(lane.owed_follow[lane.owed_n..][0..rows.len], r.follow[0..rows.len]); + lane.owed_n += @intCast(rows.len); + lane.rows = true; + continue; + } const n: u32 = @intCast(if (prefix) rows.len else rows[rows.len - 1] + 1); const f = try x.target.features(r.stream, x.drafter.taps(), r.start, n); try x.absorbs.append(x.gpa, .{ .stream = r.stream, .features = f, .start = r.start, .follow = r.follow[0..rows.len], .rows = if (prefix) null else rows, .prompt = false, .propose = r.depth > 0, .offered = lane.offered }); @@ -317,14 +378,16 @@ pub const Drafted = struct { pending = r.follow[rows.len - 1]; lane.rows = true; } else { - const feed = r.first orelse return error.NoFirstToken; - tok.* = switch (feed) { - .handle => |h| try x.target.read(h), - .value => |v| v, - }; + if (lane.owed_n > 0) try x.payDebt(r.stream, lane, true); + tok.* = try x.firstToken(r); pending = tok.*; const last = r.stream.prompt_len - 1; - if (r.stream.cached <= last) { // the pass computed the prompt's last row (not restored whole) + if (r.stream.cached <= last and r.depth == 0 and lazy > 0) { // owed: absorbed before the first hold + lane.owed_from = last; + lane.owed_follow[0] = tok.*; + lane.owed_n = 1; + lane.rows = true; + } else if (r.stream.cached <= last) { // the pass computed the prompt's last row (not restored whole) // right after this stream's own prompt pass: a target keeping one pass's taps refuses another's const f = try x.target.features(r.stream, x.drafter.taps(), last, 1); try x.absorbs.append(x.gpa, .{ .stream = r.stream, .features = f, .start = last, .follow = @as(*const [1]u32, tok), .propose = r.depth > 0 }); @@ -349,6 +412,23 @@ pub const Drafted = struct { if (x.holds.items.len > 0) try x.drafter.hold(x.holds.items); } + /// A request's prompt-last token: read back from the target, or the value it was given. + fn firstToken(x: *Drafted, r: be.DraftRequest) !u32 { + const feed = r.first orelse return error.NoFirstToken; + return switch (feed) { + .handle => |h| try x.target.read(h), + .value => |v| v, + }; + } + + /// The owed rows, oldest first, ahead of this round's: one view of the target's features (at most owed_max rows). + fn payDebt(x: *Drafted, s: *Stream, lane: *Lane, contiguous: bool) !void { + if (!contiguous) return error.OwedRowsNotContiguous; + const f = try x.target.features(s, x.drafter.taps(), lane.owed_from, lane.owed_n); + try x.absorbs.append(x.gpa, .{ .stream = s, .features = f, .start = lane.owed_from, .follow = lane.owed_follow[0..lane.owed_n], .prompt = false, .propose = true }); + lane.owed_n = 0; // the slice above stays valid: no other request of this round names this stream + } + /// A drafter-grown tree's node chances (false: none, so the rule's per-depth rates price it). fn probabilities(ptr: *anyopaque, s: *Stream, out: []f64) anyerror!bool { const x = self(ptr); diff --git a/zig/src/core/lanes/drafted_adopt_test.zig b/zig/src/core/lanes/drafted_adopt_test.zig index f3131cb562c..44d7f9dea65 100644 --- a/zig/src/core/lanes/drafted_adopt_test.zig +++ b/zig/src/core/lanes/drafted_adopt_test.zig @@ -13,6 +13,7 @@ const Fake = struct { absorbs: u32 = 0, offered: u32 = 0, holds: u32 = 0, + reach: u32 = 0, // Facts.prompt_reach (0: unbounded) rows: [16]u32 = @splat(1), fn cast(ptr: *anyopaque) *Fake { @@ -36,8 +37,8 @@ const Fake = struct { fn none(_: *anyopaque) []const u32 { return &.{}; } - fn facts(_: *anyopaque) dr.Facts { - return .{ .depth = 3, .step_ms = 0, .prior = &.{}, .stream_bytes = 0 }; + fn facts(ptr: *anyopaque) dr.Facts { + return .{ .depth = 3, .step_ms = 0, .prior = &.{}, .stream_bytes = 0, .prompt_reach = cast(ptr).reach }; } fn unused(_: *anyopaque, _: *Stream) anyerror!void { return error.Unused; @@ -97,3 +98,52 @@ test "Drafted.adopt opens a missing stream, resets a present one, and the next d try std.testing.expectEqual(@as(u32, 3), f.holds); try std.testing.expectEqual(@as(u32, 0), x.lanes.get(&w).?.filler); } + +test "a fresh_only drafter: a restored stream reads its first token, absorbs nothing, holds nothing; a fresh one holds" { + var f: Fake = .{}; + const target: be.Backend = .{ .ptr = &f, .vtable = &.{ .prefill = Fake.unused, .features = Fake.features, .first = Fake.first, .queue = Fake.queue, .read = Fake.read, .verify = Fake.verify, .keep = Fake.keep, .draft = Fake.draft, .release = Fake.release } }; + const drafter: dr.Drafter = .{ .fresh_only = true, .ptr = &f, .vtable = &.{ .taps = Fake.none, .facts = Fake.facts, .open = Fake.open, .absorb = Fake.absorb, .hold = Fake.hold, .held = Fake.held, .release = Fake.release } }; + var x = try Drafted.init(gpa, target, drafter); + defer x.deinit(); + const b = x.backend(); + const prompt = [_]u32{ 5, 6, 7, 8, 9, 10, 11, 12 }; + var w = try Stream.init(gpa, .{ .id = "w", .prompt = &prompt, .max_new = 8 }); + defer w.deinit(gpa); + w.cached = prompt.len; + try x.adopt(&w); + try b.vtable.draft(b.ptr, &.{.{ .stream = &w, .follow = &.{}, .first = .{ .value = 9 }, .rows = null, .start = 8, .position = 9, .depth = 3 }}); + try std.testing.expectEqual(@as(u32, 9), x.firsts.items[0]); + try b.vtable.draft(b.ptr, &.{kept(&w, 8)}); + try std.testing.expectEqual(@as(u32, 0), f.absorbs + f.holds); + try std.testing.expectEqual(@as(u32, 3), x.lanes.get(&w).?.filler); + var s = try Stream.init(gpa, .{ .id = "s", .prompt = &prompt, .max_new = 8 }); + defer s.deinit(gpa); + try x.adopt(&s); + try b.vtable.draft(b.ptr, &.{kept(&s, 8)}); + try std.testing.expectEqual(@as(u32, 1), f.absorbs); + try std.testing.expectEqual(@as(u32, 1), f.holds); +} + +test "a fresh_only drafter with a reach: a restore before it, or one inside it the pass rebuilt, drafts; else fillers" { + var f: Fake = .{ .reach = 8 }; + const target: be.Backend = .{ .ptr = &f, .vtable = &.{ .prefill = Fake.unused, .features = Fake.features, .first = Fake.first, .queue = Fake.queue, .read = Fake.read, .verify = Fake.verify, .keep = Fake.keep, .draft = Fake.draft, .release = Fake.release } }; + const drafter: dr.Drafter = .{ .fresh_only = true, .ptr = &f, .vtable = &.{ .taps = Fake.none, .facts = Fake.facts, .open = Fake.open, .absorb = Fake.absorb, .hold = Fake.hold, .held = Fake.held, .release = Fake.release } }; + var x = try Drafted.init(gpa, target, drafter); + defer x.deinit(); + const b = x.backend(); + var prompt: [16]u32 = undefined; + for (&prompt, 0..) |*t, i| t.* = @intCast(5 + i); + const rebuilt = [_]?u32{ null, null, 0, 7 }; + for ([_]u32{ 7, 8, 8, 8 }, rebuilt, [_]u32{ 1, 0, 1, 1 }) |cached, from, holds| { // row 15 reads back to row 7 + f.holds = 0; + var s = try Stream.init(gpa, .{ .id = "s", .prompt = &prompt, .max_new = 8 }); + defer s.deinit(gpa); + s.cached = cached; + s.rebuilt = from; + try x.adopt(&s); + try b.vtable.draft(b.ptr, &.{kept(&s, 16)}); + try std.testing.expectEqual(holds, f.holds); + try std.testing.expectEqual(if (holds == 0) @as(u32, 3) else 0, x.lanes.get(&s).?.filler); + b.vtable.release(b.ptr, &s); + } +} diff --git a/zig/src/core/lanes/drafted_lazy_test.zig b/zig/src/core/lanes/drafted_lazy_test.zig new file mode 100644 index 00000000000..b55457fe8c3 --- /dev/null +++ b/zig/src/core/lanes/drafted_lazy_test.zig @@ -0,0 +1,220 @@ +//! Lazy absorb: depth-0 rows owed, absorbed before the next hold, leave the eager drafter's state (ring wrap, limits). +const std = @import("std"); +const be = @import("backend.zig"); +const dr = @import("drafter.zig"); +const Stream = @import("stream.zig").Stream; +const Drafted = @import("drafted.zig").Drafted; +const FakeDrafter = @import("drafted_test.zig").FakeDrafter; + +const gpa = std.testing.allocator; + +/// A target holding each position's token as its tapped row, in a ring of `keep` positions, `view` rows a read. +const Ring = struct { + const keep = 256; + const view = 64; + tokens: [1024]u32 = undefined, + written: u64 = 0, // positions [written - keep, written) readable + refused: u32 = 0, + + fn cast(ptr: *anyopaque) *Ring { + return @ptrCast(@alignCast(ptr)); + } + fn features(ptr: *anyopaque, _: *Stream, _: []const u32, start: u64, n: u32) anyerror!be.Features { + const r = cast(ptr); + if (n > view or start + n > r.written or start < r.written -| keep) { + r.refused += 1; + return error.RowsNotHeld; + } + return .{ .buffer = @intFromPtr(&r.tokens), .offset = start * 4, .rows = n, .row_bytes = 4, .space = .host, .dtype = .u32 }; + } + fn prefill(_: *anyopaque, _: *Stream) anyerror!void {} + fn first(_: *anyopaque, _: *Stream, _: u64) anyerror!u64 { + return 0; + } + fn queue(_: *anyopaque, _: *Stream, _: be.Feed, _: u64) anyerror!u64 { + return 0; + } + fn read(_: *anyopaque, _: u64) anyerror!u32 { + return 0; + } + fn verify(_: *anyopaque, _: []const be.Window, _: []be.Verified) anyerror!void {} + fn keepRows(_: *anyopaque, _: []const be.Window, _: []const []const u32) anyerror!void {} + fn draft(_: *anyopaque, _: []const be.DraftRequest) anyerror!void {} + fn release(_: *anyopaque, _: *Stream) void {} + fn backend(r: *Ring) be.Backend { + return .{ .ptr = r, .vtable = &.{ .prefill = prefill, .features = features, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keepRows, .draft = draft, .release = release } }; + } +}; + +/// What one run leaves: the drafter's rows by position, its held drafts at every hold, its absorb calls. +const Run = struct { history: [1024]u32 = undefined, len: usize = 0, held: [128][3]u32 = undefined, holds: usize = 0, absorbs: u32 = 0, refused: u32 = 0 }; + +/// Rounds of 1-3 kept rows from position 8 to past 600: `holds_every`-th round holds 3 drafts, the rest depth 0. +fn run(lazy: u32, holds_every: usize) !Run { + var ring: Ring = .{}; + for (&ring.tokens, 0..) |*t, p| t.* = @intCast((p * 7 + 3) % 97); + var fd: FakeDrafter = .{}; + defer fd.deinit(); + fd.facts_.lazy_rows = lazy; + var x = try Drafted.init(gpa, ring.backend(), fd.drafter()); + defer x.deinit(); + var s = try Stream.init(gpa, .{ .id = "lazy", .prompt = ring.tokens[0..8], .max_new = 900 }); + defer s.deinit(gpa); + try x.adopt(&s); + defer x.backend().release(&s); + var out: Run = .{}; + var start: u64 = 8; + var round: usize = 0; + while (start < 600) : (round += 1) { + const kept: usize = 1 + (round * 5 + 1) % 3; + ring.written = start + kept; // the verify's kept rows are on the target (a keep rolled the rest back) + const depth: u32 = if (round % holds_every == holds_every - 1) 3 else 0; + const rows = [_]u32{ 0, 1, 2 }; + try x.backend().draft(&.{.{ .stream = &s, .follow = ring.tokens[start + 1 ..][0..kept], .rows = rows[0..kept], .start = start, .position = start + kept + 1, .depth = depth }}); + if (depth > 0) { + const l = fd.lanes.getPtr(&s).?; + @memcpy(&out.held[out.holds], l.held.items[0..3]); + out.holds += 1; + } + start += kept; + } + // the stream's last rows: a final hold pays what is owed, so both runs end on the same state + ring.written = start + 1; + try x.backend().draft(&.{.{ .stream = &s, .follow = ring.tokens[start + 1 ..][0..1], .rows = &.{0}, .start = start, .position = start + 2, .depth = 1 }}); + const l = fd.lanes.getPtr(&s).?; + out.len = l.history.items.len; + @memcpy(out.history[0..out.len], l.history.items); + out.absorbs = fd.absorbs; + out.refused = ring.refused; + return out; +} + +fn expectSame(eager: Run, lazy: Run) !void { + try std.testing.expectEqual(eager.len, lazy.len); + try std.testing.expectEqualSlices(u32, eager.history[0..eager.len], lazy.history[0..lazy.len]); + try std.testing.expectEqual(eager.holds, lazy.holds); + for (eager.held[0..eager.holds], lazy.held[0..lazy.holds]) |a, b| try std.testing.expectEqualSlices(u32, &a, &b); + try std.testing.expectEqual(@as(u32, 0), lazy.refused); +} + +test "lazy absorb: owed depth-0 rows absorbed before the next hold give the eager drafter's rows and drafts" { + const eager = try run(0, 4); + const lazy = try run(dr.owed_max, 4); + try expectSame(eager, lazy); + try std.testing.expect(lazy.absorbs < eager.absorbs); // depth-0 rounds made no absorb call of their own +} + +test "lazy absorb: a stream that never holds flushes at the owed limit, past the target ring's wrap" { + const eager = try run(0, 1000); + for ([_]u32{ 47, 48, 49, dr.owed_max }) |limit| { + const lazy = try run(limit, 1000); + try expectSame(eager, lazy); + // about one flush a limit's rows: 600 positions, never a view past the target's ring + try std.testing.expect(lazy.absorbs <= 600 / (limit - 2) + 2); + } +} + +test "lazy absorb: through the engine, a lazy drafter's prompt rows and owed rows give the same rounds" { + const dt = @import("drafted_test.zig"); + const cases = [_]dt.Case{ .{ .prompt = &dt.p1, .max_new = 60 }, .{ .prompt = &dt.long, .sampling = dt.sampled, .max_new = 50 } }; + const eager = try dt.run(&cases, .wrapped, true); + defer dt.freeOut(eager); + dt.lazy_rows = dr.owed_max; + defer dt.lazy_rows = 0; + const lazy = try dt.run(&cases, .wrapped, true); + defer dt.freeOut(lazy); + for (eager.tokens, lazy.tokens) |a, b| try std.testing.expectEqualSlices(u32, a, b); + try std.testing.expectEqual(eager.drafted, lazy.drafted); + try std.testing.expectEqual(eager.accepted, lazy.accepted); + try std.testing.expect(lazy.head.prompt_rows > 0); // the prompts' rows reached the drafter +} + +/// Absorb calls of a 40-token prompt pass into an eager drafter for a reply of `max_new` tokens. +fn promptAbsorbs(max_new: u32) !u32 { + var ring: Ring = .{}; + for (&ring.tokens, 0..) |*t, p| t.* = @intCast((p * 7 + 3) % 97); + ring.written = 40; + var fd: FakeDrafter = .{}; + defer fd.deinit(); + var x = try Drafted.init(gpa, ring.backend(), fd.drafter()); + defer x.deinit(); + var s = try Stream.init(gpa, .{ .id = "one", .prompt = ring.tokens[0..40], .max_new = max_new }); + defer s.deinit(gpa); + try x.backend().prefill(&s); + defer x.backend().release(&s); + return fd.absorbs; +} + +test "lazy absorb: a one-token reply's prompt pass absorbs nothing, a two-token reply's absorbs its rows" { + try std.testing.expectEqual(@as(u32, 0), try promptAbsorbs(1)); + try std.testing.expectEqual(@as(u32, 1), try promptAbsorbs(2)); +} + +/// A target filling a 600-token prompt 200 rows a step: the last step's rows whole, a slab's from `held` on. +const Steps = struct { + ring: Ring = .{}, + held: ?u64 = null, + chunk_from: u64 = 0, + + fn cast(ptr: *anyopaque) *Steps { + return @ptrCast(@alignCast(ptr)); + } + fn features(ptr: *anyopaque, s: *Stream, taps: []const u32, start: u64, n: u32) anyerror!be.Features { + const x = cast(ptr); + const whole = start >= x.chunk_from or (x.held != null and start >= x.held.?); + if (whole and start + n <= x.ring.written) return .{ .buffer = @intFromPtr(&x.ring.tokens), .offset = start * 4, .rows = n, .row_bytes = 4, .space = .host, .dtype = .u32 }; + return Ring.features(&x.ring, s, taps, start, n); + } + fn step(ptr: *anyopaque, s: *Stream, _: u32) anyerror!bool { + const x = cast(ptr); + x.chunk_from = x.ring.written; + x.ring.written = @min(x.ring.written + 200, s.prompt().len); + s.fill_at.store(@intCast(x.ring.written), .monotonic); + return x.ring.written == s.prompt().len; + } + fn promptHeld(ptr: *anyopaque, _: *Stream) ?u64 { + return cast(ptr).held; + } + fn backend(x: *Steps) be.Backend { + return .{ .ptr = x, .vtable = &.{ .prefill = Ring.prefill, .prefill_step = step, .reports_fill = true, .features = features, .prompt_held = promptHeld, .first = Ring.first, .queue = Ring.queue, .read = Ring.read, .verify = Ring.verify, .keep = Ring.keepRows, .draft = Ring.draft, .release = Ring.release } }; + } +}; + +/// Absorb calls during the stepped prompt pass, a first round of `depth`'s, and where its absorb starts (null: none). +fn steppedRun(held: ?u64, depth: u32) !struct { during: u32, after: u32, first: ?u64, refused: u32 } { + var t: Steps = .{ .held = held }; + for (&t.ring.tokens, 0..) |*v, p| v.* = @intCast((p * 7 + 3) % 97); + var fd: FakeDrafter = .{}; + defer fd.deinit(); + fd.facts_.lazy_rows = dr.owed_max; + fd.facts_.prompt_reach = 200; + var x = try Drafted.init(gpa, t.backend(), fd.drafter()); + defer x.deinit(); + var s = try Stream.init(gpa, .{ .id = "steps", .prompt = t.ring.tokens[0..600], .max_new = 8 }); + defer s.deinit(gpa); + const b = x.backend(); + while (!try b.vtable.prefill_step.?(b.ptr, &s, 0)) {} + defer b.release(&s); + const during = fd.absorbs; + fd.first_start = null; + try b.draft(&.{.{ .stream = &s, .follow = &.{}, .first = .{ .value = t.ring.tokens[600] }, .rows = null, .start = 600, .position = 601, .depth = depth }}); + return .{ .during = during, .after = fd.absorbs - during, .first = fd.first_start, .refused = t.ring.refused }; +} + +test "lazy absorb: the prompt's reach is absorbed before the first token, in one call where the target holds it" { + const slab = try steppedRun(599 - 200, 1); // a slab from the reach on: earlier chunks wait for the last chunk + try std.testing.expectEqual(@as(u32, 1), slab.during); + try std.testing.expectEqual(@as(u64, 599), slab.first.?); // the first round absorbs the prompt's last row alone + try std.testing.expectEqual(@as(u32, 0), slab.refused); + const none = try steppedRun(null, 1); // no slab: each chunk's rows in the reach at its pass + try std.testing.expectEqual(@as(u32, 2), none.during); + try std.testing.expectEqual(@as(u64, 599), none.first.?); + try std.testing.expectEqual(@as(u32, 0), none.refused); +} + +test "lazy absorb: a first round of no drafts absorbs nothing, the prompt's last row owed to the next hold" { + const plain = try steppedRun(599 - 200, 0); + try std.testing.expectEqual(@as(u32, 1), plain.during); + try std.testing.expectEqual(@as(u32, 0), plain.after); + try std.testing.expectEqual(@as(?u64, null), plain.first); +} diff --git a/zig/src/core/lanes/drafted_test.zig b/zig/src/core/lanes/drafted_test.zig index f8ac1008761..ec0d1cec474 100644 --- a/zig/src/core/lanes/drafted_test.zig +++ b/zig/src/core/lanes/drafted_test.zig @@ -50,7 +50,7 @@ pub const FakeDrafter = struct { } pub fn drafter(x: *FakeDrafter) dr.Drafter { - return .{ .ptr = x, .vtable = &.{ .taps = taps, .facts = facts, .open = open, .absorb = absorb, .hold = hold, .held = held, .release = release } }; + return .{ .ptr = x, .lazy = x.facts_.lazy_rows > 0, .vtable = &.{ .taps = taps, .facts = facts, .open = open, .absorb = absorb, .hold = hold, .held = held, .release = release } }; } fn self(ptr: *anyopaque) *FakeDrafter { @@ -274,10 +274,11 @@ pub fn base() Model { return .{ .exact_width = 16, .gpu_tokens = true, .window_costs = &costs, .hidden_rows = true, .batch_rows = 32, .max_streams = 8 }; } +pub var lazy_rows: u32 = 0; // Facts.lazy_rows of run's drafter (drafted_lazy_test sets it) pub fn run(cases: []const Case, mode: Mode, batched: bool) !Out { var target: fake.Fake = .{ .gpa = gpa }; defer target.deinit(); - var head: FakeDrafter = .{ .facts_ = .{ .depth = 6, .step_ms = 0.5, .batched = batched } }; + var head: FakeDrafter = .{ .facts_ = .{ .depth = 6, .step_ms = 0.5, .batched = batched, .lazy_rows = lazy_rows } }; var strict: Strict = .{ .inner = target.backend() }; defer strict.deinit(); var target_backend = strict.backend(); @@ -285,7 +286,7 @@ pub fn run(cases: []const Case, mode: Mode, batched: bool) !Out { target_backend.penalties = mode == .wrapped_early; var wrapped = try Drafted.init(gpa, target_backend, head.drafter()); defer wrapped.deinit(); - try std.testing.expectEqual(mode == .wrapped_early, wrapped.backend().first_before_draft); + try std.testing.expectEqual(mode == .wrapped_early or lazy_rows > 0, wrapped.backend().first_before_draft); try std.testing.expectEqual(mode == .wrapped_early, wrapped.backend().penalties); var m = base(); m.root_copies = cases[0].root_copies; diff --git a/zig/src/core/lanes/drafter.zig b/zig/src/core/lanes/drafter.zig index 3cb2b1fd733..7f52fff62d3 100644 --- a/zig/src/core/lanes/drafter.zig +++ b/zig/src/core/lanes/drafter.zig @@ -27,8 +27,16 @@ pub const Facts = struct { slack: u32 = 0, // with chances: drafts a hold offers past the stream's last grant (0: the depth rule's own) copy_first: bool = false, // a hold costs a pass of its own: none is asked for a stream with a copy ahead hold_costs: []const @import("hold_price.zig").HoldCost = &.{}, // that pass's ms by blocks and depth (timed at load) + // kept rows a depth-0 stream may owe before the wrapper absorbs them (0: every round; at most owed_max) + lazy_rows: u32 = 0, + prompt_reach: u32 = 0, // prompt rows before its last that later reads reach: all a lazy drafter absorbs + // one absorb pass's ms (timed at load): with lazy_rows, a round pays it only when it holds drafts + absorb_ms: f64 = 0, }; +/// Kept rows a stream may owe the drafter at most: one target feature view covers them. +pub const owed_max = 64; + /// Target rows [start, start + features.rows) and the token after each; `rows`, when given, picks which to absorb. pub const Absorb = struct { stream: *Stream, @@ -47,6 +55,8 @@ pub const Hold = struct { stream: *Stream, pending: u32, position: u64, depth: u pub const Drafter = struct { kind: []const u8 = "draft model", // descriptive only; the loader identifies the implementation it attached proposal_head: ?*const @import("proposal_head.zig").Service = null, + lazy: bool = false, // it owes rows (Facts.lazy_rows): the wrapper hands out the first token before a draft + fresh_only: bool = false, // its state does not survive a prompt-cache restore: a restored stream holds nothing ptr: *anyopaque, vtable: *const VTable, diff --git a/zig/src/core/lanes/lanes.zig b/zig/src/core/lanes/lanes.zig index d026acfcaa3..54cb57c0205 100644 --- a/zig/src/core/lanes/lanes.zig +++ b/zig/src/core/lanes/lanes.zig @@ -87,6 +87,7 @@ test { _ = @import("gpu_top_test.zig"); _ = @import("gpu_draw_test.zig"); _ = @import("drafted_test.zig"); + _ = @import("drafted_lazy_test.zig"); _ = @import("drafter_depth_sweep_test.zig"); _ = @import("drafted_chances_test.zig"); _ = @import("drafted_copy_test.zig"); diff --git a/zig/src/core/lanes/open.zig b/zig/src/core/lanes/open.zig index fa389f34136..8668fbefb24 100644 --- a/zig/src/core/lanes/open.zig +++ b/zig/src/core/lanes/open.zig @@ -145,6 +145,7 @@ fn openedCommitted(e: *Engine, s: *Stream, reach: Reach, hook: ?be.Committed) !v /// The first drafts' depth for `reach`. pub fn firstDepth(e: *Engine, s: *Stream, reach: Reach) !u32 { var who = win.who(s); + who.draft_room -= 1; // the first token, committed right after this depth is read, takes one of the room const d = if (reach == .head and e.cfg.node_probabilities) try e.rule.headDepth(&who, null, win.probe(e)) else try e.rule.depth(who); return @intCast(if (e.cfg.shared_mtp_cap > 0 and e.live.items.len > 0) @min(d, e.cfg.shared_mtp_cap) else d); // joins a shared round } diff --git a/zig/src/core/lanes/shared_drafts.zig b/zig/src/core/lanes/shared_drafts.zig index 2582513acc8..502b4dd711c 100644 --- a/zig/src/core/lanes/shared_drafts.zig +++ b/zig/src/core/lanes/shared_drafts.zig @@ -66,7 +66,11 @@ pub fn budgets(e: *Engine, plans: []const win.Plan, heads: []const usize, out: [ for (heads, out) |i, *budget| { budget.* = if (neural[i]) counts[i] else 0; } - if (limits) |l| if (e.cfg.granted_depth) try payReserved(e, l.who, probs, heads, sampled, out); + if (limits) |l| { + if (e.cfg.granted_depth) { + try payReserved(e, l.who, probs, heads, sampled, out); + } else if (e.rule.k.hold_costs.len > 0) try payPass(e, l.who, probs, heads, sampled, out); + } } // Copy lookups may advance a proposer's backoff; the reservation loop, not this depth cap, asks it once. @@ -116,6 +120,22 @@ fn payReserved(e: *Engine, who: []depth.Who, probs: []const []const f64, heads: try e.rule.payHolds(who, sampled, out); } +/// A drafter's timed hold pass under a legacy cap: each head's reserved depth is the hold the rule prices. +fn payPass(e: *Engine, who: []depth.Who, probs: []const []const f64, heads: []const usize, sampled: bool, out: []i64) !void { + for (who, heads, out) |*w, i, d| { + if (d <= 0) continue; + const kept: usize = @intCast(@min(d, @as(i64, @intCast(probs[i].len)))); + w.granted = @intCast(kept); // its rows and expected tokens this round, not its last verified grant + var gain: f64 = 0; + for (probs[i][0..kept]) |chance| gain += chance; + w.gain = gain; + } + if (e.cfg.plain_guard) + try e.rule.payHoldsFor(who, sampled, out, probs.len) + else + try e.rule.payHolds(who, sampled, out); +} + test "shared draft prices: a short cached tree can grow when allocation returns more rows" { const a = std.testing.allocator; const Cfg = @import("config.zig"); diff --git a/zig/src/core/lanes/shared_hold_pass_test.zig b/zig/src/core/lanes/shared_hold_pass_test.zig new file mode 100644 index 00000000000..5a4f59b97ec --- /dev/null +++ b/zig/src/core/lanes/shared_hold_pass_test.zig @@ -0,0 +1,61 @@ +//! A drafter's timed hold pass under a legacy cap (limit_shared_drafts): the rule keeps its holds while they pay. +const std = @import("std"); +const t = std.testing; +const a = t.allocator; +const Config = @import("config.zig").Config; +const HoldCost = @import("hold_price.zig").HoldCost; +const Stream = @import("stream.zig").Stream; +const Engine = @import("engine.zig").Engine; +const fake = @import("fake.zig"); +const win = @import("windows.zig"); + +/// Four drafting streams, three drafts each at 0.8 a depth; `holds` the drafter's pass. Each stream's reserved depth. +fn round(holds: []const HoldCost) ![4]i64 { + return roundAbsorbing(holds, 0); +} + +/// `round`, a lazy drafter's absorb pass of `absorb_ms` paid by a round that holds drafts. +fn roundAbsorbing(holds: []const HoldCost, absorb_ms: f64) ![4]i64 { + // forward 12 ms a row plus about 1 ms a row more; plain 4 rows ~15 ms, 16 drafted rows ~27.5 ms, fixed 8 ms + const model: @import("config.zig").Model = .{ .exact_width = 32, .mtp = true, .drafts = 3, .draft_prior = &.{0.8}, .plain_guard = true, .hidden_rows = true, .allocate_shared_drafts = true, .limit_shared_drafts = true, .hold_costs = holds, .absorb_ms = absorb_ms, .window_costs = &.{ .{ .width = 1, .ms = 12 }, .{ .width = 32, .ms = 44 } } }; + var cfg = try Config.init(a, model, 32, 3); + defer cfg.deinit(a); + var target: fake.Fake = .{ .gpa = a }; + defer target.deinit(); + var clock: fake.FixedClock = .{}; + var e = Engine.init(a, &cfg, target.backend(), clock.clock()); + defer e.deinit(); + var streams: [4]Stream = undefined; + var made: usize = 0; + defer for (streams[0..made]) |*s| s.deinit(a); + var plans: [4]win.Plan = undefined; + for (&streams, &plans) |*s, *p| { + s.* = try Stream.init(a, .{ .id = "pass", .prompt = &.{1}, .max_new = 64 }); + made += 1; + p.* = .{ .stream = s, .position = 1, .kind = .none }; + } + var out: [4]i64 = undefined; + try @import("shared_drafts.zig").budgets(&e, &plans, &.{ 0, 1, 2, 3 }, &out); + return out; +} + +// Break-even: 4 tokens / 23.1 ms plain vs 11.8 / (35.5 ms + pass); the pass may cost up to ~32.7 ms at 4 streams. +const cheap = [_]HoldCost{ .{ .streams = 1, .depth = 1, .ms = 0.5 }, .{ .streams = 1, .depth = 3, .ms = 1 }, .{ .streams = 4, .depth = 1, .ms = 1 }, .{ .streams = 4, .depth = 3, .ms = 2 } }; +const dear = [_]HoldCost{ .{ .streams = 1, .depth = 1, .ms = 20 }, .{ .streams = 1, .depth = 3, .ms = 30 }, .{ .streams = 4, .depth = 1, .ms = 40 }, .{ .streams = 4, .depth = 3, .ms = 60 } }; + +test "hold pass: a pass cheaper than the drafts it buys keeps every stream's drafter depth" { + try t.expectEqualSlices(i64, &.{ 3, 3, 3, 3 }, &try round(&cheap)); +} + +test "hold pass: a pass dearer than the drafts it buys falls back to copies (no drafter hold)" { + try t.expectEqualSlices(i64, &.{ 0, 0, 0, 0 }, &try round(&dear)); +} + +test "hold pass: no timed pass leaves the legacy cap as it was (the dear case's control)" { + try t.expectEqualSlices(i64, &.{ 3, 3, 3, 3 }, &try round(&.{})); +} + +test "hold pass: a lazy drafter's absorb pass joins the cheap pass's price, and past break-even the round takes copies" { + try t.expectEqualSlices(i64, &.{ 3, 3, 3, 3 }, &try roundAbsorbing(&cheap, 1)); + try t.expectEqualSlices(i64, &.{ 0, 0, 0, 0 }, &try roundAbsorbing(&cheap, 35)); +} diff --git a/zig/src/core/lanes/stream.zig b/zig/src/core/lanes/stream.zig index 7e621e98d71..56fffe2f7be 100644 --- a/zig/src/core/lanes/stream.zig +++ b/zig/src/core/lanes/stream.zig @@ -203,7 +203,9 @@ pub const Stream = struct { key: []const u32 = &.{}, cache_salt: ?u64 = null, cached: u32 = 0, // prompt tokens the backend restored from `reuse` (its prompt pass started there) + rebuilt: ?u32 = null, // a restored stream's pass re-ran the kept rows from here: a fresh_only drafter's taps fill_at: std.atomic.Value(u32) = .init(0), // prompt tokens the pass has prefilled; the engine thread writes + fed: u32 = 0, // the pass's replay frontier: rows its forward has computed (0: none reported; a drafter reads fill_at) reuse_failed: bool = false, // the backend's restore of `reuse` failed: it prefilled from 0 reuse_error: ?anyerror = null, // the rejected restore's reason, logged once when its cache borrow is reported context: std.ArrayList(u32) = .empty, diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 9d9a15b0d2f..36ce0f36f59 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -71,6 +71,7 @@ pub const qwen_vl = @import("qwen_vl/qwen_vl.zig"); pub const image_rows = @import("image_rows.zig"); pub const drafter_release = @import("drafter_release.zig"); pub const drafter_layout = @import("drafter_layout.zig"); +pub const drafter_published = @import("drafter_published.zig"); pub const dspine = @import("dspine.zig"); pub const tree_round = @import("tree_round.zig"); pub const attention_ref = @import("attention_ref.zig"); @@ -159,6 +160,7 @@ test { _ = image_rows; _ = @import("nvfp4_fixture_test.zig"); _ = @import("drafter_release_test.zig"); + _ = @import("drafter_published.zig"); _ = kv_pool; _ = kv_prompts; _ = state_walk; diff --git a/zig/src/cuda/dense_rows.zig b/zig/src/cuda/dense_rows.zig index 125d932c4ab..1fd0d97e442 100644 --- a/zig/src/cuda/dense_rows.zig +++ b/zig/src/cuda/dense_rows.zig @@ -13,11 +13,14 @@ const Stream = stream_.Stream; const warps = 8; /// The launch tiles: rows a tile shares each weight row across. const tiles = [_]usize{ 1, 4, 16, 32 }; +/// Rows past which rows() launches tf_dense_rows_tiled (a prompt's, an absorb's): the same bits, weights read less. +pub const tiled_from = 64; pub const DenseRows = struct { mod: Module, fns: [tiles.len]Function, scaled_fns: [tiles.len]Function, + tiled: Function, // past `tiled_from` rows: 8 rows x 8 columns a warp, the same sums pub fn load(d: *const Driver) !DenseRows { if (!kernels.available) return error.BuiltWithoutKernels; @@ -29,7 +32,7 @@ pub const DenseRows = struct { fns[i] = try mod.function(std.fmt.comptimePrint("tf_dense_rows_{d}", .{t})); scaled[i] = try mod.function(std.fmt.comptimePrint("tf_dense_rows_scaled_{d}", .{t})); } - return .{ .mod = mod, .fns = fns, .scaled_fns = scaled }; + return .{ .mod = mod, .fns = fns, .scaled_fns = scaled, .tiled = try mod.function("tf_dense_rows_tiled") }; } pub fn unload(g: *DenseRows) void { @@ -38,17 +41,23 @@ pub const DenseRows = struct { /// out [m, n] fp32 = x [m, k] bf16 times w [n, k] bf16 transposed; strides in elements, k % 8 == 0, 16 B aligned. pub fn rows(g: *const DenseRows, s: Stream, x: u64, x_stride: usize, w: u64, out: u64, out_stride: usize, m: usize, n: usize, k: usize) !void { - return g.rowsWith(null, s, x, x_stride, w, out, out_stride, m, n, k); + return g.rowsWith(null, false, s, x, x_stride, w, out, out_stride, m, n, k); + } + + /// rows in tf_dense_rows_tiled at any row count (the same bits): a caller whose rounds pass 16 rows. + pub fn rowsTiled(g: *const DenseRows, s: Stream, x: u64, x_stride: usize, w: u64, out: u64, out_stride: usize, m: usize, n: usize, k: usize) !void { + return g.rowsWith(null, true, s, x, x_stride, w, out, out_stride, m, n, k); } /// rows with the scaled epilogue: out = fp32(bf16(x . w[n])) * scale[n], scale fp32 [n] (Dory's logits). pub fn rowsScaled(g: *const DenseRows, s: Stream, x: u64, x_stride: usize, w: u64, scale: u64, out: u64, out_stride: usize, m: usize, n: usize, k: usize) !void { - return g.rowsWith(scale, s, x, x_stride, w, out, out_stride, m, n, k); + return g.rowsWith(scale, false, s, x, x_stride, w, out, out_stride, m, n, k); } - fn rowsWith(g: *const DenseRows, scale: ?u64, s: Stream, x: u64, x_stride: usize, w: u64, out: u64, out_stride: usize, m: usize, n: usize, k: usize) !void { + fn rowsWith(g: *const DenseRows, scale: ?u64, tiled: bool, s: Stream, x: u64, x_stride: usize, w: u64, out: u64, out_stride: usize, m: usize, n: usize, k: usize) !void { if (k % 8 != 0 or x % 16 != 0 or w % 16 != 0 or x_stride % 8 != 0) return error.Misaligned; if (m == 0 or n == 0) return; + const wide = scale == null and (tiled or m > tiled_from); const i: usize = if (m == 1) 0 else if (m <= 4) 1 else if (m <= 16) 2 else 3; var a: launch_.Args = .{}; a.add(x); @@ -60,6 +69,10 @@ pub const DenseRows = struct { a.add(@as(i32, @intCast(m))); a.add(@as(i32, @intCast(n))); a.add(@as(i32, @intCast(k))); + if (wide) { + const grid: launch_.Dim3 = .{ .x = @intCast((n + 7) / 8), .y = @intCast((m + 63) / 64), .z = 1 }; + return launch_.launch(g.tiled, .{ .grid = grid, .block = .{ .x = warps * 32 } }, s, &a); + } const grid: launch_.Dim3 = .{ .x = @intCast((n + warps - 1) / warps), .y = @intCast((m + tiles[i] - 1) / tiles[i]), .z = 1 }; try launch_.launch(if (scale != null) g.scaled_fns[i] else g.fns[i], .{ .grid = grid, .block = .{ .x = warps * 32 } }, s, &a); } diff --git a/zig/src/cuda/eagle3.zig b/zig/src/cuda/eagle3.zig new file mode 100644 index 00000000000..d0cc3a9c59c --- /dev/null +++ b/zig/src/cuda/eagle3.zig @@ -0,0 +1,355 @@ +//! An EAGLE-3 drafter's passes on shared operators only (no kernel of its own): taps and a token in, draft picks out. +const std = @import("std"); +const Driver = @import("driver.zig").Driver; +const Stream = @import("stream.zig").Stream; +const DeviceBuffer = @import("memory.zig").DeviceBuffer; +const Function = @import("module.zig").Function; +const launch_ = @import("launch.zig"); +const abi = @import("abi.zig"); +const DenseRows = @import("dense_rows.zig").DenseRows; +const Norms = @import("norms.zig").Norms; +const QkRows = @import("qk_rows.zig").QkRows; +const ActRows = @import("act_rows.zig").ActRows; +const EmbedRows = @import("embed_rows.zig").EmbedRows; +const wa = @import("window_attention.zig"); + +/// Rows one pass takes: an absorb goes in parts of this many, a hold's step takes one row a stream. +pub const pass_rows = 256; +/// A pass of more rows packs its outputs' rows past the last layer's keys (a prompt's); fewer run every row. +pub const pack_rows = 64; + +pub const Dims = struct { + hidden: usize, + heads: usize, // key heads too: every query head has its own + head_dim: usize, + ffn: usize, + layers: usize, + taps: usize, // tapped rows a context row reads, each `hidden` wide + vocab: usize, // the draft vocabulary's rows of the head + window: usize, // keys back a row attends to, its own included + chain: usize, // a hold's steps at most + eps: f32, + + fn att(d: Dims) usize { + return d.heads * d.head_dim; + } + + /// Ring rows a stream keeps: a pass's rows and a chain written before the first row reads its window. + pub fn ring(d: Dims) usize { + return (d.window + pass_rows + d.chain + 63) / 64 * 64; + } + + /// Device bytes one stream's keys and values take (every layer's) and its last output. + pub fn streamBytes(d: Dims) usize { + return 2 * d.layers * d.ring() * d.att() * 2 + d.hidden * 2; + } + + /// The first position a part ending at `end` computes: the rows its last output and later rows still read. + pub fn firstNeeded(d: Dims, end: u64) u64 { + return end -| (1 + d.reach()); + } + + /// Positions before a row that its read reaches through every layer: a prompt's rows a drafter still needs. + pub fn reach(d: Dims) usize { + return d.layers * (d.window - 1); + } + + fn attention(d: Dims) wa.Window { + const dh: f32 = @floatFromInt(d.head_dim); + return .{ .h = d.heads, .hk = d.heads, .d = d.head_dim, .win = d.window, .ring = d.ring(), .scale = 1.0 / @sqrt(dh) }; + } + + /// Each scratch buffer's bytes for a pass of `pass_rows`, in `Eagle3.Scratch`'s field order (init allocates these). + fn scratch(d: Dims) [@typeInfo(Eagle3.Scratch).@"struct".field_names.len]usize { + const n = pass_rows; + const h = d.hidden; + const wide = @max(d.taps * h, @max(3 * d.att(), 2 * d.ffn)); + const rows_att = n * d.att() * 2; + return .{ n * d.taps * h * 2, n * 4, n * 4, n * 4, n * d.chain * 4, n * 2 * h * 2, n * h * 2, n * h * 2, n * wide * 4, n * h * 4, n * h * 2, 3 * rows_att, rows_att, rows_att, rows_att, rows_att, n * 2 * d.ffn * 2, n * d.ffn * 2, wa.WindowAttention.scratchBytes(d.attention(), n), n * d.vocab * 4 }; + } + + /// Device bytes the scratch takes, each buffer at least 256 as `Eagle3.alloc` makes it. + pub fn scratchBytes(d: Dims) usize { + var sum: usize = 0; + for (d.scratch()) |b| sum += @max(b, 256); + return sum; + } +}; + +/// One layer: projections bf16 [out, in] (qkv and gate|up stacked), norms fp32. +pub const Layer = struct { qkv: u64, o: u64, gate_up: u64, down: u64, n1: u64, n2: u64 }; + +/// The drafter's weights and the target's: `embed` its table [V, hidden], `head` its rows for the draft vocabulary. +pub const Weights = struct { fuse: u64, fc: u64, layers: []const Layer, out_norm: u64, inv: u64, embed: u64, head: u64 }; + +/// The shared operators the passes launch, loaded by the caller (a target's family loads most of them already). +pub const Ops = struct { + dense: *const DenseRows, + norms: *const Norms, + qk: *const QkRows, + win: *const wa.WindowAttention, + embed: *const EmbedRows, + act: *const ActRows, + argmax: Function, // torch's first-maximum argmax over fp32 rows into int32 + to_bf16: Function, // fp32 to bf16, round to nearest even +}; + +/// One row of a pass: the stream's slot, its position, the token after it; `src` its tapped row or prior output. +pub const Row = struct { slot: u32, pos: u32, token: u32 }; + +pub const Eagle3 = struct { + gpa: std.mem.Allocator, + d: *const Driver, + s: Stream, + dims: Dims, + w: Weights, + ops: Ops, + slots: usize = 0, + kc: u64 = 0, // [slots, ring, heads, head_dim] bf16 + vc: u64 = 0, + out: u64 = 0, // [slots, hidden] bf16: each stream's last row's normed output (its next draft's state) + x: Scratch, + buffers: std.ArrayList(DeviceBuffer) = .empty, + caches: std.ArrayList(DeviceBuffer) = .empty, + host: []i32, // [3, pass_rows] staging: tokens, positions, slots + + const Scratch = struct { tin: u64, ids: u64, pos: u64, slot: u64, picks: u64, cat: u64, e: u64, st: u64, f: u64, z: u64, a: u64, qkv: u64, q: u64, k: u64, v: u64, att: u64, gu: u64, act: u64, part: u64, logits: u64 }; + + pub fn init(gpa: std.mem.Allocator, d: *const Driver, s: Stream, dims: Dims, w: Weights, ops: Ops) !Eagle3 { + if (dims.head_dim != 128 or dims.hidden % 64 != 0 or dims.ffn % 64 != 0 or dims.chain == 0) return error.Eagle3Shape; + var x: Eagle3 = .{ .gpa = gpa, .d = d, .s = s, .dims = dims, .w = w, .ops = ops, .x = undefined, .host = try gpa.alloc(i32, 3 * pass_rows) }; + errdefer x.deinit(); + const sizes = dims.scratch(); + inline for (@typeInfo(Scratch).@"struct".field_names, 0..) |name, i| @field(x.x, name) = try x.alloc(sizes[i]); + return x; + } + + pub fn deinit(x: *Eagle3) void { + for (x.buffers.items) |*b| b.free(); + x.buffers.deinit(x.gpa); + for (x.caches.items) |*b| b.free(); + x.caches.deinit(x.gpa); + x.gpa.free(x.host); + } + + fn alloc(x: *Eagle3, bytes: usize) !u64 { + const b = try DeviceBuffer.alloc(x.d, @max(bytes, 256)); + errdefer { + var y = b; + y.free(); + } + try x.buffers.append(x.gpa, b); + return b.ptr; + } + + /// Caches for `slots` streams (made once; a second call with no more slots keeps them). + pub fn reserve(x: *Eagle3, slots: usize) !void { + if (slots <= x.slots) return; + try x.s.synchronize(); + for (x.caches.items) |*b| b.free(); + x.caches.clearRetainingCapacity(); + x.slots = 0; + const per = x.dims.layers * x.dims.ring() * x.dims.att() * 2; + var bufs: [3]u64 = undefined; + for (&bufs, [_]usize{ slots * per, slots * per, slots * x.dims.hidden * 2 }) |*p, bytes| { + const b = try DeviceBuffer.alloc(x.d, bytes); + x.caches.append(x.gpa, b) catch |e| { + var y = b; + y.free(); + return e; + }; + p.* = b.ptr; + } + x.kc, x.vc, x.out = bufs; + x.slots = slots; + } + + fn window(x: *const Eagle3) wa.Window { + return x.dims.attention(); + } + + fn copy2d(x: *Eagle3, dst: u64, dst_pitch: usize, src: u64, src_pitch: usize, width: usize, rows: usize) !void { + const p: abi.Memcpy2D = .{ .src = src, .src_pitch = src_pitch, .dst = dst, .dst_pitch = dst_pitch, .width = width, .height = rows }; + try x.d.check(x.d.api.cuMemcpy2DAsync_v2(&p, x.s.handle), "cuMemcpy2DAsync"); + } + + fn toBf16(x: *Eagle3, src: u64, dst: u64, n: usize) !void { + var a: launch_.Args = .{}; + a.add(src); + a.add(dst); + a.add(@as(u64, n)); + try launch_.launch(x.ops.to_bf16, .{ .grid = .{ .x = @intCast(@max(1, @min((n + 255) / 256, 65535))) }, .block = .{ .x = 256 } }, x.s, &a); + } + + /// bf16 rows [m, k] times weight rows [n, k] into bf16 `out` [m, n], through the fp32 scratch. + fn linear(x: *Eagle3, in: u64, in_stride: usize, w: u64, out: u64, m: usize, n: usize, k: usize) !void { + try x.ops.dense.rows(x.s, in, in_stride, w, x.x.f, n, m, n, k); + try x.toBf16(x.x.f, out, m * n); + } + + /// Rows `keep` of the staged pass (their queries, residuals, positions, slots) to the front, in order. + fn pack(x: *Eagle3, keep: []const usize) !void { + const dm = x.dims; + const q = dm.att() * 2; + const z = dm.hidden * 4; + for (keep, 0..) |r, j| { + if (r == j) continue; + for ([_][2]u64{ .{ x.x.q, q }, .{ x.x.z, z } }) |b| try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(b[0] + j * b[1], b[0] + r * b[1], b[1], x.s.handle), "cuMemcpyDtoDAsync"); + x.host[pass_rows + j] = x.host[pass_rows + r]; + x.host[2 * pass_rows + j] = x.host[2 * pass_rows + r]; + } + for ([_]u64{ x.x.pos, x.x.slot }, 1..) |dst, at| try x.d.check(x.d.api.cuMemcpyHtoDAsync_v2(dst, &x.host[at * pass_rows], keep.len * 4, x.s.handle), "cuMemcpyHtoDAsync"); + } + + /// The rows' tokens, positions and slots on the device (ids: the token embedded beside each row's state). + fn stage(x: *Eagle3, rows: []const Row) !void { + const n = rows.len; + for (rows, 0..) |r, i| { + x.host[i] = @intCast(r.token); + x.host[pass_rows + i] = @intCast(r.pos); + x.host[2 * pass_rows + i] = @intCast(r.slot); + } + for ([_]u64{ x.x.ids, x.x.pos, x.x.slot }, 0..) |dst, j| try x.d.check(x.d.api.cuMemcpyHtoDAsync_v2(dst, &x.host[j * pass_rows], n * 4, x.s.handle), "cuMemcpyHtoDAsync"); + } + + /// Staged rows through every layer into `a` (`fused`: taps fused first); `outs` (null: all) packed past the keys. + fn pass(x: *Eagle3, rows_in: usize, state: u64, state_ld: usize, fused: bool, outs: ?[]const usize) !void { + var n = rows_in; + const dm = x.dims; + const h = dm.hidden; + const sx = x.x; + try x.ops.embed.bf16(x.s, sx.ids, x.w.embed, sx.e, n, h); + try x.copy2d(sx.cat, 4 * h, sx.e, 2 * h, 2 * h, n); + if (fused) { + try x.linear(state, state_ld, x.w.fuse, sx.a, n, h, dm.taps * h); + try x.copy2d(sx.cat + 2 * h, 4 * h, sx.a, 2 * h, 2 * h, n); + } else try x.copy2d(sx.cat + 2 * h, 4 * h, state, 2 * state_ld, 2 * h, n); + try x.ops.dense.rows(x.s, sx.cat, 2 * h, x.w.fc, sx.z, h, n, h, 2 * h); + try x.ops.norms.rms(x.s, sx.z, .f32, x.w.layers[0].n1, sx.a, .bf16, n, h, dm.eps); + const att = dm.att(); + const win = x.window(); + for (x.w.layers, 0..) |l, i| { + try x.linear(sx.a, h, l.qkv, sx.qkv, n, 3 * att, h); + const shape: @import("qk_rows.zig").Shape = .{ .inv = x.w.inv, .rot = dm.head_dim }; + const kv_at = i * x.slots * dm.ring() * att * 2; + const out: @import("qk_rows.zig").Out = .{ .q = sx.q, .k = sx.k, .v = sx.v, .kc = x.kc + kv_at, .vc = x.vc + kv_at, .len = dm.ring() }; + try x.ops.qk.rows(x.s, sx.qkv, .{ .h = dm.heads, .hk = dm.heads, .dim = dm.head_dim }, shape, sx.pos, sx.slot, out, n); + if (i + 1 == x.w.layers.len) if (outs) |keep| if (keep.len < n) { + try x.pack(keep); + n = keep.len; + }; + try x.ops.win.decode(x.s, sx.q, x.kc + kv_at, x.vc + kv_at, sx.att, sx.pos, sx.slot, win, sx.part, n); + try x.ops.dense.rows(x.s, sx.att, att, l.o, sx.f, h, n, h, att); + try x.ops.norms.addRms(x.s, sx.f, .f32, sx.z, null, l.n2, sx.a, .bf16, n, h, dm.eps); + try x.linear(sx.a, h, l.gate_up, sx.gu, n, 2 * dm.ffn, h); + try x.ops.act.swiglu(x.s, sx.gu, 2 * dm.ffn, sx.gu + dm.ffn * 2, 2 * dm.ffn, sx.act, null, n, dm.ffn); + try x.ops.dense.rows(x.s, sx.act, dm.ffn, l.down, sx.f, h, n, h, dm.ffn); + const next = if (i + 1 < x.w.layers.len) x.w.layers[i + 1].n1 else x.w.out_norm; + try x.ops.norms.addRms(x.s, sx.f, .f32, sx.z, null, next, sx.a, .bf16, n, h, dm.eps); + } + } + + /// A stream's kept rows (positions rising), their taps [rows.len, taps * hidden] bf16; end: rows read to here. + pub const Part = struct { rows: []const Row, taps: u64, end: u64 = 0 }; + + /// Every part's rows read (Dims.firstNeeded on) in as few passes as fit; each slot's last output kept. + pub fn absorbMany(x: *Eagle3, parts: []const Part) !void { + const dm = x.dims; + if (x.slots == 0) return error.NoCaches; + const row = dm.taps * dm.hidden * 2; + var batch: [pass_rows]Row = undefined; + var n: usize = 0; + for (parts) |whole| { + if (whole.rows.len == 0) continue; + for (whole.rows) |r| if (r.slot >= x.slots) return error.NoSuchDraftSlot; + const cut = dm.firstNeeded(@max(whole.end, @as(u64, whole.rows[whole.rows.len - 1].pos) + 1)); + var skip: usize = 0; + while (skip < whole.rows.len and whole.rows[skip].pos < cut) skip += 1; + const p: Part = .{ .rows = whole.rows[skip..], .taps = whole.taps + skip * row }; + var at: usize = 0; + while (at < p.rows.len) { + const take = @min(pass_rows - n, p.rows.len - at); + @memcpy(batch[n..][0..take], p.rows[at..][0..take]); + try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(x.x.tin + n * row, p.taps + at * row, take * row, x.s.handle), "cuMemcpyDtoDAsync"); + n += take; + at += take; + if (n == pass_rows) { + try x.absorbPass(batch[0..n]); + n = 0; + } + } + } + if (n > 0) try x.absorbPass(batch[0..n]); + } + + fn absorbPass(x: *Eagle3, rows: []const Row) !void { + const dm = x.dims; + const n = rows.len; + var outs: [pass_rows]usize = undefined; + var k: usize = 0; + for (rows, 0..) |r, i| if (i + 1 == n or rows[i + 1].slot != r.slot) { + outs[k] = i; + k += 1; + }; + try x.stage(rows); + const packs = n > pack_rows; // a round's few rows: the weights cost the same, packing would only add copies + try x.pass(n, x.x.tin, dm.taps * dm.hidden, true, if (packs) outs[0..k] else null); + for (outs[0..k], 0..) |i, j| { // each slot's last row: row j of `a` when packed, else row i + const at = if (packs) j else i; + try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(x.out + rows[i].slot * dm.hidden * 2, x.x.a + at * dm.hidden * 2, dm.hidden * 2, x.s.handle), "cuMemcpyDtoDAsync"); + } + } + + /// `steps` draft-vocabulary indices for each item (slot, last absorbed position) into out[item]; a sync a step. + pub fn chain(x: *Eagle3, items: []const Row, steps: usize, map: []const u32, out: [][]u32) !void { + const dm = x.dims; + const n = items.len; + if (n > pass_rows or steps > dm.chain) return error.TooManyDraftRows; + const h = dm.hidden; + var rows: [pass_rows]Row = undefined; + for (items, 0..) |it, i| { + if (it.slot >= x.slots) return error.NoSuchDraftSlot; + try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(x.x.a + i * h * 2, x.out + it.slot * h * 2, h * 2, x.s.handle), "cuMemcpyDtoDAsync"); + } + var picks: [pass_rows]i32 = undefined; + for (0..steps) |j| { + if (j > 0) { // the step's state is the last step's output; its keys sit past the context, uncommitted + for (items, rows[0..n], 0..) |it, *r, i| r.* = .{ .slot = it.slot, .pos = it.pos + @as(u32, @intCast(j)), .token = map[out[i][j - 1]] }; + try x.stage(rows[0..n]); + try x.d.check(x.d.api.cuMemcpyDtoDAsync_v2(x.x.st, x.x.a, n * h * 2, x.s.handle), "cuMemcpyDtoDAsync"); + try x.pass(n, x.x.st, h, false, null); + } + try x.ops.dense.rows(x.s, x.x.a, h, x.w.head, x.x.logits, dm.vocab, n, dm.vocab, h); + var a: launch_.Args = .{}; + a.add(x.x.logits); + a.add(x.x.picks); + for ([_]usize{ n, dm.vocab, dm.vocab }) |v| a.add(@as(i64, @intCast(v))); + a.add(@as(i32, 1)); // fp32 rows + try launch_.launch(x.ops.argmax, .{ .grid = .{ .x = @intCast(n) }, .block = .{ .x = 1024 } }, x.s, &a); + try x.s.synchronize(); + try @import("memory.zig").download(x.d, x.x.picks, std.mem.sliceAsBytes(picks[0..n])); + for (out[0..n], picks[0..n]) |o, p| { + if (p < 0 or p >= dm.vocab) return error.DraftPickOutOfRange; + o[j] = @intCast(p); + } + } + } +}; + +test "a stream's ring holds the window, a pass and a chain in whole key tiles" { + const d: Dims = .{ .hidden = 2560, .heads = 20, .head_dim = 128, .ffn = 4096, .layers = 1, .taps = 3, .vocab = 32768, .window = 2048, .chain = 8, .eps = 1e-6 }; + try std.testing.expectEqual(@as(usize, 2368), d.ring()); + try std.testing.expect(d.ring() >= d.window + pass_rows + d.chain and d.ring() % 64 == 0); + try std.testing.expectEqual(@as(usize, 2 * 2368 * 2560 * 2 + 2560 * 2), d.streamBytes()); +} + +test "an absorb computes only the rows its last output and later rows read: a window back for one layer" { + const d: Dims = .{ .hidden = 2560, .heads = 20, .head_dim = 128, .ffn = 4096, .layers = 1, .taps = 3, .vocab = 32768, .window = 2048, .chain = 8, .eps = 1e-6 }; + // a 7,900-row prompt part [0, 7899): its last row (7898) reads keys 5851..7898, the next row 5852..7899 + try std.testing.expectEqual(@as(u64, 7899 - 2048), d.firstNeeded(7899)); + try std.testing.expectEqual(@as(u64, 0), d.firstNeeded(2048)); + try std.testing.expectEqual(@as(u64, 0), d.firstNeeded(5)); + var two = d; + two.layers = 2; // a second layer's keys read the first layer's outputs a window further back + try std.testing.expectEqual(@as(u64, 7899 - 1 - 2 * 2047), two.firstNeeded(7899)); +} diff --git a/zig/src/cuda/root.zig b/zig/src/cuda/root.zig index 1ef28094724..d4b15647406 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -87,6 +87,7 @@ pub const window_attention = @import("window_attention.zig"); pub const moe_glue = @import("moe_glue.zig"); pub const mla = @import("mla.zig"); pub const dense_rows = @import("dense_rows.zig"); +pub const eagle3 = @import("eagle3.zig"); pub const exl3 = @import("exl3.zig"); pub const exl3_experts = @import("exl3_experts.zig"); pub const exl3_upload = @import("exl3_upload.zig"); @@ -128,6 +129,7 @@ test { _ = @import("vit.zig"); _ = @import("tree_round.zig"); _ = @import("act_rows.zig"); + _ = @import("eagle3.zig"); _ = @import("gdn_prep.zig"); _ = @import("qk_rows.zig"); _ = @import("exl3_candidate.zig"); diff --git a/zig/src/families/kolibri1/backend.zig b/zig/src/families/kolibri1/backend.zig index 85f806fa59d..c161e6d8ce1 100644 --- a/zig/src/families/kolibri1/backend.zig +++ b/zig/src/families/kolibri1/backend.zig @@ -9,6 +9,7 @@ const snap = @import("snap.zig"); const limits = @import("context.zig"); const kv = @import("core").kv_pool; const kp = @import("core").kv_prompts; +const tap = @import("taps.zig"); const be = lanes.backend; const Stream = lanes.Stream; @@ -68,6 +69,7 @@ pub const Kolibri = struct { pool: ?kv.Pool = null, // paged: the pages every slot leases (attach) prompts: ?kp.Prompts = null, // TF_KV_SHARE: the store keeping prompts as the pool's pages (cuda_prompt_pages.zig) pending: ?*const snap.Saved = null, // TF_KV_SHARE: a resumed state's rings, put in once its lane opens + taps: tap.Taps = .{}, // a drafter's tapped rows, once it names its layers (prepare_features) /// The device bytes `init` allocates: a round's logits, the token ring, and each slot's last row and rule. pub fn openBytes(vocab: usize, slots: usize) usize { @@ -127,6 +129,7 @@ pub const Kolibri = struct { } if (x.pool) |*p| p.deinit(); x.lanes.deinit(x.gpa); + x.taps.deinit(x.gpa); for (x.slot_bufs) |*b| b.free(); x.gpa.free(x.slot_bufs); for (x.steps) |*g| if (g.*) |*e| e.exec.deinit(); @@ -143,7 +146,7 @@ pub const Kolibri = struct { return .{ .ptr = x, .vtable = &vtable }; } - const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .cancel_prefill = cancelPrefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true }; + const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .cancel_prefill = cancelPrefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true, .prepare_features = prepareFeatures, .features = features, .prompt_held = promptHeld }; /// The round loop's facts: no draft head; host copies verified in windows up to 16 rows, streams sharing a forward. pub fn facts(x: *const Kolibri) lanes.Model { @@ -154,7 +157,7 @@ pub const Kolibri = struct { return @ptrCast(@alignCast(ptr)); } - fn ops(x: *const Kolibri) kern.Ops { + pub fn ops(x: *const Kolibri) kern.Ops { return .{ .k = x.k, .s = x.s }; } @@ -294,11 +297,24 @@ pub const Kolibri = struct { l.sampled = true; } s.cached = 0; + s.rebuilt = null; + s.fed = 0; l.fill = if (x.prompts != null) try x.resumeShared(s, l) else x.resumeAt(s, l, p.len); s.fill_at.store(@intCast(l.fill.?), .monotonic); + if (x.rebuild(s)) |from| l.fill = from; return l; } + /// A drafted prompt within the slab, restored below a sliding window: re-run from row 0, its taps as cold. + fn rebuild(x: *const Kolibri, s: *Stream) ?u32 { + if (s.cached == 0 or !s.drafts or s.max_new < 2 or x.taps.slab == null) return null; + const from: u32 = @intCast(s.prompt().len -| tap.slab_rows); + if (from >= s.cached) return null; // the pass from the restore fills the whole slab already + if (from > 0 or s.cached >= x.m.c.window) return null; // a kept state: a sliding window's keys only + s.rebuilt = from; + return from; + } + /// The kept state's position, restored into the slot (0: none, or not this prompt's); any row resumes exactly. fn resumeAt(x: *Kolibri, s: *Stream, l: *const Lane, len: usize) usize { const saved = s.reuse.saved orelse return 0; @@ -336,27 +352,30 @@ pub const Kolibri = struct { const p = s.prompt(); const at = l.fill.?; if (s.isCancelled()) { - s.keepInterruptedPrefill(@intCast(at)); + s.keepInterruptedPrefill(@intCast(@max(at, s.cached))); return error.Cancelled; } var end = @min(p.len, (at / prompt_rows + 1) * prompt_rows); const marks = if (x.prompts != null) l.marks else s.reuse.marks; - for (marks) |mk| if (mk > at and mk < end) { + for (marks) |mk| if (mk > @max(at, s.cached) and mk < end) { end = mk; }; - try x.m.forward(x.ops(), &.{.{ .slot = l.slot, .p0 = at, .tokens = p[at..end] }}, true, null, l.last); - s.fill_at.store(@intCast(end), .monotonic); + const ch: fwd.Chain = .{ .slot = l.slot, .p0 = at, .tokens = p[at..end] }; + try x.m.forward(x.ops(), &.{ch}, true, null, l.last); + try x.taps.keptPrompt(x.gpa, x.m, x.s, ch, p.len); + s.fill_at.store(@intCast(@max(end, s.cached)), .monotonic); + s.fed = @intCast(end); // the drafter's frontier: a replay below the restore reports its real end const done = end == p.len; l.fill = if (done) null else end; if (done) l.len = p.len; if (x.prompts) |pr| { - if (!done and std.mem.indexOfScalar(u32, l.marks, @intCast(end)) != null) x.keepPages(pr, s, l, end) catch |e| { + if (!done and end > s.cached and std.mem.indexOfScalar(u32, l.marks, @intCast(end)) != null) x.keepPages(pr, s, l, end) catch |e| { std.log.warn("kolibri1: prompt pages not kept: {s}", .{@errorName(e)}); }; if (done) pr.report(p.len, s.cached, l.kept); return done; } - if (s.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) hk.at(hk.ptr, s, @intCast(end)); + if (s.reuse.hook) |hk| if (end > s.cached and std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) hk.at(hk.ptr, s, @intCast(end)); return done; } @@ -377,7 +396,7 @@ pub const Kolibri = struct { fn cancelPrefill(ptr: *anyopaque, s: *Stream) !void { const l = self(ptr).lanes.getPtr(s) orelse return; - if (l.fill) |at| s.keepInterruptedPrefill(@intCast(at)); + if (l.fill) |at| s.keepInterruptedPrefill(@intCast(@max(at, s.cached))); } fn handle(x: *Kolibri) usize { @@ -417,13 +436,16 @@ pub const Kolibri = struct { /// One row at the lane's cache length: the slot's captured graph (captured at its first step), else eager. fn step(x: *Kolibri, l: *Lane, token: u32) !u64 { try x.reach(l, l.len + 1); + const ch: fwd.Chain = .{ .slot = l.slot, .p0 = l.len, .tokens = &.{token} }; if (!x.graphed) { - try x.m.forward(x.ops(), &.{.{ .slot = l.slot, .p0 = l.len, .tokens = &.{token} }}, false, null, x.logits.ptr); + try x.m.forward(x.ops(), &.{ch}, false, null, x.logits.ptr); + try x.taps.kept(x.gpa, x.m, x.s, &.{ch}, false); return x.logits.ptr; } const g = &x.steps[l.slot]; if (g.* == null) g.* = try x.m.captureStep(x.ops(), l.slot); try x.m.step(x.ops(), &g.*.?, token, l.len); + try x.taps.kept(x.gpa, x.m, x.s, &.{ch}, false); // the graph's copies wrote tap_rows' first row return g.*.?.logits; } @@ -460,13 +482,16 @@ pub const Kolibri = struct { var logits = x.logits.ptr; if (total == 1) { logits = try x.step(x.lanes.getPtr(windows[0].stream).?, chains[0].tokens[0]); // a lone row: the step - } else if (x.graphed) { - try x.rounds.forward(x.m, x.ops(), chains, logits); // every row's logits, as the eager forward below } else { - const rows = try x.gpa.alloc(usize, total); - defer x.gpa.free(rows); - for (rows, 0..) |*r, i| r.* = i; - try x.m.forward(x.ops(), chains, false, rows, logits); + if (x.graphed) { + try x.rounds.forward(x.m, x.ops(), chains, logits); // every row's logits, as the eager forward below + } else { + const rows = try x.gpa.alloc(usize, total); + defer x.gpa.free(rows); + for (rows, 0..) |*r, i| r.* = i; + try x.m.forward(x.ops(), chains, false, rows, logits); + } + try x.taps.kept(x.gpa, x.m, x.s, chains, false); // graphed or eager, the round's copies wrote tap_rows } var at: usize = 0; for (windows, 0..) |w, i| { @@ -496,6 +521,7 @@ pub const Kolibri = struct { if (path.len == 0 or path.len > l.rows.items.len) return error.EmptyPath; for (path, 0..) |r, i| if (r != i) return error.ChainsOnly; // a chain keeps a prefix of its rows l.len = l.base + path.len; // caches are positional: later rows overwrite what the rejected ones wrote + x.taps.keepTo(l.slot, l.len); // nor are the rejected rows' taps handed out } } @@ -504,6 +530,33 @@ pub const Kolibri = struct { for (requests) |r| if (r.depth != 0 or r.lanes != null) return error.NoDraftHead; } + /// The drafter's layers, before any stream: forwards copy them out from now on (graphs captured again). + fn prepareFeatures(ptr: *anyopaque, taps: []const u32) anyerror!void { + const x = self(ptr); + if (x.lanes.count() != 0) return error.TapsAfterStreams; + for (x.steps) |*g| if (g.*) |*e| { // a step captured before copies no taps + e.exec.deinit(); + g.* = null; + }; + x.rounds.drop(); // nor does a round's + try x.taps.prepare(x.gpa, x.m, taps); + } + + /// Rows [start, start + count) of the stream's taps, while the target still holds them. + fn features(ptr: *anyopaque, s: *Stream, taps: []const u32, start: u64, count: u32) anyerror!be.Features { + const x = self(ptr); + if (!std.mem.eql(u32, taps, x.taps.ids[0..x.taps.n])) return error.TapsMismatch; + const l = x.lanes.getPtr(s) orelse return error.UnknownStream; + return x.taps.view(x.m, l.slot, start, count); + } + + /// The first prompt position whose taps wait for the stream's first draft (its slab's), else null. + fn promptHeld(ptr: *anyopaque, s: *Stream) ?u64 { + const x = self(ptr); + const l = x.lanes.getPtr(s) orelse return null; + return x.taps.slabFrom(l.slot); + } + fn dropLane(x: *Kolibri, s: *const Stream) void { if (x.lanes.fetchRemove(s)) |entry| { var l = entry.value; @@ -512,6 +565,7 @@ pub const Kolibri = struct { x.m.unmapPages(l.slot); } x.free[l.slot] = true; + x.taps.drop(l.slot); l.rows.deinit(x.gpa); x.gpa.free(l.marks); if (x.lanes.count() == 0) x.report(); diff --git a/zig/src/families/kolibri1/cuda.zig b/zig/src/families/kolibri1/cuda.zig index 3f3027723b5..46e42201d24 100644 --- a/zig/src/families/kolibri1/cuda.zig +++ b/zig/src/families/kolibri1/cuda.zig @@ -10,7 +10,11 @@ pub const kernels = @import("kernels.zig"); pub const forward = @import("forward.zig"); pub const rounds = @import("rounds.zig"); pub const snap = @import("snap.zig"); +pub const paging = @import("paging.zig"); +pub const taps = @import("taps.zig"); pub const backend = @import("backend.zig"); +pub const drafter = @import("drafter.zig"); +pub const row_costs = @import("row_costs.zig"); pub const native = @import("native.zig"); test { @@ -23,7 +27,10 @@ test { _ = @import("kernels.zig"); _ = @import("forward.zig"); _ = @import("rounds.zig"); + _ = @import("row_costs.zig"); _ = @import("snap.zig"); + _ = @import("taps.zig"); _ = @import("backend.zig"); + _ = @import("drafter.zig"); _ = @import("native.zig"); } diff --git a/zig/src/families/kolibri1/drafter.zig b/zig/src/families/kolibri1/drafter.zig new file mode 100644 index 00000000000..2a2bff9c648 --- /dev/null +++ b/zig/src/families/kolibri1/drafter.zig @@ -0,0 +1,531 @@ +//! Kolibri-1's published EAGLE-3 drafter: core's release checks, cuda/eagle3.zig's passes, the lane core's Drafted. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const core = @import("core"); +const be = @import("backend.zig"); +const kern = @import("kernels.zig"); +const wts = @import("weights.zig"); +const row_costs = @import("row_costs.zig"); +const tap = @import("taps.zig"); + +const dr = lanes.drafter; +const Stream = lanes.Stream; +const release = core.drafter_release; +const published = core.drafter_published; +const E = cuda.eagle3; + +/// The one checkpoint of model type kolibri1: the target a published release names. +pub const target_repo = "Aleph-Alpha/Kolibri-1"; +const chain = release.most_chain; +/// Stream counts a hold pass is timed at (the lane core interpolates between them and extends past the widest). +const hold_streams = [_]u32{ 1, 2, 4, 8 }; + +/// The target the server loaded, as a release's adapter compares it. +pub fn adapter(c: @import("config.zig").Config) release.Adapter { + return .{ .layers = @intCast(c.layers), .hidden = @intCast(c.hidden), .vocab = @intCast(c.vocab), .embed_scale = 1.0, .tied = false, .softcap = null, .head_bias = false }; +} + +fn gib(bytes: u64) f64 { + return @as(f64, @floatFromInt(bytes)) / (1 << 30); +} + +const Lane = struct { slot: u32, pos: u64 = 0, token: u32 = 0, rows: bool = false, held: [chain]u32 = undefined, held_len: u32 = 0 }; + +/// `free` as `n` slots, every one free but the last (the timing slot); the old table freed only once the new is made. +fn growSlots(gpa: std.mem.Allocator, free: *[]bool, n: usize) !void { + const grown = try gpa.alloc(bool, n); + @memset(grown, true); + grown[n - 1] = false; + gpa.free(free.*); + free.* = grown; +} + +pub const Drafter = struct { + gpa: std.mem.Allocator, + io: std.Io, + kb: *be.Kolibri, + act: cuda.act_rows.ActRows, + e: E.Eagle3, + vocab: []u32, // draft index -> target id + taps: [8]u32 = undefined, + n_taps: usize, + depth: u32, + step_ms: f64 = 0, + costs: [row_costs.widths.len]lanes.config.Cost = undefined, // the target's round ms by rows (timed at reserve) + n_costs: usize = 0, // the widths the served streams' slots hold + holds: [2 * hold_streams.len]lanes.hold_price.HoldCost = undefined, // a hold pass's ms by streams and depth + n_holds: usize = 0, + absorb_ms: f64 = 0, // one absorb pass of a round's rows (timed at reserve): rounds that hold pay it + timed: bool = false, + lanes: std.AutoHashMapUnmanaged(*Stream, Lane) = .empty, + free: []bool = &.{}, // drafter slot i is free (the last slot times a step and is never a stream's) + layers: []E.Layer, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + + /// The release in `dir` over `kb`'s model: refused by name (logged) if not served or past `load`'s device bytes. + pub fn open(gpa: std.mem.Allocator, io: std.Io, kb: *be.Kolibri, k: *const kern.Kernels, dir: []const u8, load: Load) !*Drafter { + var folder = try std.Io.Dir.cwd().openDir(io, dir, .{}); + defer folder.close(io); + var why: release.Why = .{}; + var r = published.Release.open(gpa, io, folder, .{ .repo = target_repo, .adapter = adapter(kb.m.c) }, &why) catch |e| { + if (why.len > 0) std.log.err("--drafter {s}: {s}", .{ dir, why.text() }); + return e; + }; + defer r.deinit(gpa); + const c = &r.manifest.config; + if (c.architecture != .eagle3) { + std.log.err("--drafter {s}: a {s} release; Kolibri-1 on CUDA serves eagle3 releases", .{ dir, @tagName(c.architecture) }); + return error.DrafterArchitectureNotServed; + } + _ = admit(c, r.vocab.len, load) catch |e| { + std.log.err("--drafter {s}: needs {d:.2} GiB of device memory for {d} stream{s} and a timing slot, the target's taps {d:.2} GiB and the first stream's window {d:.2} GiB; the budget leaves {d:.2} GiB", .{ dir, gib(need(c, r.vocab.len, load.slots)), load.slots, if (load.slots == 1) "" else "s", gib(load.tap_rows * tapRowBytes(c)), gib(load.first), gib(load.left.?) }); + return e; + }; + const x = try gpa.create(Drafter); + errdefer gpa.destroy(x); + x.* = .{ .gpa = gpa, .io = io, .kb = kb, .act = undefined, .e = undefined, .vocab = try gpa.dupe(u32, r.vocab), .n_taps = c.taps.ids.len, .depth = c.serving.depth, .layers = &.{} }; + errdefer gpa.free(x.vocab); + for (c.taps.ids, 0..) |id, i| x.taps[i] = id - 1; // the format's "after id layers" is layer id - 1's output + x.act = try cuda.act_rows.ActRows.load(kb.d); + errdefer x.act.unload(); + errdefer x.freeWeights(); + const w = try x.upload(dir, c, r.names, k); + const ops: E.Ops = .{ .dense = &k.dense, .norms = &k.norms, .qk = &k.qk, .win = &k.win, .embed = &k.embed, .act = &x.act, .argmax = k.argmax_fn, .to_bf16 = k.to_bf16_fn }; + x.e = try E.Eagle3.init(gpa, kb.d, kb.s, dimsOf(c, x.vocab.len), w, ops); + errdefer x.e.deinit(); + try x.e.reserve(load.now); // before the server reads its room: what its stream plan leaves out is held already + return x; + } + + /// The passes' shapes for release config `c` and a draft vocabulary of `vocab` rows. + fn dimsOf(c: *const release.Config, vocab: usize) E.Dims { + const s = c.drafter; + return .{ .hidden = s.hidden, .heads = s.heads, .head_dim = s.head_dim, .ffn = s.ffn, .layers = s.layers, .taps = c.taps.ids.len, .vocab = vocab, .window = s.window, .chain = chain, .eps = @floatCast(s.eps) }; + } + + /// Device bytes `upload` puts, from the shapes `core.drafter_layout` checked (projections bf16, norms fp32). + pub fn weightBytes(c: *const release.Config, vocab: usize) usize { + const s = c.drafter; + const d: usize = s.hidden; + const att = @as(usize, s.heads) * s.head_dim; + const t: usize = c.target.hidden; + const layer = [_]usize{ 3 * att * d * 2, d * att * 2, 2 * s.ffn * d * 2, d * s.ffn * 2, d * 4, d * 4 }; + const rest = [_]usize{ vocab * 4, vocab * d * 2, d * c.taps.ids.len * t * 2, d * (t + d) * 2, d * 4, s.head_dim / 2 * 4 }; + var sum: usize = 0; + for (layer) |b| sum += s.layers * @max(b, 256); + for (rest) |b| sum += @max(b, 256); + return sum; + } + + /// Device bytes the drafter takes beside `slots` streams: weights, scratch, each slot's caches and a timing slot's. + pub fn need(c: *const release.Config, vocab: usize, slots: usize) usize { + const dm = dimsOf(c, vocab); + return weightBytes(c, vocab) + dm.scratchBytes() + (slots + 1) * dm.streamBytes(); + } + + /// What a load holds once served, read before the drafter allocates anything. + pub const Load = struct { + slots: usize, // the streams reserve() gets at most, if known now (else 1: the plan pays each later one's) + first: u64 = 0, // the first stream's target window, made after the drafter (paged caches: the plan's) + now: usize, // drafter slots allocated at open: those the server's stream plan does not count + left: ?u64, // the budget's room now (null: unread) + tap_rows: usize = 0, // rows of the taps the target keeps (taps.heldRows), allocated before the pool plan + }; + + /// Bytes of one tap row: every tapped layer's target hidden values, bf16. + pub fn tapRowBytes(c: *const release.Config) usize { + return c.taps.ids.len * @as(usize, c.target.hidden) * 2; + } + + /// `need`, the target's tap rows and the first window when `load.left` holds them, else DrafterPastMemory. + pub fn admit(c: *const release.Config, vocab: usize, load: Load) error{DrafterPastMemory}!usize { + const bytes = need(c, vocab, load.slots) + load.tap_rows * tapRowBytes(c) + load.first; + if (load.left) |l| if (l < bytes) return error.DrafterPastMemory; + return bytes; + } + + fn put(x: *Drafter, bytes: []const u8) !u64 { + const b = try cuda.DeviceBuffer.alloc(x.kb.d, @max(bytes.len, 256)); + errdefer { + var y = b; + y.free(); + } + try b.upload(0, bytes); + try x.buffers.append(x.gpa, b); + return b.ptr; + } + + fn freeWeights(x: *Drafter) void { + for (x.buffers.items) |*b| b.free(); + x.buffers.deinit(x.gpa); + x.gpa.free(x.layers); + } + + /// The release's tensors on the device: projections bf16 (q|k|v and gate|up stacked), norms fp32, the head's rows. + fn upload(x: *Drafter, dir: []const u8, c: *const release.Config, names: core.drafter_layout.Names, k: *const kern.Kernels) !E.Weights { + var arena: std.heap.ArenaAllocator = .init(x.gpa); + defer arena.deinit(); + const a = arena.allocator(); + var f = try core.safetensors.File.open(x.gpa, x.io, try std.fs.path.join(a, &.{ dir, published.weights })); + defer f.close(x.io); + const L = struct { + fn get(file: *const core.safetensors.File, al: std.mem.Allocator, n: core.drafter_layout.Names, name: []const u8) !core.safetensors.Tensor { + return file.get(try n.of(al, name)) orelse error.DrafterTensorMissing; + } + }; + const bf = struct { + fn rows(al: std.mem.Allocator, ts: []const core.safetensors.Tensor) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + for (ts) |t| { + if (t.dtype != .bf16) return error.DrafterWeightNotBf16; // the published releases store bf16 + try out.appendSlice(al, t.bytes); + } + return out.items; + } + fn norm(al: std.mem.Allocator, t: core.safetensors.Tensor) ![]const u8 { + const n = t.shape[0]; + const v = try al.alloc(f32, n); + for (v, 0..) |*o, i| o.* = switch (t.dtype) { + .f32 => @bitCast(std.mem.readInt(u32, t.bytes[4 * i ..][0..4], .little)), + .bf16 => @bitCast(@as(u32, std.mem.readInt(u16, t.bytes[2 * i ..][0..2], .little)) << 16), + else => return error.DrafterNormDtype, + }; + return std.mem.sliceAsBytes(v); + } + }; + x.layers = try x.gpa.alloc(E.Layer, c.drafter.layers); + for (x.layers, 0..) |*l, i| { + var g: [7]core.safetensors.Tensor = undefined; + for (&g, [_][]const u8{ "q", "k", "v", "o", "gate", "up", "down" }) |*t, p| t.* = try L.get(&f, a, names, try std.fmt.allocPrint(a, "layers.{d}.{s}.weight", .{ i, p })); + l.* = .{ .qkv = try x.put(try bf.rows(a, g[0..3])), .o = try x.put(try bf.rows(a, g[3..4])), .gate_up = try x.put(try bf.rows(a, g[4..6])), .down = try x.put(try bf.rows(a, g[6..7])), .n1 = try x.put(try bf.norm(a, try L.get(&f, a, names, try std.fmt.allocPrint(a, "layers.{d}.n1.w", .{i})))), .n2 = try x.put(try bf.norm(a, try L.get(&f, a, names, try std.fmt.allocPrint(a, "layers.{d}.n2.w", .{i})))) }; + } + const inv = try a.alloc(f32, c.drafter.head_dim / 2); + core.rope_freq.inverseFrequencies(c.drafter.theta, c.drafter.head_dim, inv); + // the head's rows for the draft vocabulary, gathered on the device from the target's head + const ids = try a.alloc(i32, x.vocab.len); + for (ids, x.vocab) |*o, v| o.* = @intCast(v); + const id_buf = try x.put(std.mem.sliceAsBytes(ids)); + const slice = try cuda.DeviceBuffer.alloc(x.kb.d, x.vocab.len * c.drafter.hidden * 2); + x.buffers.append(x.gpa, slice) catch |e| { + var y = slice; + y.free(); + return e; + }; + try k.embed.bf16(x.kb.s, id_buf, x.kb.m.w.head, slice.ptr, x.vocab.len, c.drafter.hidden); + try x.kb.s.synchronize(); + return .{ + .fuse = try x.put(try bf.rows(a, &.{try L.get(&f, a, names, "fuse.weight")})), + .fc = try x.put(try bf.rows(a, &.{try L.get(&f, a, names, "fc.weight")})), + .layers = x.layers, + .out_norm = try x.put(try bf.norm(a, try L.get(&f, a, names, "out_norm.w"))), + .inv = try x.put(std.mem.sliceAsBytes(inv)), + .embed = x.kb.m.w.embed, + .head = slice.ptr, + }; + } + + pub fn deinit(x: *Drafter) void { + x.kb.s.synchronize() catch {}; + x.e.deinit(); + x.act.unload(); + x.freeWeights(); + x.lanes.deinit(x.gpa); + x.gpa.free(x.free); + x.gpa.free(x.vocab); + x.gpa.destroy(x); + } + + /// Caches for `streams` streams and one more that times a step, then the step's and hold pass's costs. + pub fn reserve(x: *Drafter, streams: u32) !void { + if (streams + 1 <= x.free.len) return; + if (x.lanes.count() != 0) return error.DraftReserveWithStreams; + try x.e.reserve(streams + 1); + try x.clearCaches(); // the timing passes below read them: zeroed first, not fresh device memory + try growSlots(x.gpa, &x.free, streams + 1); + x.step_ms = try x.time(streams); + x.n_holds = try x.timeHolds(streams); // on the streams' slots: zeroed after, before any stream opens + x.absorb_ms = try x.timeAbsorb(streams); + try x.clearCaches(); + x.n_costs = try row_costs.time(x.kb, x.io, &x.costs); // the depth rule trades drafts against rows by them + x.timed = true; + } + + /// Every EAGLE-3 cache zeroed on the drafter's stream. + fn clearCaches(x: *Drafter) !void { + for (x.e.caches.items) |b| try x.kb.d.check(x.kb.d.api.cuMemsetD8Async(b.ptr, 0, b.len, x.kb.s.handle), "cuMemsetD8Async"); + } + + /// One more draft's ms: chains of `depth` and of 1 on the spare slot, the best of three each. + fn time(x: *Drafter, spare: u32) !f64 { + var out: [1][chain]u32 = undefined; + var outs = [_][]u32{&out[0]}; + var best: [2]f64 = @splat(std.math.inf(f64)); + const steps = [2]usize{ 1, @max(x.depth, 2) }; + for (0..4) |round| for (steps, 0..) |n, i| { + const t0 = std.Io.Clock.awake.now(x.io); + try x.e.chain(&.{.{ .slot = spare, .pos = 64, .token = 0 }}, n, x.vocab, &outs); + const ms = @as(f64, @floatFromInt(t0.durationTo(std.Io.Clock.awake.now(x.io)).toNanoseconds())) / 1e6; + if (round > 0) best[i] = @min(best[i], ms); + }; + return @max(best[1] - best[0], 0) / @as(f64, @floatFromInt(steps[1] - 1)); + } + + /// A hold pass of n streams at depth 1 and at the serving depth, best of three, on slots no stream holds yet. + fn timeHolds(x: *Drafter, streams: u32) !usize { + var out: [hold_streams[hold_streams.len - 1]][chain]u32 = undefined; + var outs: [out.len][]u32 = undefined; + var items: [out.len]E.Row = undefined; + for (&outs, &out, &items, 0..) |*o, *b, *it, slot| { + o.* = b; + it.* = .{ .slot = @intCast(slot), .pos = 64, .token = 0 }; + } + var n: usize = 0; + for (hold_streams) |k| { + if (k > streams) break; + for ([2]u32{ 1, @max(x.depth, 2) }) |depth| { + var best = std.math.inf(f64); + for (0..4) |round| { + const t0 = std.Io.Clock.awake.now(x.io); + try x.e.chain(items[0..k], depth, x.vocab, outs[0..k]); + const ms = @as(f64, @floatFromInt(t0.durationTo(std.Io.Clock.awake.now(x.io)).toNanoseconds())) / 1e6; + if (round > 0) best = @min(best, ms); + } + x.holds[n] = .{ .streams = k, .depth = depth, .ms = best }; + n += 1; + } + } + if (n == 0) return 0; + std.log.info("Kolibri drafter hold pass: 1 stream {d:.2}/{d:.2} ms, {d} streams {d:.2}/{d:.2} ms (depth 1/{d})", .{ x.holds[0].ms, x.holds[1].ms, x.holds[n - 1].streams, x.holds[n - 2].ms, x.holds[n - 1].ms, x.holds[1].depth }); + return n; + } + + /// An absorb pass of two rows a stream over up to 8 streams' slots, best of three: its weights read once. + fn timeAbsorb(x: *Drafter, streams: u32) !f64 { + const k: usize = @max(1, @min(streams, 8)); // usize: @min with 8 alone is a u4, and 2 * 8 overflows it + var rows: [16]E.Row = undefined; + for (rows[0 .. 2 * k], 0..) |*r, i| r.* = .{ .slot = @intCast(i / 2), .pos = @intCast(64 + i % 2), .token = 0 }; + const part: E.Eagle3.Part = .{ .rows = rows[0 .. 2 * k], .taps = x.kb.m.tap_rows }; + var best = std.math.inf(f64); + for (0..4) |round| { + const t0 = std.Io.Clock.awake.now(x.io); + try x.e.absorbMany(&.{part}); + try x.kb.s.synchronize(); + const ms = @as(f64, @floatFromInt(t0.durationTo(std.Io.Clock.awake.now(x.io)).toNanoseconds())) / 1e6; + if (round > 0) best = @min(best, ms); + } + std.log.info("Kolibri drafter absorb pass: {d} rows over {d} slots {d:.2} ms", .{ 2 * k, k, best }); + return best; + } + + pub fn drafter(x: *Drafter) dr.Drafter { + return .{ .kind = "EAGLE-3", .lazy = true, .fresh_only = true, .ptr = x, .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(ptr: *anyopaque) []const u32 { + const x = cast(ptr); + return x.taps[0..x.n_taps]; + } + + /// Chains of the release's serving depth, every stream's step in one pass, capped by the rule in shared rounds. + fn factsFn(ptr: *anyopaque) dr.Facts { + const x = cast(ptr); + const costs: []const lanes.config.Cost = if (x.timed) x.costs[0..x.n_costs] else &.{}; + const holds: []const lanes.hold_price.HoldCost = if (x.timed) x.holds[0..x.n_holds] else &.{}; + return .{ .limit_shared_drafts = true, .depth = x.depth, .step_ms = x.step_ms, .batched = true, .stream_bytes = x.e.dims.streamBytes(), .window_costs = costs, .lane_costs = costs, .hold_costs = holds, .lazy_rows = tap.mirror, .prompt_reach = if (x.e.dims.reach() < tap.slab_rows) @intCast(x.e.dims.reach()) else 0, .absorb_ms = if (x.timed) x.absorb_ms else 0 }; + } + + fn openFn(ptr: *anyopaque, s: *Stream) anyerror!void { + const x = cast(ptr); + if (x.lanes.contains(s)) return error.DraftStreamOpen; + const slot = std.mem.indexOfScalar(bool, x.free, true) orelse return error.NoDraftSlot; + try x.lanes.put(x.gpa, s, .{ .slot = @intCast(slot) }); + x.free[slot] = false; + } + + fn releaseFn(ptr: *anyopaque, s: *Stream) void { + const x = cast(ptr); + if (x.lanes.fetchRemove(s)) |e| x.free[e.value.slot] = true; // one CUDA stream: later writes queue behind + } + + /// Each item's kept rows into its stream's ring (its last row's output the next chain's start). + fn absorbFn(ptr: *anyopaque, items: []const dr.Absorb) anyerror!void { + const x = cast(ptr); + var rows: std.ArrayList(E.Row) = .empty; + defer rows.deinit(x.gpa); + var parts: std.ArrayList(E.Eagle3.Part) = .empty; + defer parts.deinit(x.gpa); + const width = x.n_taps * x.e.dims.hidden * 2; + for (items) |it| { + const f = it.features; + if (f.space != .device or f.dtype != .bf16 or f.row_bytes != width or it.rows != null) return error.DraftFeaturesUnsupported; + if (it.follow.len < f.rows) return error.DraftFollowShort; + if (!x.lanes.contains(it.stream)) return error.DraftStreamUnknown; + } + for (items) |it| { // rows of every stream first: `parts` slices them once they no longer move + const l = x.lanes.getPtr(it.stream).?; + for (0..it.features.rows) |i| try rows.append(x.gpa, .{ .slot = l.slot, .pos = @intCast(it.start + i), .token = it.follow[i] }); + } + var at: usize = 0; + for (items) |it| { + const f = it.features; + if (f.rows == 0) continue; + // a prompt chunk's rows a window before the prompt's last are never read + const end = it.stream.prompt().len -| 1; + try parts.append(x.gpa, .{ .rows = rows.items[at..][0..f.rows], .taps = f.buffer + f.offset, .end = end }); + at += f.rows; + const l = x.lanes.getPtr(it.stream).?; + l.pos = it.start + f.rows - 1; + l.token = it.follow[f.rows - 1]; + l.rows = true; + l.held_len = 0; + } + try x.e.absorbMany(parts.items); // one pass for every stream's rows: the drafter's weights read once + } + + /// Every stream's chain in one pass a step; the drafts read back as target ids. + fn holdFn(ptr: *anyopaque, holds: []const dr.Hold) anyerror!void { + const x = cast(ptr); + if (holds.len > E.pass_rows) return error.DraftTooManyStreams; + var items: [E.pass_rows]E.Row = undefined; + var picks: [E.pass_rows][chain]u32 = undefined; + var outs: [E.pass_rows][]u32 = undefined; + var steps: usize = 0; + for (holds, 0..) |h, i| { + const l = x.lanes.getPtr(h.stream) orelse return error.DraftStreamUnknown; + if (h.depth == 0 or h.depth > chain) return error.DraftDepth; + if (h.lanes != null) return error.DraftTreesUnsupported; + if (!l.rows or l.token != h.pending) return error.DraftContextGap; // it drafts after its last absorbed row + items[i] = .{ .slot = l.slot, .pos = @intCast(l.pos), .token = l.token }; + outs[i] = &picks[i]; + steps = @max(steps, h.depth); + } + try x.e.chain(items[0..holds.len], steps, x.vocab, outs[0..holds.len]); + for (holds, 0..) |h, i| { + const l = x.lanes.getPtr(h.stream).?; + for (l.held[0..h.depth], picks[i][0..h.depth]) |*t, p| t.* = x.vocab[p]; + l.held_len = h.depth; + } + } + + fn heldFn(ptr: *anyopaque, streams: []const *Stream, out: []const []u32) anyerror!void { + const x = cast(ptr); + for (streams, out) |s, o| { + const l = x.lanes.get(s) orelse return error.DraftStreamUnknown; + if (o.len > l.held_len) return error.DraftHeldFewer; + @memcpy(o, l.held[0..o.len]); + } + } +}; + +test "the loaded Kolibri-1 is the adapter its published drafters were trained against" { + const config = @import("config.zig"); + var why: config.Why = .{}; + const c = try config.parse(std.testing.allocator, config.pinned, &why); + const a = adapter(c); + try std.testing.expectEqual(@as(u32, 50), a.layers); + try std.testing.expectEqual(@as(u32, 2560), a.hidden); + try std.testing.expectEqual(@as(u32, 128000), a.vocab); +} + +test "the drafter's device bytes come from its config alone; one byte short refuses by name, nothing allocated" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const config = @import("config.zig"); + var why: config.Why = .{}; + const kc = try config.parse(arena.allocator(), config.pinned, &why); + // the published EAGLE-3 release's config.json (josch15366/Kolibri-1-EAGLE3-drafter), training counts left out + const text = + \\{"architecture": "kolibri1-eagle3-drafter", "target": "Aleph-Alpha/Kolibri-1", + \\ "drafter": {"hidden": 2560, "heads": 20, "head_dim": 128, "ffn": 4096, "eps": 1e-06, "theta": 10000.0, + \\ "layers": 1, "taps": 3}, "taps": [44, 47, 49], "draft_vocab": "draft_vocab.json", "draft_vocab_size": 32768} + ; + var rwhy: release.Why = .{}; + const got = try published.parse(arena.allocator(), text, .{ .repo = target_repo, .adapter = adapter(kc) }, &rwhy); + const c = &got.config; + const v = 32768; + // per layer q|k|v, o, gate|up, down, 2 norms; ids, head rows, fuse, fc, out_norm, RoPE (each listed in weightBytes) + try std.testing.expectEqual(@as(usize, 348813568), Drafter.weightBytes(c, v)); + const stream: usize = 2 * 2368 * 2560 * 2 + 2560 * 2; // a slot's keys, values and last output + const one = Drafter.need(c, v, 1); + try std.testing.expectEqual(348813568 + 70528256 + 2 * stream, one); // scratch 70528256: a pass of 256 rows + try std.testing.expectError(error.DrafterPastMemory, Drafter.admit(c, v, .{ .slots = 1, .now = 2, .left = one - 1 })); + try std.testing.expectEqual(one, try Drafter.admit(c, v, .{ .slots = 1, .now = 2, .left = one })); + try std.testing.expectEqual(one + 7 * stream, try Drafter.admit(c, v, .{ .slots = 8, .now = 9, .left = null })); +} + +test "DrafterPastMemory: --parallel 8 on pages counts 9 drafter slots and the first window, nothing allocated before" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const config = @import("config.zig"); + var why: config.Why = .{}; + const kc = try config.parse(arena.allocator(), config.pinned, &why); + const text = + \\{"architecture": "kolibri1-eagle3-drafter", "target": "Aleph-Alpha/Kolibri-1", + \\ "drafter": {"hidden": 2560, "heads": 20, "head_dim": 128, "ffn": 4096, "eps": 1e-06, "theta": 10000.0, + \\ "layers": 1, "taps": 3}, "taps": [44, 47, 49], "draft_vocab": "draft_vocab.json", "draft_vocab_size": 32768} + ; + var rwhy: release.Why = .{}; + const got = try published.parse(arena.allocator(), text, .{ .repo = target_repo, .adapter = adapter(kc) }, &rwhy); + const c = &got.config; + const v = 32768; + const stream: usize = 2 * 2368 * 2560 * 2 + 2560 * 2; + const window: u64 = 3 << 30; // the first stream's paged window, made after the drafter + const final = 348813568 + 70528256 + 9 * stream + window; + const fixed: Drafter.Load = .{ .slots = 8, .first = window, .now = 2, .left = final - 1 }; + try std.testing.expectError(error.DrafterPastMemory, Drafter.admit(c, v, fixed)); + // the old check (one stream, no window) let this budget through and failed or overran later + _ = try Drafter.admit(c, v, .{ .slots = 1, .now = 2, .left = final - 1 }); + try std.testing.expectEqual(final, try Drafter.admit(c, v, .{ .slots = 8, .first = window, .now = 2, .left = final })); + // admit takes numbers only, no allocator and no device: nothing can be allocated before it refuses + const Numbers = fn (*const release.Config, usize, Drafter.Load) error{DrafterPastMemory}!usize; + try std.testing.expect(@TypeOf(Drafter.admit) == Numbers); +} + +test "DrafterPastMemory: the target's tap ring for 64 paged slots and a prompt chunk's tap rows count, one byte short" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const config = @import("config.zig"); + const fwd = @import("forward.zig"); + var why: config.Why = .{}; + const kc = try config.parse(arena.allocator(), config.pinned, &why); + const text = + \\{"architecture": "kolibri1-eagle3-drafter", "target": "Aleph-Alpha/Kolibri-1", + \\ "drafter": {"hidden": 2560, "heads": 20, "head_dim": 128, "ffn": 4096, "eps": 1e-06, "theta": 10000.0, + \\ "layers": 1, "taps": 3}, "taps": [44, 47, 49], "draft_vocab": "draft_vocab.json", "draft_vocab_size": 32768} + ; + var rwhy: release.Why = .{}; + const got = try published.parse(arena.allocator(), text, .{ .repo = target_repo, .adapter = adapter(kc) }, &rwhy); + const c = &got.config; + const v = 32768; + // paged: the ring spans every slot a round can name (64), a forward's tap rows a prompt chunk (8,192) + const rows = @import("taps.zig").heldRows(fwd.prompt_rows, fwd.round_rows); + const ring: usize = 64 * (256 + 64) * 3 * 2560 * 2; // 314,572,800 B: 3 taps x 2,560 bf16, 256 + 64 rows a slot + const chunk: usize = 8192 * 3 * 2560 * 2 + 2048 * 3 * 2560 * 2; // 125,829,120 B and the prompt slab's 31,457,280 B + try std.testing.expectEqual(ring + chunk, rows * Drafter.tapRowBytes(c)); + const stream: usize = 2 * 2368 * 2560 * 2 + 2560 * 2; + const window: u64 = 3 << 30; + const untapped = 348813568 + 70528256 + 9 * stream + window; // --parallel 8: 9 drafter slots and the first window + const enough = untapped + ring + chunk; + var load: Drafter.Load = .{ .slots = 8, .first = window, .now = 2, .left = enough - 1, .tap_rows = rows }; + try std.testing.expectError(error.DrafterPastMemory, Drafter.admit(c, v, load)); + load.left = enough; + try std.testing.expectEqual(enough, try Drafter.admit(c, v, load)); + // control: without the taps (the accounting before) the same one-byte-short budget is admitted + load = .{ .slots = 8, .first = window, .now = 2, .left = enough - 1 }; + try std.testing.expectEqual(untapped, try Drafter.admit(c, v, load)); +} + +test "reserve's slot table: a larger reserve that fails to allocate keeps the smaller table, freed once at teardown" { + var fail: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 1 }); + const gpa = fail.allocator(); + var free: []bool = &.{}; + try growSlots(gpa, &free, 3); // a smaller reserve: 2 streams and the timing slot + try std.testing.expectError(error.OutOfMemory, growSlots(gpa, &free, 9)); // the larger one fails to allocate + try std.testing.expectEqualSlices(bool, &.{ true, true, false }, free); + gpa.free(free); // teardown: once, no double free (the testing allocator checks) +} diff --git a/zig/src/families/kolibri1/forward.zig b/zig/src/families/kolibri1/forward.zig index 92372ab8f01..8eb046c3445 100644 --- a/zig/src/families/kolibri1/forward.zig +++ b/zig/src/families/kolibri1/forward.zig @@ -60,6 +60,8 @@ pub const Model = struct { s: Scratch, buffers: std.ArrayList(DeviceBuffer) = .empty, planned: ?usize = null, // a plan: the bytes counted, nothing allocated + taps: []const u32 = &.{}, // layers whose normed outputs each forward copies out (a drafter's), in its order + tap_rows: u64 = 0, // bf16 [max_rows, taps.len * hidden]: the last forward's rows of those layers const Scratch = struct { ids: u64, pos: u64, slot: u64, res: u64, x: u64, qkv: u64, q: u64, kn: u64, vn: u64, att: u64, o: u64, part: u64, logits_e: u64, pick: u64, wts: u64, plan: grouped.Plan, act: u64, y: u64, mo: u64, flat: u64, paths: u64, depths: u64, offs: u64, sel: u64, win: u64, tree: u64, ctab: u64 }; @@ -533,11 +535,19 @@ pub const Model = struct { try o.combine(m.s.y, prompt, wt, m.s.mo, n, sl, c.hidden); const after = if (i + 1 < w.layers.len) w.layers[i + 1].input_norm else w.norm; try o.addRms(m.s.mo, m.s.res, L.post_moe_norm, after, m.s.x, n, c.hidden, c.eps); + if (std.mem.indexOfScalar(u32, m.taps, @intCast(i))) |j| try m.tap(s, j, n); // as the next layer reads it } for (pick, 0..) |r, j| try m.d.check(m.d.api.cuMemcpyDtoDAsync_v2(m.s.sel + j * c.hidden * 2, m.s.x + r * c.hidden * 2, c.hidden * 2, s.handle), "cuMemcpyDtoDAsync"); try o.dense(m.s.sel, c.hidden, w.head, out, pick.len, c.hidden, c.vocab); } + /// The rows' normed outputs of the drafter's tap `j` into column `j` of `tap_rows` (a copy: no kernel). + fn tap(m: *Model, s: cuda.Stream, j: usize, n: usize) !void { + const row = m.c.hidden * 2; + const p: cuda.abi.Memcpy2D = .{ .src = m.s.x, .src_pitch = row, .dst = m.tap_rows + j * row, .dst_pitch = m.taps.len * row, .width = row, .height = n }; + try m.d.check(m.d.api.cuMemcpy2DAsync_v2(&p, s.handle), "cuMemcpy2DAsync"); + } + /// One stream's one-row step as a CUDA graph: its stream row, paths and offsets fixed; a step writes token and row. pub const Step = struct { exec: cuda.graph.Exec, slot: usize, flat: u64, logits: u64 }; @@ -583,7 +593,6 @@ pub const Model = struct { try g.exec.launchOn(s); } }; - test { _ = @import("forward_offsets_test.zig"); _ = @import("forward_rope_test.zig"); diff --git a/zig/src/families/kolibri1/forward_test.zig b/zig/src/families/kolibri1/forward_test.zig index 0bf1b685275..ea54c1fa170 100644 --- a/zig/src/families/kolibri1/forward_test.zig +++ b/zig/src/families/kolibri1/forward_test.zig @@ -1,3 +1,4 @@ +//! Kolibri-1's forward without a GPU: the ring's size, the RoPE table's words, a page's bytes. const std = @import("std"); const fwd = @import("forward.zig"); const config = @import("config.zig"); @@ -11,18 +12,72 @@ test "kolibri1_1 plan: the two dense layers count their slot ids and weights onc try m.denseSlots(undefined, 8192); try std.testing.expectEqual(@as(usize, 2 * 8192 * 4), m.planned.?); } +const Model = fwd.Model; +const ringSize = fwd.ringSize; +const prompt_rows = fwd.prompt_rows; test "the ring holds a prompt chunk and a window, in whole key tiles" { - try std.testing.expectEqual(@as(usize, 8768), fwd.ringSize(fwd.prompt_rows, 513)); - try std.testing.expect(fwd.ringSize(fwd.prompt_rows, 513) - 513 >= fwd.prompt_rows); + try std.testing.expectEqual(@as(usize, 8768), ringSize(prompt_rows, 513)); + try std.testing.expect(ringSize(prompt_rows, 513) - 513 >= prompt_rows); +} + +test "the f64 angle table against core's words: 19 of 64 differ, first at 7" { + const rope_freq = @import("core").rope_freq; + // The site's f64 frequency rounded to fp32 (the word a move would store); it keeps the f64 value for the angle. + const theta: f64 = 1e4; // config.zig's default rope_theta + const dh = 128; + const site_words = [64]u32{ + 0x3f800000, 0x3f5dafd7, 0x3f3ff911, 0x3f263de0, 0x3f0ff59a, 0x3ef953cf, 0x3ed7e89b, 0x3ebaf81a, + 0x3ea1e89b, 0x3e8c3504, 0x3e72d424, 0x3e5247ed, 0x3e361887, 0x3e1db040, 0x3e088d77, 0x3dec7fd5, + 0x3dcccccd, 0x3db15978, 0x3d99940e, 0x3d84fe4d, 0x3d6655c3, 0x3d47763f, 0x3d2cba15, 0x3d159348, + 0x3d0186e2, 0x3ce054d2, 0x3cc24350, 0x3ca8398b, 0x3c91ad39, 0x3c7c4d33, 0x3c5a7bf1, 0x3c3d3311, + 0x3c23d70a, 0x3c0de12d, 0x3bf5b9b0, 0x3bd4ca14, 0x3bb8449c, 0x3b9f91cc, 0x3b8a2e77, 0x3b6f520d, + 0x3b4f3e37, 0x3b33770f, 0x3b1b690d, 0x3b06946f, 0x3ae91528, 0x3ac9d75c, 0x3aaec98e, 0x3a975c0e, + 0x3a83126f, 0x3a6301e2, 0x3a44948c, 0x3a2a3b43, 0x3a136a16, 0x39ff4fad, 0x39dd1726, 0x39bf74d7, + 0x39a5cb5f, 0x398f9272, 0x3978a814, 0x395753e5, 0x393a7753, 0x39217917, 0x390bd472, 0x38f22ce3, + }; + const core_words = [64]u32{ + 0x3f800000, 0x3f5dafd7, 0x3f3ff911, 0x3f263de0, 0x3f0ff59a, 0x3ef953cf, 0x3ed7e89b, 0x3ebaf81b, + 0x3ea1e89b, 0x3e8c3504, 0x3e72d423, 0x3e5247ed, 0x3e361887, 0x3e1db040, 0x3e088d77, 0x3dec7fd6, + 0x3dcccccd, 0x3db15978, 0x3d99940d, 0x3d84fe4d, 0x3d6655c2, 0x3d47763f, 0x3d2cba15, 0x3d159348, + 0x3d0186e3, 0x3ce054d2, 0x3cc2434f, 0x3ca8398b, 0x3c91ad39, 0x3c7c4d33, 0x3c5a7bf2, 0x3c3d3311, + 0x3c23d70a, 0x3c0de12d, 0x3bf5b9b0, 0x3bd4ca15, 0x3bb8449c, 0x3b9f91cc, 0x3b8a2e77, 0x3b6f520e, + 0x3b4f3e38, 0x3b33770f, 0x3b1b690d, 0x3b06946f, 0x3ae91528, 0x3ac9d75c, 0x3aaec98e, 0x3a975c0e, + 0x3a83126f, 0x3a6301e2, 0x3a44948c, 0x3a2a3b44, 0x3a136a16, 0x39ff4fac, 0x39dd1725, 0x39bf74d7, + 0x39a5cb60, 0x398f9272, 0x3978a815, 0x395753e4, 0x393a7753, 0x39217916, 0x390bd472, 0x38f22ce2, + }; + var site: [64]f32 = undefined; + var core: [64]f32 = undefined; + for (&site, 0..) |*f, j| { + const frac = @as(f64, @floatFromInt(2 * j)) / @as(f64, @floatFromInt(dh)); + f.* = @floatCast(1.0 / std.math.pow(f64, theta, frac)); + } + rope_freq.inverseFrequencies(theta, dh, &core); + var differ: usize = 0; + var first: ?usize = null; + var max_ulp: u32 = 0; + for (site, core, 0..) |s, c, j| { + try std.testing.expectEqual(site_words[j], @as(u32, @bitCast(s))); + try std.testing.expectEqual(core_words[j], @as(u32, @bitCast(c))); + const a: u32 = @bitCast(s); + const b: u32 = @bitCast(c); + if (a != b) { + differ += 1; + if (first == null) first = j; + max_ulp = @max(max_ulp, if (a > b) a - b else b - a); + } + } + try std.testing.expectEqual(@as(usize, 19), differ); + try std.testing.expectEqual(@as(?usize, 7), first); + try std.testing.expectEqual(@as(u32, 1), max_ulp); } test "a page's bytes: the pool's layout and the kernels' stride agree" { var why: config.Why = .{}; - var m: fwd.Model = undefined; + var m: Model = undefined; m.c = try config.parse(std.testing.allocator, config.pinned, &why); m.context = 32768; - m.ring = fwd.ringSize(fwd.prompt_rows, m.c.window); + m.ring = ringSize(prompt_rows, m.c.window); try std.testing.expectEqual(m.pageBytes(), m.layout().pageBytes()); try std.testing.expectEqual(@as(u32, 10), m.layout().group().layers); } diff --git a/zig/src/families/kolibri1/kernels.zig b/zig/src/families/kolibri1/kernels.zig index 484627d1799..d7ce1d16be0 100644 --- a/zig/src/families/kolibri1/kernels.zig +++ b/zig/src/families/kolibri1/kernels.zig @@ -172,11 +172,16 @@ pub const Ops = struct { try o.k.tree.run(o.s, q, kn, vn, rows, sc, out, n, h, hk, d, ng, scale); } - /// x [m, D] bf16 times rows [n, D] bf16 into fp32 [m, n] (the router and the head). + /// x [m, D] bf16 times rows [n, D] bf16 into fp32 [m, n] (the router and the head), the same bits at any m. pub fn dense(o: Ops, x: u64, x_stride: usize, rows: u64, out: u64, m: usize, d: usize, n: usize) !void { - try o.k.dense.rows(o.s, x, x_stride, rows, out, n, m, n, d); + if (m <= tile) return o.k.dense.rows(o.s, x, x_stride, rows, out, n, m, n, d); + // past a 16-row tile the tiled launch reads the 128k-row head once: 17..64 rows x1.2-2.3 (micro, GB10) + return o.k.dense.rowsTiled(o.s, x, x_stride, rows, out, n, m, n, d); } + /// Rows a narrow round launches in one tile; dense_rows.cu sums each row in one order whatever the launch. + pub const tile = 16; + /// Each row's top-k experts by sigmoid logit + bias, unnormalised sigmoid weights, then the shared expert's slot. pub fn topk(o: Ops, logits: u64, bias: u64, pick: u64, wts: u64, rows: usize, ne: usize, k: usize) !void { try o.k.moe.topk(o.s, logits, bias, .{ .experts = ne, .topk = k, .shared = true }, pick, wts, rows); diff --git a/zig/src/families/kolibri1/native.zig b/zig/src/families/kolibri1/native.zig index fb0c18d440b..b9f035a1b3c 100644 --- a/zig/src/families/kolibri1/native.zig +++ b/zig/src/families/kolibri1/native.zig @@ -10,6 +10,7 @@ const snap = @import("snap.zig"); const limits = @import("context.zig"); const kv = @import("core").kv_pool; const cfg = @import("config.zig"); +const eagle = @import("drafter.zig"); pub const model_type = "kolibri1"; /// Kolibri 1.1 (config_v11.zig): the same family, its dense layers, shared caches and window read from config.json. @@ -18,11 +19,10 @@ pub const formats: []const []const u8 = &.{"fp8-block"}; pub const default_context: i64 = 65536; pub const max_segments: u32 = 1; pub const prompt_rows: u32 = be.prompt_rows; -/// A kept state is the caches through its position and nothing past it (no draft head reads a token on). +/// A kept state is the caches through its position and nothing past it (a drafter reads the target's taps). pub const snap_lookahead: u32 = 0; -/// No drafter yet: --drafter is refused before the load. -pub const takes_drafter = false; -pub const drafter_refusal = "--drafter: Kolibri-1 on CUDA loads no drafter yet; serve it without --drafter"; +/// --drafter: a published EAGLE-3 release (drafter.zig), off unless named. +pub const takes_drafter = true; /// `explain` words this family's open refusals too. pub const explains_open = true; @@ -78,7 +78,7 @@ pub const Loaded = struct { engine_paged: bool = true, }; -const Owned = struct { gpa: std.mem.Allocator, w: weights.Weights, k: kern.Kernels, s: cuda.Stream, m: fwd.Model, kb: be.Kolibri }; +const Owned = struct { gpa: std.mem.Allocator, w: weights.Weights, k: kern.Kernels, s: cuda.Stream, m: fwd.Model, kb: be.Kolibri, room: ?Room = null, window: usize = 0, lanes: ?u32 = null }; /// Streams to allocate in `room`: as asked, else (auto) the most that fit; a fixed count past them or a round refuses. fn fit(room: u64, asked: u32, fixed: bool, plan: anytype) !usize { @@ -148,6 +148,9 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ const own = try gpa.create(Owned); errdefer gpa.destroy(own); own.gpa = gpa; + own.room = o.room; + own.window = o.context; + own.lanes = if (o.lanes_fixed) o.lanes else null; own.w = try weights.load(gpa, io, ctx.d, dir, null); errdefer own.w.deinit(); own.k = try kern.Kernels.load(ctx); @@ -182,6 +185,36 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ }; } +/// --drafter's release over the loaded model, before any stream: refused by name, nothing served on a refusal. +pub fn openDrafter(gpa: std.mem.Allocator, io: std.Io, p: *anyopaque, dir: []const u8, bits: u8) !struct { drafter: lanes.drafter.Drafter, ctx: *anyopaque, close: *const fn (*anyopaque) void, reserve: *const fn (*anyopaque, u32) anyerror!void } { + if (bits != 4 and bits != 0) return error.DrafterBitsUnsupported; // the releases are bf16: default or 0 only + const own: *Owned = @ptrCast(@alignCast(p)); + if (own.kb.lanes.count() != 0) return error.TapsAfterStreams; + const left = if (own.room) |r| r.read(r.ctx) else null; // the release's own bytes refuse before any is allocated + const d = try eagle.Drafter.open(gpa, io, &own.kb, &own.k, dir, drafterLoad(own, left)); + errdefer d.deinit(); + return .{ .drafter = d.drafter(), .ctx = d, .close = closeDrafter, .reserve = reserveDrafter }; +} + +/// What the drafter's load holds that the server's stream plan does not count (linear: every stream's slot). +fn drafterLoad(own: *const Owned, left: ?u64) eagle.Drafter.Load { + const tap_rows = @import("taps.zig").heldRows(own.m.max_rows, own.m.slotCap()); // prepare_features allocates them + if (!own.m.paged) return .{ .slots = own.m.slots, .now = own.m.slots + 1, .left = left, .tap_rows = tap_rows }; + const l = own.m.layout(); // pages: the plan pays each later stream's slot; the first's, timing slot, window here + const first = l.pages(own.window + window_rows) * l.pageBytes(); + return .{ .slots = own.lanes orelse 1, .first = first, .now = 2, .left = left, .tap_rows = tap_rows }; +} + +fn closeDrafter(p: *anyopaque) void { + const d: *eagle.Drafter = @ptrCast(@alignCast(p)); + d.deinit(); +} + +fn reserveDrafter(p: *anyopaque, streams: u32) anyerror!void { + const d: *eagle.Drafter = @ptrCast(@alignCast(p)); + try d.reserve(streams); +} + fn gib(bytes: u64) f64 { return @as(f64, @floatFromInt(bytes)) / (1 << 30); } @@ -226,7 +259,11 @@ pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { return switch (err) { error.PastContext => "the prompt and its reply exceed this server's context window: shorten it or lower max_tokens", error.NoFreeSlot => "every stream's caches are in use: retry once another request ends", - error.NoDraftHead => "Kolibri-1 on CUDA has no draft head yet: drafts come from the prompt's own text only", + error.NoDraftHead => "Kolibri-1 on CUDA drafts from the prompt's own text, or from a drafter named by --drafter", + error.BadDrafterRelease, error.AdapterMismatch => "--drafter: the folder is not a drafter release for Kolibri-1 (the log line names what is wrong)", + error.DrafterArchitectureNotServed => "--drafter: Kolibri-1 on CUDA serves the EAGLE-3 release (josch15366/Kolibri-1-EAGLE3-drafter) only", + error.DrafterBitsUnsupported => "--drafter-bits: Kolibri-1's drafter releases are bf16; serve without --drafter-bits", + error.DrafterPastMemory => "--drafter: the CUDA memory budget leaves too little for the drafter's weights, scratch and caches (the log line names the bytes): lower --parallel or --context", error.StructuresUnsupported => "structured output is not built for Kolibri-1 on CUDA yet", error.CapturedKernels => "Kolibri-1 runs on the engine's own kernels: unset TENSORFOLD_CUDA_KERNELS", error.ParallelPastRound => std.fmt.comptimePrint("--parallel: Kolibri-1 on CUDA holds at most {d} streams (a round's rows): serve --parallel {d} or fewer, or auto", .{ be.round_rows, be.round_rows }), @@ -252,7 +289,7 @@ test "the prompt cache's hooks compile against the store's vtable" { } test "every refusal of its own is worded, the rest left to the server" { - for ([_]anyerror{ error.PastContext, error.NoFreeSlot, error.NoDraftHead, error.StructuresUnsupported, error.CapturedKernels, error.ParallelPastRound, error.ParallelPastMemory, error.NoStreamFits }) |e| { + for ([_]anyerror{ error.PastContext, error.NoFreeSlot, error.NoDraftHead, error.StructuresUnsupported, error.CapturedKernels, error.ParallelPastRound, error.ParallelPastMemory, error.NoStreamFits, error.BadDrafterRelease, error.AdapterMismatch, error.DrafterArchitectureNotServed, error.DrafterBitsUnsupported, error.DrafterPastMemory }) |e| { try std.testing.expect(explain(null, e) != null); } try std.testing.expect(explain(null, error.OutOfMemory) == null); diff --git a/zig/src/families/kolibri1/rounds.zig b/zig/src/families/kolibri1/rounds.zig index 1a950a706eb..7665def7219 100644 --- a/zig/src/families/kolibri1/rounds.zig +++ b/zig/src/families/kolibri1/rounds.zig @@ -34,11 +34,15 @@ pub const Rounds = struct { r.cache.?.name = "kolibri1 rounds"; } const key: Key = .{ .rows = @intCast(st.n), .streams = @intCast(chains.len), .groups = @intCast(st.ng) }; - const fp = gc.fingerprintOf(&.{ out, m.origin, m.table, m.s.x }); - _ = try r.cache.?.run(key, o.s, fp, .{ .ctx = &body, .run = Body.run }); + _ = try r.cache.?.run(key, o.s, fingerprint(m, out), .{ .ctx = &body, .run = Body.run }); } }; +/// The addresses a round's graph holds: a drafter's tap copies (their rows, their count) among them. +pub fn fingerprint(m: *const fwd.Model, out: u64) u64 { + return gc.fingerprintOf(&.{ out, m.origin, m.table, m.s.x, m.tap_rows, m.taps.len }); +} + /// A round's launches as the eager forward makes them, on the stream the cache runs them on. const Body = struct { m: *fwd.Model, @@ -68,3 +72,16 @@ test "kolibri rounds: a plan's offsets follow its rows and streams alone, which defer gpa.free(c.flat); try std.testing.expect(c.parentsAt() != a.parentsAt()); // a third stream moves the parents: the key holds streams } + +test "kolibri rounds: naming a drafter's taps changes the fingerprint, so no round graph without tap copies replays" { + var m: fwd.Model = undefined; + m.origin = 0x1000; + m.table = 0x2000; + m.s.x = 0x3000; + m.tap_rows = 0; + m.taps = &.{}; + const before = fingerprint(&m, 0x4000); + m.tap_rows = 0x5000; + m.taps = &.{ 1, 3 }; + try std.testing.expect(fingerprint(&m, 0x4000) != before); +} diff --git a/zig/src/families/kolibri1/row_costs.zig b/zig/src/families/kolibri1/row_costs.zig new file mode 100644 index 00000000000..f42da37f5b5 --- /dev/null +++ b/zig/src/families/kolibri1/row_costs.zig @@ -0,0 +1,103 @@ +//! The target's forward ms by round rows, timed before any stream opens: the depth rule's verify prices for a drafter. +const std = @import("std"); +const lanes = @import("lanes"); +const be = @import("backend.zig"); +const fwd = @import("forward.zig"); + +const Cost = lanes.config.Cost; + +/// Round widths timed (the lane core interpolates between them and scales past the widest). +pub const widths = [_]u32{ 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64 }; + +/// Chains a round of `rows` rows takes: windows of at most be.max_window rows, as even as they split. +pub fn chainsFor(rows: u32) u32 { + return (rows + be.max_window - 1) / be.max_window; +} + +const Map = struct { + m: *fwd.Model, + x: *be.Kolibri, + slot: usize, + fn write(ctx: *anyopaque, ids: []const u32, from: usize) anyerror!void { + const p: *const Map = @ptrCast(@alignCast(ctx)); + try p.m.mapPages(p.x.s, p.slot, ids[from..], from); + } +}; + +/// Entry `i` is a round of widths[i] rows over free slots at position 0, timed once (cost_rule's timer shape). +const Timer = struct { + x: *be.Kolibri, + io: std.Io, + tokens: []const u32, + pub fn time(t: Timer, i: usize) !f64 { + const w = widths[i]; + const n = chainsFor(w); + var chains: [chainsFor(widths[widths.len - 1])]fwd.Chain = undefined; + var at: usize = 0; + for (chains[0..n], 0..) |*ch, c| { + const rows = w / n + @intFromBool(c < w % n); + ch.* = .{ .slot = c, .p0 = 0, .tokens = t.tokens[at..][0..rows] }; + at += rows; + } + var rows: [fwd.round_rows]usize = undefined; + for (&rows, 0..) |*r, k| r.* = k; + const t0 = std.Io.Clock.awake.now(t.io); + try t.x.m.forward(t.x.ops(), chains[0..n], false, rows[0..w], t.x.logits.ptr); + try t.x.taps.kept(t.x.gpa, t.x.m, t.x.s, chains[0..n], false); + try t.x.s.synchronize(); + return @as(f64, @floatFromInt(t0.durationTo(std.Io.Clock.awake.now(t.io)).toNanoseconds())) / 1e6; + } +}; + +/// Widths a round over `slots` streams can take: each stream's window at most be.max_window rows. +pub fn widthsFor(slots: usize) usize { + var n: usize = 0; + while (n < widths.len and chainsFor(widths[n]) <= slots) n += 1; + return n; +} + +/// Every width the target's slots hold, fastest run each (lanes.cost_rule), pages returned after; the count timed. +pub fn time(x: *be.Kolibri, io: std.Io, out: *[widths.len]Cost) !usize { + if (x.lanes.count() != 0) return error.TimingWithStreams; + const n = widthsFor(x.m.slots); + if (n == 0) return error.TimingSlots; + const most = chainsFor(widths[n - 1]); + var leases: [chainsFor(widths[widths.len - 1])]@import("core").kv_pool.Lease = @splat(.{}); + defer for (leases[0..most], 0..) |*l, slot| if (x.pool) |*p| { + p.finish(l); + x.m.unmapPages(slot); + }; + if (x.pool) |*p| for (leases[0..most], 0..) |*l, slot| { + try p.promise(l, 1); + var map: Map = .{ .m = x.m, .x = x, .slot = slot }; + try p.cover(l, 1, .{ .ctx = &map, .write = Map.write }); + }; + var ids: [fwd.round_rows]u32 = undefined; // spread ids, as qwen27_costs.zig times its windows + for (&ids, 0..) |*t, i| t.* = @intCast((i * 7919 + 13) % x.m.c.vocab); + const timer: Timer = .{ .x = x, .io = io, .tokens = &ids }; + for (0..5) |_| _ = try timer.time(n - 1); // the widest round first, while the GPU's clocks ramp up + var ms: [widths.len]f64 = undefined; + for (ms[0..n], 0..) |*m, i| m.* = try lanes.cost_rule.fastest(timer, i); + try lanes.cost_rule.smooth(timer, ms[0..n]); + for (out[0..n], widths[0..n], ms[0..n]) |*c, w, m| c.* = .{ .width = w, .ms = m }; + std.log.info("Kolibri round costs over {d} slot{s}: 1 row {d:.2} ms, {d} rows {d:.2}", .{ x.m.slots, if (x.m.slots == 1) "" else "s", ms[0], widths[n - 1], ms[n - 1] }); + for (x.taps.written[0..@min(most, x.taps.written.len)]) |*w| w.* = 0; // no stream wrote these rows + return n; +} + +test "a round splits into windows of at most max_window rows" { + try std.testing.expectEqual(@as(u32, 1), chainsFor(1)); + try std.testing.expectEqual(@as(u32, 1), chainsFor(16)); + try std.testing.expectEqual(@as(u32, 2), chainsFor(17)); + try std.testing.expectEqual(@as(u32, 4), chainsFor(64)); + for (widths) |w| try std.testing.expect(chainsFor(w) * be.max_window >= w); +} + +test "calibration times the widths 1, 2 and 3 streams can take, without asking four slots" { + try std.testing.expectEqual(@as(usize, 0), widthsFor(0)); + for ([_]usize{ 1, 2, 3, 4, 8 }, [_]u32{ 16, 32, 48, 64, 64 }, [_]usize{ 8, 10, 11, 12, 12 }) |slots, widest, n| { + try std.testing.expectEqual(n, widthsFor(slots)); + try std.testing.expectEqual(widest, widths[widthsFor(slots) - 1]); + try std.testing.expect(chainsFor(widths[n - 1]) <= slots); + } +} diff --git a/zig/src/families/kolibri1/taps.zig b/zig/src/families/kolibri1/taps.zig new file mode 100644 index 00000000000..b4381cc182c --- /dev/null +++ b/zig/src/families/kolibri1/taps.zig @@ -0,0 +1,263 @@ +//! Kolibri-1's tapped rows for a drafter: each forward's copies kept per stream in a ring, handed out as Features. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const fwd = @import("forward.zig"); + +/// Positions a stream's ring keeps: the last verify's rows and its prompt's last, with room to spare. +pub const keep = 256; +/// Rows a ring view hands out at most; ring rows below it are mirrored past `keep`, so every view is contiguous. +pub const mirror = 64; +/// Positions before its end a prefilling prompt's slab keeps: a one-layer drafter's window, read after token one. +pub const slab_rows = 2048; +/// Layers a drafter may tap. +pub const most = 8; + +/// A copy of `rows` rows: forward row `src` on into ring row `dst` on. +pub const Piece = struct { src: usize, dst: usize, rows: usize }; + +/// Positions [p0, p0 + n), n <= keep, into ring rows (p % keep), each row below `mirror` again at keep + row. +pub fn pieces(p0: u64, n: usize, out: *[4]Piece) []const Piece { + std.debug.assert(n <= keep); + var k: usize = 0; + const r0: usize = @intCast(p0 % keep); + const first = @min(n, keep - r0); + for ([_]Piece{ .{ .src = 0, .dst = r0, .rows = first }, .{ .src = first, .dst = 0, .rows = n - first } }) |seg| { + if (seg.rows == 0) continue; + out[k] = seg; + k += 1; + if (seg.dst < mirror) { + out[k] = .{ .src = seg.src, .dst = keep + seg.dst, .rows = @min(seg.rows, mirror - seg.dst) }; + k += 1; + } + } + return out[0..k]; +} + +/// Rows, each the tapped layers' width, `prepare` allocates: a forward's `max_rows` and a ring for each of `slots`. +pub fn heldRows(max_rows: usize, slots: usize) usize { + return max_rows + slots * (keep + mirror) + slab_rows; +} + +pub const Taps = struct { + ids: [most]u32 = undefined, + n: usize = 0, // 0: no drafter taps; forwards copy nothing + rows: ?cuda.DeviceBuffer = null, // the forward's tap_rows + ring: ?cuda.DeviceBuffer = null, // [slots, keep + mirror, row] + slots: usize = 0, + written: []u64 = &.{}, // a slot's ring holds positions [written - keep, written) + prompt: ?fwd.Chain = null, // the last forward was this stream's prompt chunk: its rows are in tap_rows whole + slab: ?cuda.DeviceBuffer = null, // [slab_rows, row]: one prefilling stream's prompt end, linear from `slab_from` + slab_slot: ?usize = null, // the stream holding it, until its first round or its release + slab_from: u64 = 0, + slab_to: u64 = 0, // positions [slab_from, slab_to) written + + pub fn deinit(t: *Taps, gpa: std.mem.Allocator) void { + if (t.rows) |*b| b.free(); + if (t.ring) |*b| b.free(); + if (t.slab) |*b| b.free(); + gpa.free(t.written); + t.* = .{}; + } + + pub fn rowBytes(t: *const Taps, m: *const fwd.Model) usize { + return t.n * m.c.hidden * 2; + } + + /// The drafter's layers (0-based, rising, normed outputs): its rows and every slot's ring, before the pool plan. + pub fn prepare(t: *Taps, gpa: std.mem.Allocator, m: *fwd.Model, taps: []const u32) !void { + if (t.n != 0) return error.TapsTwice; + if (taps.len == 0 or taps.len > most) return error.TooManyTaps; + for (taps, 0..) |id, i| if (id >= m.c.layers or (i > 0 and id <= taps[i - 1])) return error.BadTap; + @memcpy(t.ids[0..taps.len], taps); + t.n = taps.len; + errdefer t.n = 0; + t.rows = try cuda.DeviceBuffer.alloc(m.d, m.max_rows * t.rowBytes(m)); + errdefer if (t.rows) |*b| { + b.free(); + t.rows = null; + }; + t.slab = try cuda.DeviceBuffer.alloc(m.d, slab_rows * t.rowBytes(m)); + errdefer if (t.slab) |*b| { + b.free(); + t.slab = null; + }; + try t.reserve(gpa, m, m.slotCap()); + m.taps = t.ids[0..t.n]; + m.tap_rows = t.rows.?.ptr; + } + + /// A ring for each of `slots` streams (kept rings are dropped: no stream holds one while slots grow). + fn reserve(t: *Taps, gpa: std.mem.Allocator, m: *const fwd.Model, slots: usize) !void { + if (slots <= t.slots) return; + if (t.ring) |*b| b.free(); + t.ring = null; + t.slots = 0; + gpa.free(t.written); + t.written = &.{}; + var ring = try cuda.DeviceBuffer.alloc(m.d, slots * (keep + mirror) * t.rowBytes(m)); + errdefer ring.free(); // published only once the host slice is made too + const written = try gpa.alloc(u64, slots); + @memset(written, 0); + t.ring = ring; + t.written = written; + t.slots = slots; + } + + /// After a forward over `chains` (rows back to back in tap_rows): each chain's last rows into its slot's ring. + pub fn kept(t: *Taps, gpa: std.mem.Allocator, m: *const fwd.Model, s: cuda.Stream, chains: []const fwd.Chain, prompt: bool) !void { + if (t.n == 0) return; + try t.reserve(gpa, m, m.slotCap()); + const row = t.rowBytes(m); + var at: usize = 0; + for (chains) |ch| { + const n = @min(ch.tokens.len, keep); + const skip = ch.tokens.len - n; + var buf: [4]Piece = undefined; + for (pieces(ch.p0 + skip, n, &buf)) |p| { + const dst = t.ring.?.ptr + (ch.slot * (keep + mirror) + p.dst) * row; + try m.d.check(m.d.api.cuMemcpyDtoDAsync_v2(dst, m.tap_rows + (at + skip + p.src) * row, p.rows * row, s.handle), "cuMemcpyDtoDAsync"); + } + t.written[ch.slot] = ch.p0 + ch.tokens.len; + at += ch.tokens.len; + if (!prompt and t.slab_slot == ch.slot) t.slab_slot = null; // its first round: the first draft read it + } + t.prompt = if (prompt) chains[0] else null; + } + + /// A prompt chunk of a `len`-token prompt: kept as `kept`, and its rows past `len - slab_rows` into the slab. + pub fn keptPrompt(t: *Taps, gpa: std.mem.Allocator, m: *const fwd.Model, s: cuda.Stream, ch: fwd.Chain, len: u64) !void { + try t.kept(gpa, m, s, &.{ch}, true); + const slab = t.slab orelse return; + if (t.slab_slot) |held| if (held != ch.slot) return; // another prompt's: this one absorbs as it goes + const end = ch.p0 + ch.tokens.len; + if (t.slab_slot == null) { + t.slab_slot = ch.slot; + t.slab_from = @max(len -| slab_rows, ch.p0); + t.slab_to = t.slab_from; + } + const lo = @max(t.slab_from, ch.p0); + if (end <= lo) return; // rows before the slab's: never read + if (lo != t.slab_to) return error.SlabGap; + const row = t.rowBytes(m); + const dst = slab.ptr + @as(usize, @intCast(lo - t.slab_from)) * row; + try m.d.check(m.d.api.cuMemcpyDtoDAsync_v2(dst, m.tap_rows + @as(usize, @intCast(lo - ch.p0)) * row, @as(usize, @intCast(end - lo)) * row, s.handle), "cuMemcpyDtoDAsync"); + t.slab_to = end; + } + + /// The first prompt position `slot`'s slab holds for its first draft, if it holds the slab. + pub fn slabFrom(t: *const Taps, slot: usize) ?u64 { + return if (t.slab_slot == slot) t.slab_from else null; + } + + /// A stream released: its slab, if it held it, free for the next prompt. + pub fn drop(t: *Taps, slot: usize) void { + if (t.slab_slot == slot) t.slab_slot = null; + } + + /// A keep rolled `slot` back to `len` positions: rows past it were rejected drafts', no longer handed out. + pub fn keepTo(t: *Taps, slot: usize, len: u64) void { + if (slot < t.slots) t.written[slot] = @min(t.written[slot], len); + } + + /// Rows [start, start + count) of `slot`'s taps: the last prompt chunk's whole, else up to `mirror` from the ring. + pub fn view(t: *const Taps, m: *const fwd.Model, slot: usize, start: u64, count: u32) !lanes.backend.Features { + if (t.n == 0) return error.NoTaps; + const row = t.rowBytes(m); + const f: lanes.backend.Features = .{ .buffer = 0, .rows = count, .row_bytes = @intCast(row), .space = .device, .dtype = .bf16 }; + if (t.slab_slot == slot and start >= t.slab_from and start + count <= t.slab_to) { + var v = f; + v.buffer = t.slab.?.ptr + @as(usize, @intCast(start - t.slab_from)) * row; + return v; + } + if (t.prompt) |p| if (p.slot == slot and start >= p.p0 and start + count <= p.p0 + p.tokens.len) { + var v = f; + v.buffer = m.tap_rows + (start - p.p0) * row; + return v; + }; + if (slot >= t.slots or count > mirror or start + count > t.written[slot] or start < t.written[slot] -| keep) return error.RowsNotHeld; + var v = f; + v.buffer = t.ring.?.ptr + (slot * (keep + mirror) + @as(usize, @intCast(start % keep))) * row; + return v; + } +}; + +test "a chunk's rows land at their ring rows, rows below the mirror twice, and every view up to it is contiguous" { + var buf: [4]Piece = undefined; + try std.testing.expectEqualSlices(Piece, &.{ .{ .src = 0, .dst = 10, .rows = 5 }, .{ .src = 0, .dst = keep + 10, .rows = 5 } }, pieces(10, 5, &buf)); + try std.testing.expectEqualSlices(Piece, &.{.{ .src = 0, .dst = 100, .rows = 5 }}, pieces(keep + 100, 5, &buf)); + try std.testing.expectEqualSlices(Piece, &.{ .{ .src = 0, .dst = 250, .rows = 6 }, .{ .src = 6, .dst = 0, .rows = 4 }, .{ .src = 6, .dst = keep, .rows = 4 } }, pieces(250, 10, &buf)); + // a whole lap: positions 300..555 -> rows 44..255 then 0..43; rows 44..63 and 0..43 mirrored + const lap = pieces(300, keep, &buf); + try std.testing.expectEqual(@as(usize, 4), lap.len); + try std.testing.expectEqualSlices(Piece, &.{ .{ .src = 0, .dst = 44, .rows = 212 }, .{ .src = 0, .dst = keep + 44, .rows = 20 }, .{ .src = 212, .dst = 0, .rows = 44 }, .{ .src = 212, .dst = keep, .rows = 44 } }, lap); + // the ring as positions: every view of up to `mirror` rows over the last `keep` reads its positions in order + var ring: [keep + mirror]u64 = @splat(std.math.maxInt(u64)); + var p0: u64 = 0; + for ([_]usize{ 37, 256, 1, 17, 200, 3 }) |n| { + for (pieces(p0, n, &buf)) |p| for (0..p.rows) |i| { + ring[p.dst + i] = p0 + p.src + i; + }; + p0 += n; + var start = p0 -| keep; + while (start < p0) : (start += 1) { + const count = @min(mirror, p0 - start); + const r: usize = @intCast(start % keep); + for (0..count) |i| try std.testing.expectEqual(start + i, ring[r + i]); + } + } +} + +const Fake = struct { // a driver that counts live device allocations + var live: usize = 0; + var next: u64 = 0x10000; + fn alloc(out: *u64, len: usize) callconv(.c) c_int { + out.* = next; + next += len + 256; + live += 1; + return 0; + } + fn free(_: u64) callconv(.c) c_int { + live -= 1; + return 0; + } +}; + +test "prepare: a failed host allocation leaves no device allocation behind, the new ring included" { + var d: cuda.Driver = .{ .lib = undefined, .api = undefined }; + d.api.cuMemAlloc_v2 = Fake.alloc; + d.api.cuMemFree_v2 = Fake.free; + var m: fwd.Model = undefined; + m.d = &d; + m.c.layers = 4; + m.c.hidden = 8; + m.max_rows = 16; + m.paged = false; + m.slots = 2; + m.taps = &.{}; + m.tap_rows = 0; + var fail: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); + var t: Taps = .{}; + try std.testing.expectError(error.OutOfMemory, t.prepare(fail.allocator(), &m, &.{ 1, 3 })); + try std.testing.expectEqual(@as(usize, 0), Fake.live); + try std.testing.expect(t.ring == null and t.rows == null and t.slots == 0 and t.n == 0); + try t.prepare(std.testing.allocator, &m, &.{ 1, 3 }); // the same call with room: rows, slab and ring made + try std.testing.expectEqual(@as(usize, 3), Fake.live); + t.deinit(std.testing.allocator); + try std.testing.expectEqual(@as(usize, 0), Fake.live); +} + +test "keepTo: after a verify of four rows keeps two, the rejected rows are not handed out" { + var t: Taps = .{ .n = 1, .slots = 1 }; + var written = [_]u64{104}; // a verify wrote positions 100..103 + t.written = &written; + t.ring = .{ .d = undefined, .ptr = 0x10000, .len = 0, .borrowed = true }; + var m: fwd.Model = undefined; + m.c.hidden = 8; + _ = try t.view(&m, 0, 100, 4); + t.keepTo(0, 102); + _ = try t.view(&m, 0, 100, 2); + try std.testing.expectError(error.RowsNotHeld, t.view(&m, 0, 100, 3)); + t.keepTo(0, 110); // a keep never extends what the ring holds + try std.testing.expectEqual(@as(u64, 102), written[0]); +} diff --git a/zig/src/native/cuda_drafted.zig b/zig/src/native/cuda_drafted.zig index 4919af89da5..7df2e3e4ad0 100644 --- a/zig/src/native/cuda_drafted.zig +++ b/zig/src/native/cuda_drafted.zig @@ -19,7 +19,10 @@ pub const Served = struct { /// The family's and the drafter's per-stream buffers for `streams`, once the server knows the count. pub fn reserve(s: *Served, streams: u32) !void { if (s.family) |f| try f.reserve(f.ctx, streams); - if (s.held) |h| try h.reserve(h.ctx, streams); + if (s.held) |h| { + try h.reserve(h.ctx, streams); + s.facts = h.drafted.facts(s.facts); // a drafter that times at reserve: its step, hold pass and round costs + } } pub fn calibrate(s: *Served, gpa: Allocator, cfg: *lanes.Config) !void { @@ -154,3 +157,47 @@ test "--mtp-drafts 0 reaches drafter selection so an MTP refusal does not suppre try std.testing.expect(called); try std.testing.expect(served.held == null); } + +test "--drafter: the served facts carry what the drafter timed at reserve, not the untimed facts it opened with" { + const Timed = struct { + timed: bool = false, + const holds = [_]lanes.hold_price.HoldCost{.{ .streams = 1, .depth = 3, .ms = 2 }}; + const costs = [_]lanes.config.Cost{ .{ .width = 1, .ms = 12 }, .{ .width = 8, .ms = 20 } }; + fn of(p: *anyopaque) *@This() { + return @ptrCast(@alignCast(p)); + } + fn facts(p: *anyopaque) lanes.drafter.Facts { + if (!of(p).timed) return .{ .depth = 3, .step_ms = 0 }; + return .{ .depth = 3, .step_ms = 1.5, .hold_costs = &holds, .window_costs = &costs, .lane_costs = &costs }; + } + fn reserve(p: *anyopaque, _: u32) anyerror!void { + of(p).timed = true; + } + fn close(_: *anyopaque) void {} + fn taps(_: *anyopaque) []const u32 { + return &.{}; + } + fn open(_: *anyopaque, _: *lanes.Stream) anyerror!void {} + fn absorb(_: *anyopaque, _: []const lanes.drafter.Absorb) anyerror!void {} + fn hold(_: *anyopaque, _: []const lanes.drafter.Hold) anyerror!void {} + fn held(_: *anyopaque, _: []const *lanes.Stream, _: []const []u32) anyerror!void {} + fn release(_: *anyopaque, _: *lanes.Stream) void {} + }; + const gpa = std.testing.allocator; + var d: Timed = .{}; + const drafter: lanes.drafter.Drafter = .{ .ptr = &d, .vtable = &.{ .taps = Timed.taps, .facts = Timed.facts, .open = Timed.open, .absorb = Timed.absorb, .hold = Timed.hold, .held = Timed.held, .release = Timed.release } }; + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var h: Held = .{ .drafted = try lanes.drafted.Drafted.init(gpa, target.backend(), drafter), .ctx = &d, .close = Timed.close, .reserve = Timed.reserve }; + defer h.drafted.deinit(); + const base: lanes.Model = .{ .exact_width = 8 }; + var s: Served = .{ .backend = h.drafted.backend(), .facts = h.drafted.facts(base), .stream_bytes = 0, .held = &h }; + try std.testing.expectEqual(@as(f64, 0), s.facts.mtp_step_ms); // opened untimed: no prices yet + try std.testing.expectEqual(@as(usize, 0), s.facts.hold_costs.len); + try s.reserve(8); + try std.testing.expectEqual(@as(f64, 1.5), s.facts.mtp_step_ms); + try std.testing.expectEqual(@as(usize, 1), s.facts.hold_costs.len); + try std.testing.expectEqual(@as(usize, 2), s.facts.window_costs.len); + try std.testing.expect(s.facts.limit_shared_drafts == base.limit_shared_drafts); // the rest as the drafter set it + try std.testing.expectEqual(@as(u32, 3), s.facts.drafts); +} diff --git a/zig/tests/cuda/contract_moe.zig b/zig/tests/cuda/contract_moe.zig index bc86c12add2..1992eb67980 100644 --- a/zig/tests/cuda/contract_moe.zig +++ b/zig/tests/cuda/contract_moe.zig @@ -452,9 +452,15 @@ fn laneChain(s: c.Shape) usize { } pub const dense_tiles = [_]usize{ 1, 4, 16, 32 }; +/// dense_tiles' entries and tf_dense_rows_tiled's (64 rows a block, past dense_rows.tiled_from rows). +pub const dense_entries = dense_tiles.len + 1; /// Shape: rows, outputs (n) and k; each entry launches its own row tile (the wrapper picks it by row count). pub fn denseSpec(i: usize) c.Spec { + if (i == dense_tiles.len) { // the prompt rows' launch: Kolibri's router, the drafter's fuse and fc at prompt rows + const served = [_]c.Shape{ .{ .rows = 257, .n = 384, .k = 2560 }, .{ .rows = 256, .n = 2560, .k = 7680 }, .{ .rows = 65, .n = 4103, .k = 2560 } }; + return .{ .name = "cuda dense rows tf_dense_rows_tiled", .accum = .f32, .depth = laneChain, .out = .f32, .replaces = "tf_dense_rows_32 at the same rows, bit for bit", .tiles = .{ .{ .size = 64 }, .{ .size = 8 }, .{ .size = 256, .step = 8, .min = 8 } }, .served = &served }; + } const names = [_][]const u8{ "cuda dense rows tf_dense_rows_1", "cuda dense rows tf_dense_rows_4", "cuda dense rows tf_dense_rows_16", "cuda dense rows tf_dense_rows_32" }; // Kolibri's router (384 x 2,560), an output head's odd 4,103 columns, 257 x 7,168; rows as the wrapper sends them const m = [_][2]usize{ .{ 1, 1 }, .{ 4, 3 }, .{ 16, 9 }, .{ 32, 40 } }; @@ -473,9 +479,11 @@ pub const DenseRows = struct { g: *const cuda.dense_rows.DenseRows, d: ?Dense = null, dev: [3]u64 = @splat(0), + base: std.ArrayList(u8) = .empty, pub fn deinit(self: *DenseRows) void { if (self.d) |d| d.deinit(); + self.base.deinit(self.rig.gpu.gpa); self.rig.deinit(); } @@ -512,22 +520,39 @@ pub const DenseRows = struct { return true; } - /// The wrapper's launch, at this entry's row tile whatever the row count. - pub fn run(self: *DenseRows) !void { + /// One launch at `tile`'s row tile (64 rows: the tiled entry) writing `out`, then a sync. + fn launchTile(self: *DenseRows, tile: usize, out: u64) !void { const sh = self.d.?.shape; var a: cuda.Args = .{}; a.add(self.dev[0]); a.add(@as(i64, @intCast(sh.k))); a.add(self.dev[1]); - a.add(self.dev[2]); + a.add(out); a.add(@as(i64, @intCast(sh.n))); for ([_]usize{ sh.rows, sh.n, sh.k }) |v| a.add(@as(i32, @intCast(v))); - const rt = dense_tiles[self.tile]; + const rt = if (tile < dense_tiles.len) dense_tiles[tile] else 64; const grid: cuda.Dim3 = .{ .x = @intCast((sh.n + 7) / 8), .y = @intCast((sh.rows + rt - 1) / rt), .z = 1 }; - try cuda.launch.launch(self.g.fns[self.tile], .{ .grid = grid, .block = .{ .x = 256 } }, self.rig.s, &a); + const f = if (tile < dense_tiles.len) self.g.fns[tile] else self.g.tiled; + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = 256 } }, self.rig.s, &a); try self.rig.s.synchronize(); } + /// The wrapper's launch, at this entry's row tile whatever the row count. + pub fn run(self: *DenseRows) !void { + try self.launchTile(self.tile, self.dev[2]); + } + + /// The tiled entry's baseline: tf_dense_rows_32 on the same inputs (its bytes, which the tiled launch must give). + pub fn replaced(self: *DenseRows) ![]const u8 { + const n = self.count(); + var tmp = try cuda.DeviceBuffer.alloc(self.rig.gpu.d, n * 4); + defer tmp.free(); + try self.launchTile(dense_tiles.len - 1, tmp.ptr); + try self.base.resize(self.rig.gpu.gpa, n * 4); + try tmp.download(0, self.base.items); + return self.base.items; + } + pub fn count(self: *DenseRows) usize { return self.d.?.outputs(); } diff --git a/zig/tests/cuda/contract_tests.zig b/zig/tests/cuda/contract_tests.zig index d3f4a24fe5f..0c61aa2d054 100644 --- a/zig/tests/cuda/contract_tests.zig +++ b/zig/tests/cuda/contract_tests.zig @@ -443,7 +443,7 @@ fn registered(gpu: check.Gpu, opt: @import("contract_shard.zig").Options, t0: *i for (&combines) |*x| try kernels.append(a, x.kernel()); var dense_fns = try cuda.dense_rows.DenseRows.load(gpu.d); defer dense_fns.unload(); - var denses: [moe_k.dense_tiles.len]moe_k.DenseRows = undefined; + var denses: [moe_k.dense_entries]moe_k.DenseRows = undefined; for (&denses, 0..) |*x, i| x.* = .{ .rig = .{ .gpu = gpu, .s = s }, .tile = i, .g = &dense_fns }; defer for (&denses) |*x| x.deinit(); for (&denses) |*x| try kernels.append(a, x.kernel()); diff --git a/zig/tests/cuda/kolibri_drafter_tests.zig b/zig/tests/cuda/kolibri_drafter_tests.zig new file mode 100644 index 00000000000..957f1cab50d --- /dev/null +++ b/zig/tests/cuda/kolibri_drafter_tests.zig @@ -0,0 +1,142 @@ +//! Kolibri-1's EAGLE-3 drafter on a prompt-cache hit: the pass re-runs the kept rows it reads, its state as cold. +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const kolibri1 = @import("kolibri1"); +const check = @import("check.zig"); +const layer_tests = @import("kolibri_layer_tests.zig"); +const Gpu = check.Gpu; + +const Rig = layer_tests.Rig; +const count = 64; // reply tokens + +/// A finished stream's reply and the drafts it landed. +const Ran = struct { reply: []u32, accepted: u64 }; + +const Kit = struct { + gpu: Gpu, + kb: *kolibri1.backend.Kolibri, + d: *kolibri1.drafter.Drafter, + x: *lanes.drafted.Drafted, + + /// One drafted stream to its end (a lone stream opens drafter slot 0, the lowest free). + fn run(k: Kit, s: *lanes.Stream) !Ran { + const gpa = k.gpu.gpa; + var cfg = try lanes.Config.init(gpa, k.x.facts(k.kb.facts()), kolibri1.backend.max_window, kolibri1.backend.max_window - 1); + defer cfg.deinit(gpa); + var clock: lanes.fake.FixedClock = .{}; + var engine = lanes.Engine.init(gpa, &cfg, k.x.backend(), clock.clock()); + defer engine.deinit(); + try engine.addStream(s); + while (engine.activeCount() > 0) try engine.step(); + return .{ .reply = try gpa.dupe(u32, s.emitted()), .accepted = s.accepted }; + } + + /// Slot 0's last output row, then its K and V rows of positions [lo, hi) (each at its place in the ring). + fn slot(k: Kit, lo: usize, hi: usize) ![]u8 { + try k.kb.s.synchronize(); + const e = &k.d.e; + const att = e.dims.heads * e.dims.head_dim * 2; + const head = e.dims.hidden * 2; + const bytes = try k.gpu.gpa.alloc(u8, head + 2 * (hi - lo) * att); + errdefer k.gpu.gpa.free(bytes); + try cuda.memory.download(k.gpu.d, e.out, bytes[0..head]); + var at_: usize = head; + for ([_]u64{ e.kc, e.vc }) |cache| for (lo..hi) |p| { + try cuda.memory.download(k.gpu.d, cache + (p % e.dims.ring()) * att, bytes[at_..][0..att]); + at_ += att; + }; + return bytes; + } +}; + +fn hash(b: []const u8) u64 { + return std.hash.Wyhash.hash(0, b); +} + +/// The state kept at `at` by a plain stream of `p`, through the target's own path. +fn keep(gpa: std.mem.Allocator, kb: *kolibri1.backend.Kolibri, p: []const u32, at: u32) !*kolibri1.snap.Saved { + const Keep = struct { + kb: *kolibri1.backend.Kolibri, + saved: ?*kolibri1.snap.Saved = null, + fn hook(ptr: *anyopaque, s: *lanes.Stream, mark: u32) void { + const self: *@This() = @ptrCast(@alignCast(ptr)); + self.saved = self.kb.saveState(s, mark) catch null; + } + }; + var kept: Keep = .{ .kb = kb }; + var marks = [_]u32{at}; + var ks = try lanes.Stream.init(gpa, .{ .id = "keep", .prompt = p[0..@min(p.len, at + 100)], .max_new = 1, .drafts = false, .reuse = .{ .marks = &marks, .hook = .{ .ptr = &kept, .at = Keep.hook } } }); + defer ks.deinit(gpa); + try kb.backend().prefill(&ks); + kb.backend().release(&ks); + return kept.saved orelse error.NothingKept; +} + +/// `p` drafted to its end from `saved` at `at` (null: cold) after another prompt filled slot 0: its slot from `lo`. +fn resumedRun(k: Kit, ids: []const u32, p: []const u32, saved: ?*kolibri1.snap.Saved, at: u32, sampling: ?lanes.Sampling, lo: usize) !struct { ran: Ran, slot: []u8, rebuilt: ?u32 } { + const gpa = k.gpu.gpa; + var fs = try lanes.Stream.init(gpa, .{ .id = "fill", .prompt = ids[12000..][0..p.len], .max_new = 8, .drafts = true }); + defer fs.deinit(gpa); + const filled = try k.run(&fs); + gpa.free(filled.reply); + var reuse: lanes.stream.Reuse = .{}; + if (saved) |v| reuse = .{ .saved = v, .at = at }; + var s = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = p, .max_new = count, .sampling = sampling, .drafts = true, .reuse = reuse }); + defer s.deinit(gpa); + const ran = try k.run(&s); + errdefer gpa.free(ran.reply); + if (saved != null and (s.cached != at or s.reuse_failed)) return error.NotResumed; + return .{ .ran = ran, .slot = try k.slot(lo, p.len + count - 1), .rebuilt = s.rebuilt }; +} + +/// Restored before the reach or inside it: state, drafts and reply == a cold prefill's, greedy and seeded. +pub fn resumed(gpu: Gpu, model: []const u8, dir: []const u8, ids_file: []const u8, count_text: []const u8) !void { + const gpa = gpu.gpa; + _ = count_text; + const ids = try layer_tests.readIds(gpu, ids_file); + defer gpa.free(ids); + if (ids.len < 20000) return error.TooFewIds; + var rig: Rig = undefined; + try rig.init(gpu, model, null, 8192, 4, kolibri1.forward.prompt_rows); + defer rig.deinit(); + var kb = try kolibri1.backend.Kolibri.init(gpa, gpu.d, &rig.m, &rig.k, rig.s); + defer kb.deinit(); + const tap_rows = kolibri1.taps.heldRows(rig.m.max_rows, kolibri1.paging.slotCap(&rig.m)); + const d = try kolibri1.drafter.Drafter.open(gpa, gpu.io, &kb, &rig.k, dir, .{ .slots = 4, .now = 2, .left = null, .tap_rows = tap_rows }); + defer d.deinit(); + var x = try lanes.drafted.Drafted.init(gpa, kb.backend(), d.drafter()); // the target's tap rows, as the server + defer x.deinit(); + try d.reserve(4); // after them: its absorb timing reads the tap rows + const k: Kit = .{ .gpu = gpu, .kb = &kb, .d = d, .x = &x }; + const reach = d.e.dims.reach(); + var bad: usize = 0; + const Case = struct { name: []const u8, len: usize, at: u32, rebuilt: ?u32 }; + const cases = [_]Case{ + .{ .name = "before the reach", .len = 3001 + reach + 60, .at = 3001, .rebuilt = null }, + .{ .name = "inside the reach", .len = 4001, .at = 3001, .rebuilt = null }, // fillers + .{ .name = "a short prompt", .len = 131, .at = 45, .rebuilt = 0 }, // the served benchmark's shape + }; + for (cases) |c| { + const p = ids[0..c.len]; + const saved = try keep(gpa, &kb, p, c.at); + defer kb.dropState(saved); + const lo = (p.len - 1) -| reach; + for ([_]?lanes.Sampling{ null, .{ .seed = 7, .temperature = 0.8, .top_k = 20, .top_p = 0.95 } }) |sampling| { + const cold = try resumedRun(k, ids, p, null, 0, sampling, lo); + defer gpa.free(cold.ran.reply); + defer gpa.free(cold.slot); + const warm = try resumedRun(k, ids, p, saved, c.at, sampling, lo); + defer gpa.free(warm.ran.reply); + defer gpa.free(warm.slot); + const reply = std.mem.eql(u32, cold.ran.reply, warm.ran.reply); + const fills = lo > 0 and c.at > lo; // the fallback: fillers, so the reply alone (a filler can be accepted) + const same = if (fills) reply else std.mem.eql(u8, cold.slot, warm.slot) and cold.ran.accepted == warm.ran.accepted and reply; + const re = std.meta.eql(warm.rebuilt, c.rebuilt); + std.debug.print("RESULT kolibri1 drafter {s} ({s}): cold slot {x}, {d} drafts landed; resumed slot {x}, {d} drafts landed, rebuilt from {?d}; equal: {}\n", .{ c.name, if (sampling == null) "greedy" else "seeded", hash(cold.slot), cold.ran.accepted, hash(warm.slot), warm.ran.accepted, warm.rebuilt, same and re }); + if (!same or !re or cold.ran.accepted == 0) bad += 1; + } + } + try check.expect(bad == 0, "kolibri1 drafter resume: {d} checks failed", .{bad}); + check.pass("kolibri1 drafter resume: rebuilt == cold (state, drafts, reply; greedy and seeded); inside the reach fillers, reply == cold", .{}); +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 1300cb9335a..d4f3d41b803 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -441,6 +441,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "kolibri-reference")) return kolibri_layer_tests.reference(gpu, try arg(rest, 0), try arg(rest, 1)); 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, "kolibri-drafter-resume")) return @import("kolibri_drafter_tests.zig").resumed(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); 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); diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index 685d31d49a1..9583cc74fb0 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -213,6 +213,7 @@ pub const usage = \\ kolibri-reference MODEL IDS Kolibri-1's layer 0 and head against float64 from the checkpoint (prompt and decode rows) \\ kolibri-layers MODEL IDS Kolibri-1's window edge (513 keys) and its fifth layer's full reach, on the checkpoint \\ kolibri-full MODEL IDS N Kolibri-1: eager rows, steps, drafted, sampled, shared rounds, cuts and kept states alike + \\ kolibri-drafter-resume MODEL DRAFTER IDS N Kolibri-1's EAGLE-3 drafter resumed from a kept state reads its own rows only \\ kolibri-pages MODEL TEXT N Kolibri-1: full layers in pool pages == linear caches, replies and logits \\ kolibri-greedy MODEL PROMPTS N OUT Kolibri-1 greedy from each prompt (JSON id lists): ids and top-2 margins \\ kolibri-logits MODEL IDS OUT [PROMPTS] Kolibri-1's teacher-forced fp32 logits of 2,048 prompt rows; each prompt's last diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 023f1931d10..d9032531281 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -107,7 +107,7 @@ zig/src/cuda/nvfp4.zig 0556e93c12e4eb21db45d0d9d9ee7d4c1c4ab6a32a359b67edfc0b4b7 zig/src/cuda/qlinear.zig c2c4d14479ecb9e4f578df8f1e56a7cbb84a93b9fb30962fa8cfdc4c00640b89 raw commits da01294e0, 7f6f940eb, 4cec0eba1, c360607f0, ba1a9a2bb, b631fe069, 0a2a1c681, aca5a88e2, c12503be2, 7b17d0eb7, d7e44b555, 59be20e24, d40bc9e8b, f1f7f9abd, 3915bceaf, e8eabc82c; series patches 14-runtime-foundation.patch, 25-mimo-02.patch; MiMo-only aliases omitted from this candidate; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; #3131 zig/src/cuda/qmmf.zig 2d1ab1d6c2cf636a20427b93839a902df01cf54962f77bc9ff96b49040fb3d76 raw main ec76abd45, c3acc3466, fbf8d960d (BF16 prompt tile, Flash Next only), 6a1feb26e (TF_QMMF_HALF_BELOW refused by name); dependent decode launches: weights load before griddepcontrol.wait (TF_QMMF_WFIRST), Lane.pdl; TF_FLASHNEXT_FUSED_SPLIT (fuse_split_n, default 0: main's kernels); threshold owned by Flash Next's lane, other families keep 0; #4533 optional FP4/FP8/FP8G half tiles, default off; #3131; #5052 factors slice-partial byte sizing into requiredPartBytes without changing its plan zig/src/cuda/rank_scatter.zig 303fd707713af732dd1d31c6a940dd4eeed44e9b26fe202919da5925654fc212 raw -zig/src/cuda/root.zig b0f15d5624ce83fe0c98b4b35a9e496f79ff42f8b9e4656afdd57bf0681facc9 raw main 42735f94f0 (#2335: cuda.mla exported), (cuda.affine_experts exported for Hy4-flash); main 42735f94f0 (#2335: cuda.mla exported); #3518 (exports roce_pair_rule; the test block imports roce_layout, roce_pairs and roce_pair_rule); #4493 (opt-in paired prompt experts, 128-row items); #4533 exports qmmf_half; #5051: cuda.topk_rows and cuda.sparse_index exported; slice 1 of #4846: cuda.sparse_attention exported; main 32c4e3d8f (#3368: the fn_int4 image registered, the int4 module exported and its tests listed); #5442: cuda.tfq4 exported; TFQ5+TP: cuda.tfq3_tp and cuda.tfq5 exported +zig/src/cuda/root.zig 8fbf6e22afb596bbe5b2d7854eb008830315a5be8646ef9b17d503cb1940e20d raw main 42735f94f0 (#2335: cuda.mla exported), (cuda.affine_experts exported for Hy4-flash); main 42735f94f0 (#2335: cuda.mla exported); #3518 (exports roce_pair_rule; the test block imports roce_layout, roce_pairs and roce_pair_rule); #4493 (opt-in paired prompt experts, 128-row items); #4533 exports qmmf_half; #5051: cuda.topk_rows and cuda.sparse_index exported; slice 1 of #4846: cuda.sparse_attention exported; main 32c4e3d8f (#3368: the fn_int4 image registered, the int4 module exported and its tests listed); #5442: cuda.tfq4 exported; TFQ5+TP: cuda.tfq3_tp and cuda.tfq5 exported zig/src/cuda/route_rows.zig e23257dea1f244ebba4399d7bc0730953f75eebbd7789819d5785e88a8907206 raw zig/src/cuda/sample.zig 9e3a31bd0480284ff069148b2d3c92f1e2ba24f16c18362dae9de48ec7fc65fe raw series patches 02-cuda-rounds.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main 37b0776ce (#2680: adds ruleFor and rule, which reach the same core rule, byte-equal over a 25,480-setting grid; existing code unchanged), #3124 zig/src/cuda/segments.zig 8d029a27a7b2a77916c91c9e650cee07c25aec317efacfdb3f8f8967744899a9 raw