Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
b923e55
Windows: a platform layer and host builds that pass
BobClawblaw Oct 12, 2026
60c6892
Windows: CUDA kernels, the native server and the GPU suites on sm_89
BobClawblaw Oct 12, 2026
9c36621
Windows: pull into the hub cache, HOME, and the whole test step
BobClawblaw Oct 12, 2026
2f626e1
Windows: build notes, strip before install, formatting
BobClawblaw Oct 12, 2026
ec0ddc5
Default port 8888
BobClawblaw Oct 12, 2026
3c57c14
qwen3_5: serve Qwen3.5-2B on CUDA
BobClawblaw Oct 13, 2026
84c58d3
qwen3_5: serve Qwen3.8-27B on CUDA, one arena for a model's device me…
BobClawblaw Oct 14, 2026
a087521
qwen3_5: replay each decode shape as a CUDA graph
BobClawblaw Oct 14, 2026
c3861d3
qwen3_5: DFlash2 drafts for Qwen3.8-27B on CUDA
BobClawblaw Oct 14, 2026
9b8d4af
qwen3_5: tree drafts on CUDA, the kept path replayed from a log
BobClawblaw Oct 14, 2026
b5b5c4b
docs: the Qwen hybrids on CUDA in the Windows page and the README
BobClawblaw Oct 14, 2026
cf2cdf1
qwen3_5, platform: comments on one line
BobClawblaw Oct 14, 2026
221c2b5
Windows: checkpoint reads skip the page cache
BobClawblaw Oct 14, 2026
522d17d
Windows: the signal handler type allows address 1, for aarch64
BobClawblaw Oct 14, 2026
d1ea47f
docs: Windows as a target in the README and the Windows page
BobClawblaw Oct 14, 2026
95f879e
CI: the host unit tests on Windows
BobClawblaw Oct 14, 2026
7efc823
qwen3_5: the drafter reads TF_TIMING through the platform layer
BobClawblaw Oct 14, 2026
85bb88d
qwen3_5: the drafter takes a prompt longer than its tap ring
BobClawblaw Oct 14, 2026
e01d423
qwen3_5 cuda: prompt chunks past 32 rows see the right keys, and tree…
BobClawblaw Oct 14, 2026
0baccf3
Windows: the server goldens and the Cortheon fuzz step on Windows hosts
BobClawblaw Oct 14, 2026
40159f8
cuda: cuBLASLt opens by its Windows DLL name
BobClawblaw Oct 14, 2026
cdb735b
Windows: writes on an O_APPEND descriptor land at the end whole
BobClawblaw Oct 14, 2026
a63ec9b
golden check: a request-log mismatch names the first differing line
BobClawblaw Oct 14, 2026
d7fb12f
golden check: the request log compares with LF endings on either side
BobClawblaw Oct 14, 2026
02d3e2e
qwen3_5: attention chunks follow each row's own keys, not the forward…
BobClawblaw Oct 15, 2026
e7744bc
qwen3_5: the DFlash2 config's divisors must be positive, and staging …
BobClawblaw Oct 15, 2026
48dcc42
Windows: 1.0.12's new code through the platform layer
BobClawblaw Oct 16, 2026
1d0a11f
docs: 1.0.12's new pages at the default port, 8888
BobClawblaw Oct 16, 2026
26e9b68
lanes recorder: a stream's new file is never made through a link ther…
BobClawblaw Oct 16, 2026
59be20e
qwen3_5 cuda: mixed-width MLX checkpoints, 2 to 8 bits in groups of 64
BobClawblaw Oct 14, 2026
d7e44b5
qwen3_5 cuda: mixed-width comments on one line each
BobClawblaw Oct 14, 2026
7b17d0e
qwen3_5 cuda: 2, 3, 5 and 6-bit modules on tiles of their own width
BobClawblaw Oct 14, 2026
c12503b
qwen3_5 cuda: low-bit comments on one line each
BobClawblaw Oct 14, 2026
aca5a88
qwen3_5 cuda: a prompt GEMM for AffineN's tiles
BobClawblaw Oct 14, 2026
0a2a1c6
qwen3_5 cuda: the prompt GEMM in affine_prefill.cu, code readers in a…
BobClawblaw Oct 14, 2026
62a7b55
qwen3_5 cuda: the load staging buffer freed after load
BobClawblaw Oct 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
qwen3_5: tree drafts on CUDA, the kept path replayed from a log
A verify window's rows may form a tree (each row's parent given): the
convolution taps, the delta rule and attention follow each row's own
branch, and the DFlash2 drafter fills the lane core's planned lanes
(each lane its parent's rank-r choice by the codebook selector), so a
lone stream verifies up to 12 lanes a round and the planner learns
which shapes land.

A verify no longer snapshots every row's state (1.3 GB shared, which
capped the 27B at 8 rows): each stream logs its rows' decay, write and
key, and keep replays the kept path onto the recurrence in one pass
(and moves a tree's kept keys down), so any window width fits. One-row
steps and prompts update in place as before. The lane host times the
target's windows at load, which the depth rule had lacked (it had been
capping chains at 3 drafts).

The runner's new tree mode verifies tree windows with junk branches
against step logits (bit-exact on both models).
  • Loading branch information
BobClawblaw committed Oct 16, 2026
commit 9b8d4aff6c4ea2f9d72c3829033ee87900e043b2
1 change: 1 addition & 0 deletions zig/build/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const kernels = [_]Kernel{
.{ .name = "train", .flags = &.{"-O3"} }, // ours: Sliding Weights' learning step (train.metal's kernels)
.{ .name = "qwen35", .flags = &.{"-O3"} }, // ours: the Qwen3.5 hybrids' glue, the Metal kernels' rounding points
.{ .name = "qwen35_draft", .flags = &.{"-O3"} }, // ours: the DFlash2 drafter's glue (draft_ops.metal's rounding)
.{ .name = "qwen35_keep", .flags = &.{"-O3"} }, // ours: a verified window's kept path applied to its stream's state
.{ .name = "nemotron_norms", .flags = glue }, // ours, each with a host reference (glue_ref.zig): Nemotron's glue
.{ .name = "nemotron_route", .flags = glue },
.{ .name = "nemotron_mamba", .flags = glue },
Expand Down
164 changes: 89 additions & 75 deletions zig/kernels/cuda/qwen35.cu

Large diffs are not rendered by default.

81 changes: 81 additions & 0 deletions zig/kernels/cuda/qwen35.cuh
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// What qwen35.cu and qwen35_keep.cu share: the model's widths (Geo), a stream's window in a forward (Seg), the per-row
// record a verify window leaves in its stream's log, and the walk from a row back through its parents.

#pragma once
#include <cuda_bf16.h>
#include <stdint.h>

namespace tf_q35 {

constexpr int DK = 128; // linear-attention key and value head width
constexpr int TAPS = 4; // causal convolution taps
constexpr int HD = 256; // attention head width
constexpr int MAXQ = 32; // attention query heads at most
constexpr int MAXW = 16; // a window's rows at most (the log's rows a stream)

// The model's widths: hidden, linear key heads, linear value heads, attention query and key/value heads, linear layers.
struct Geo {
int hid, nk, nv, qh, kvh, nl;
__device__ int conv() const { return (2 * nk + nv) * DK; } // q, k and v channels the convolution sees
__device__ size_t rec() const { return (size_t)nv * DK * DK; } // floats of one layer's recurrence
__device__ size_t conv_rows() const { return (size_t)(TAPS - 1) * conv(); }
// one row's record of one linear layer: decay and write strength a value head, its write a value (head, dv), its
// key a key head, and the convolution tail after it
__device__ size_t log_bytes() const { return (size_t)nv * 4 + (size_t)nv * DK * 4 + (size_t)nk * DK * 2 + conv_rows() * 2; }
};

// One stream's window in this forward: its state blocks, cache length before the window, and rows.
struct Seg {
unsigned long long rec; // float recurrences, one rec() block a linear layer
unsigned long long conv; // bf16 convolution tails, conv_rows() a linear layer
unsigned long long kv; // bf16 keys then values, kvh * cap * HD each, an attention layer at a time
unsigned long long tap; // a drafter's ring of tapped rows (0: none): slot pos % tap_rows, taps * hid bf16 each
unsigned long long log; // the window's rows' records (MAXW rows of nl layers of log_bytes), for keep
int cap, len, row0, rows, tap_rows, taps;
};

// A window row's record of one linear layer (Seg.log).
struct LogRow {
float* g; // [nv] decay
float* delta; // [nv][DK] the write's strength along dv
__nv_bfloat16* k; // [nk][DK] the key
__nv_bfloat16* conv; // [TAPS - 1][conv()] the tail after the row
};

__device__ __forceinline__ LogRow log_row(const Geo& geo, const Seg& sg, int layer, int row) {
char* base = reinterpret_cast<char*>(sg.log) + ((size_t)row * geo.nl + layer) * geo.log_bytes();
LogRow l;
l.g = reinterpret_cast<float*>(base);
l.delta = l.g + geo.nv;
l.k = reinterpret_cast<__nv_bfloat16*>(l.delta + (size_t)geo.nv * DK);
l.conv = l.k + (size_t)geo.nk * DK;
return l;
}

// The rows of a window to keep, in order (row 0 first), passed by value.
struct Path {
int n;
int rows[MAXW];
};

// The row `steps` tokens before forward row `w` through its parents (rowpar: each forward row's parent forward row, -1
// for a window's first row): a forward row, or -1 - t for the stream's convolution tail row t (TAPS - 2 the newest).
__device__ __forceinline__ int back(const int* __restrict__ rowpar, int w, int steps) {
int a = w;
for (int s = 1; s <= steps; s++) {
a = rowpar[a];
if (a < 0) return -1 - (TAPS - 2 - (steps - s));
}
return a;
}

__device__ __forceinline__ float bf(__nv_bfloat16 x) { return __bfloat162float(x); }
__device__ __forceinline__ float rbf(float x) { return __bfloat162float(__float2bfloat16_rn(x)); }

__device__ __forceinline__ float warp_sum(float x) {
#pragma unroll
for (int m = 16; m; m >>= 1) x += __shfl_xor_sync(0xffffffffu, x, m);
return x;
}

} // namespace tf_q35
15 changes: 15 additions & 0 deletions zig/kernels/cuda/qwen35_draft.cu
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,21 @@ extern "C" __global__ void tf_q35d_gather_taps(const __nv_bfloat16* __restrict__
for (int i = threadIdx.x; i < width; i += blockDim.x) dst[i] = src[i];
}

// Rows of a window to gather, by value (a tree's kept path).
struct TapRows {
int n;
int rows[16];
};

// Tap rows (start + rows.rows[i]) of a stream's ring into OUT rows 0..n: a kept path's rows in order. Grid (n).
extern "C" __global__ void tf_q35d_gather_rows(const __nv_bfloat16* __restrict__ RING, int R, long long start, TapRows rows, int width,
__nv_bfloat16* __restrict__ OUT) {
const long long row = start + rows.rows[blockIdx.x];
const __nv_bfloat16* src = RING + (size_t)(row % R) * width;
__nv_bfloat16* dst = OUT + (size_t)blockIdx.x * width;
for (int i = threadIdx.x; i < width; i += blockDim.x) dst[i] = src[i];
}

// y[t, c] = sum over lags l of (BASE[branch, l, c] + DYN[t, (branch * 2 + l) * groups + c / group]) * x[t - l, c],
// each product and sum rounded to bf16 in turn; x[-1] is zero (the block's first row has no past); RES, if given,
// is added last. D wide rows, `group` channels a dynamic coefficient. Grid (rows), 256 threads.
Expand Down
63 changes: 63 additions & 0 deletions zig/kernels/cuda/qwen35_keep.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Keeping a verified window's path on CUDA (zig/src/families/qwen3_5/cuda_cache.zig): the stream's recurrences take
// the path's logged updates in order, its convolution tails the path's last row's, and a tree's kept keys move down
// to the slots after the cache. The rows of a window were recorded by qwen35.cu's kernels (Seg.log).

#include "qwen35.cuh"

using namespace tf_q35;

// Each linear layer's recurrence through the path's rows' (decay, key, write), as the forward's chain would have
// left it. Grid (1, DK / 4, nv * nl), block (32, 4): a warp a (layer, value head, value row), its lanes over the key.
extern "C" __global__ void __launch_bounds__(128) tf_q35k_apply(Geo geo, Seg sg, Path path) {
const int NK = geo.nk, NV = geo.nv;
const int layer = blockIdx.z / NV, hv = blockIdx.z % NV;
const int hk = hv / (NV / NK);
const int dk = threadIdx.x;
const int dv = blockIdx.y * 4 + threadIdx.y;
constexpr int PT = DK / 32;
const size_t at = ((size_t)hv * DK + dv) * DK + PT * dk;
float* st = reinterpret_cast<float*>(sg.rec) + (size_t)layer * geo.rec() + at;
float state[PT];
#pragma unroll
for (int i = 0; i < PT; i++) state[i] = st[i];
for (int j = 0; j < path.n; j++) {
const LogRow l = log_row(geo, sg, layer, path.rows[j]);
const float g = l.g[hv], d = l.delta[hv * DK + dv];
#pragma unroll
for (int i = 0; i < PT; i++) {
state[i] = state[i] * g;
state[i] = fmaf(bf(l.k[hk * DK + PT * dk + i]), d, state[i]);
}
}
#pragma unroll
for (int i = 0; i < PT; i++) st[i] = state[i];
}

// Each linear layer's convolution tail as logged after window row `last`. Grid (nl, tail values / 256), 256 threads.
extern "C" __global__ void tf_q35k_conv(Geo geo, Seg sg, int last) {
const int layer = blockIdx.x;
const size_t n = geo.conv_rows();
const size_t i = (size_t)blockIdx.y * blockDim.x + threadIdx.x;
if (i >= n) return;
__nv_bfloat16* CS = reinterpret_cast<__nv_bfloat16*>(sg.conv) + (size_t)layer * n;
CS[i] = log_row(geo, sg, layer, last).conv[i];
}

// The path's rows' keys and values (slot cache length + row) down to the slots cache length + 0, 1, ... in path
// order: row j of the path is at least j, so a move never lands on a slot a later move still reads. One block a
// (attention layer, kv head): grid (attention layers, kvh), HD threads, a barrier between moves.
extern "C" __global__ void __launch_bounds__(256) tf_q35k_compact(Geo geo, Seg sg, Path path) {
const int KVH = geo.kvh;
const int layer = blockIdx.x, h = blockIdx.y;
__nv_bfloat16* keys = reinterpret_cast<__nv_bfloat16*>(sg.kv) + ((size_t)layer * 2 * KVH + h) * sg.cap * HD;
__nv_bfloat16* values = keys + (size_t)KVH * sg.cap * HD;
const int d = threadIdx.x;
for (int j = 0; j < path.n; j++) {
const int from = sg.len + path.rows[j], to = sg.len + j;
if (from != to) {
keys[(size_t)to * HD + d] = keys[(size_t)from * HD + d];
values[(size_t)to * HD + d] = values[(size_t)from * HD + d];
}
__syncthreads();
}
}
16 changes: 10 additions & 6 deletions zig/src/core/lanes/drafted.zig
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ pub const Drafted = struct {
m.plain_guard = d.plain_guard;
m.draft_streams = d.batched;
m.draft_probabilities = false;
m.head_trees = false;
m.head_trees = d.trees;
if (d.window_costs.len > 0) m.window_costs = d.window_costs;
if (d.lane_costs.len > 0) m.lane_costs = d.lane_costs;
return m;
}

Expand Down Expand Up @@ -157,15 +159,17 @@ pub const Drafted = struct {
x.holds.clearRetainingCapacity();
try x.firsts.resize(x.gpa, requests.len);
for (requests, x.firsts.items) |r, *tok| {
if (r.lanes != null) return error.TreesNotBuilt;
if (r.lanes != null and !x.drafter.facts().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
var pending: u32 = undefined;
if (r.rows) |rows| {
for (rows, 0..) |row, i| if (row != i) return error.TreesNotBuilt;
const n: u32 = @intCast(rows.len);
// 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 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] });
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 });
pending = r.follow[rows.len - 1];
lane.rows = true;
} else {
Expand All @@ -187,7 +191,7 @@ pub const Drafted = struct {
lane.filler = r.depth;
continue;
}
try x.holds.append(x.gpa, .{ .stream = r.stream, .pending = pending, .position = r.position, .depth = r.depth });
try x.holds.append(x.gpa, .{ .stream = r.stream, .pending = pending, .position = r.position, .depth = r.depth, .lanes = r.lanes });
}
if (x.absorbs.items.len > 0) try x.drafter.absorb(x.absorbs.items);
if (x.holds.items.len > 0) try x.drafter.hold(x.holds.items);
Expand Down
11 changes: 9 additions & 2 deletions zig/src/core/lanes/drafter.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
//! A drafter outside the target family reading its tapped states; each call takes a round's streams together.
const Stream = @import("stream.zig").Stream;
const Features = @import("backend.zig").Features;
const Cost = @import("config.zig").Cost;
const Shape = @import("shape.zig").Shape;

/// What the round loop's depth rule needs from the drafter itself (not from the target, whose own head may not exist).
pub const Facts = struct {
Expand All @@ -10,13 +12,18 @@ pub const Facts = struct {
plain_guard: bool = true, // plain rounds compete with drafted depths (the rule may choose no drafts)
batched: bool = false, // hold() runs a shared round's streams as one batch
stream_bytes: usize = 0, // device bytes each opened stream holds (its caches), for memory admission
trees: bool = false, // hold() takes a tree of lanes (Hold.lanes), each lane its parent's rank-r token
window_costs: []const Cost = &.{}, // the target's window ms by rows (timed at load), for the depth rule
lane_costs: []const Cost = &.{}, // the same for the lane planner (Model.lane_costs)
};

/// Target rows [start, start + features.rows) and the token after each; rows at or past `start` replace what was held.
pub const Absorb = struct { stream: *Stream, features: Features, start: u64, follow: []const u32 };
/// `rows`, when given, picks the features' rows to absorb (a tree's kept path), in order; null: all of them.
pub const Absorb = struct { stream: *Stream, features: Features, start: u64, follow: []const u32, rows: ?[]const u32 = null };

/// Draft `depth` tokens after `pending`, the first at `position`; asked only once row `position - 2` was absorbed.
pub const Hold = struct { stream: *Stream, pending: u32, position: u64, depth: u32 };
/// With `lanes`, a tree instead: lane i's token is the rank-r choice after its parent (depth unused).
pub const Hold = struct { stream: *Stream, pending: u32, position: u64, depth: u32, lanes: ?*const Shape = null };

pub const Drafter = struct {
ptr: *anyopaque,
Expand Down
1 change: 1 addition & 0 deletions zig/src/cuda/kernels.zig
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pub const sample: []const u8 = if (available) &Blob("fatbin_sample").bytes else
pub const train: []const u8 = if (available) &Blob("fatbin_train").bytes else &.{};
pub const qwen35: []const u8 = if (available) &Blob("fatbin_qwen35").bytes else &.{};
pub const qwen35_draft: []const u8 = if (available) &Blob("fatbin_qwen35_draft").bytes else &.{};
pub const qwen35_keep: []const u8 = if (available) &Blob("fatbin_qwen35_keep").bytes else &.{};
pub const qmmf: []const u8 = if (available) &Blob("fatbin_qmmf").bytes else &.{};
pub const prompt16: []const u8 = if (available) &Blob("fatbin_prompt16").bytes else &.{};
pub const modelopt_pack: []const u8 = if (available) &Blob("fatbin_modelopt_pack").bytes else &.{};
Expand Down
104 changes: 104 additions & 0 deletions zig/src/families/qwen3_5/cuda_cache.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
//! One stream's state on the CUDA engine: its recurrences and convolution tails, keys and values, a drafter's tap
//! ring, and the log of its newest verify window's rows, from which `keep` lands any path of that window (a prefix
//! of a chain, or a branch of a tree) without the forward having touched the stream's state.
const std = @import("std");
const cuda = @import("cuda");
const geometry = @import("cuda_geometry.zig");
const engine = @import("cuda_engine.zig");

const Engine = engine.Engine;
const DeviceBuffer = cuda.DeviceBuffer;

/// Rows a drafter's tap ring holds a stream: its window and a prompt chunk more.
pub const tap_rows = 2048 + engine.max_rows;

/// qwen35.cuh's Seg and Path.
pub const Seg = extern struct { rec: u64, conv: u64, kv: u64, tap: u64, log: u64, cap: c_int, len: c_int, row0: c_int, rows: c_int, tap_rows: c_int, taps: c_int };
pub const Path = extern struct { n: c_int, rows: [engine.most_window]c_int };

pub const Cache = struct {
state: DeviceBuffer,
kv: DeviceBuffer,
/// A drafter's tapped rows (`Engine.taps`), a ring of tap_rows: the row at position p in slot p % tap_rows.
tap: ?DeviceBuffer = null,
/// The newest verify window's rows' records (qwen35.cuh's LogRow), most_window rows a linear layer.
log: DeviceBuffer,
cap: usize,
len: usize = 0,
/// Positions the newest forward wrote up to: a tap ring holds them until the next forward, whatever `keep` lands.
written: usize = 0,
logits: []u16,
/// The newest verify window of more than one row, until its path is kept: where it started, its rows.
last: ?struct { start: usize, rows: usize } = null,

pub fn init(gpa: std.mem.Allocator, e: *const Engine, cap: usize) !Cache {
var state = try DeviceBuffer.alloc(e.d, e.g.stateBytes());
errdefer state.free();
try state.fill8(0, null);
var kv = try DeviceBuffer.alloc(e.d, e.g.kvBytes(cap));
errdefer kv.free();
try kv.fill8(0, null); // touched now, not as the first request's keys land (the driver commits on first touch)
var log = try DeviceBuffer.alloc(e.d, e.g.logBytes(engine.most_window));
errdefer log.free();
try log.fill8(0, null);
var tap: ?DeviceBuffer = null;
if (e.n_taps > 0) {
tap = try DeviceBuffer.alloc(e.d, e.tapBytes());
try tap.?.fill8(0, null);
}
errdefer if (tap) |*t| t.free();
return .{ .state = state, .kv = kv, .tap = tap, .log = log, .cap = cap, .logits = try gpa.alloc(u16, e.g.vocab) };
}

/// Ready for another stream: no rows, the recurrences and tails zero (on the engine's stream, before its forwards).
pub fn reset(self: *Cache, e: *const Engine) !void {
self.len = 0;
self.written = 0;
self.last = null;
try self.state.fill8(0, e.stream.handle);
}

pub fn deinit(self: *Cache, gpa: std.mem.Allocator) void {
self.state.free();
self.kv.free();
self.log.free();
if (self.tap) |*t| t.free();
gpa.free(self.logits);
}

/// The stream's window of `rows` rows from forward row `row0`, after `len` cached positions.
pub fn seg(self: *const Cache, e: *const Engine, len: usize, row0: usize, rows: usize) Seg {
const g = e.g;
return .{ .rec = self.state.ptr, .conv = self.state.ptr + g.deltas() * g.recBytes(), .kv = self.kv.ptr, .tap = if (self.tap) |t| t.ptr else 0, .log = self.log.ptr, .cap = @intCast(self.cap), .len = @intCast(len), .row0 = @intCast(row0), .rows = @intCast(rows), .tap_rows = tap_rows, .taps = @intCast(e.n_taps) };
}

/// Keeps `path` (the window's rows, the first 0, ascending) of the newest window: the recurrences and tails as a
/// chain of those rows would have left them, a tree's kept keys moved down to the slots after the cache, the
/// length at the path's end. Queued on the engine's stream; nothing waits.
pub fn keep(self: *Cache, e: *Engine, path: []const u32) !void {
const last = self.last orelse return error.NothingToKeep;
if (path.len == 0 or path.len > last.rows or path[0] != 0) return error.NothingToKeep;
var p: Path = .{ .n = @intCast(path.len), .rows = @splat(0) };
var prefix = true;
for (path, 0..) |r, i| {
if (r >= last.rows or (i > 0 and r <= path[i - 1])) return error.NothingToKeep;
p.rows[i] = @intCast(r);
prefix = prefix and r == i;
}
self.last = null;
self.len = last.start + path.len;
const g = e.g;
const sg = self.seg(e, last.start, 0, last.rows);
try e.run(e.keeps.apply, .{ 1, geometry.dk / 4, g.v_heads * g.deltas() }, .{ 32, 4, 1 }, .{ e.geo, sg, p });
try e.run(e.keeps.conv, .{ g.deltas(), (g.convBytes() / 2 + 255) / 256, 1 }, .{ 256, 1, 1 }, .{ e.geo, sg, @as(c_int, @intCast(path[path.len - 1])) });
if (!prefix and g.attentions() > 0) try e.run(e.keeps.compact, .{ g.attentions(), g.kv_heads, 1 }, .{ geometry.head_dim, 1, 1 }, .{ e.geo, sg, p });
}

/// The newest window kept whole (the round loop keeps nothing when every row landed), before the next forward.
pub fn settle(self: *Cache, e: *Engine) !void {
const last = self.last orelse return;
var all: [engine.most_window]u32 = undefined;
for (all[0..last.rows], 0..) |*r, i| r.* = @intCast(i);
try self.keep(e, all[0..last.rows]);
}
};
Loading