Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
616fcca
Lane core: requests that arrive together share their prompt passes
philip-pentatonic Oct 10, 2026
82d8721
Nemotron: the checkpoint Source copies to a Target, so other CUDA fam…
philip-pentatonic Oct 10, 2026
99bcc5b
Qwen3.8-27B on CUDA: the qwen27 family's engine for NVIDIA GPUs, ever…
philip-pentatonic Oct 10, 2026
907e013
Native image input: images from a request's image parts, prepared bef…
BobClawblaw Oct 10, 2026
47c4098
Native image input: --vision-urls fetches public HTTPS image URLs as …
BobClawblaw Oct 10, 2026
b68e3da
Merge PR #608 (Qwen3.8-27B native CUDA engine) onto 1.0.7
BobClawblaw Oct 12, 2026
9f99ca9
Merge PR #598 and #614 (native image input, HTTPS image URLs) onto qw…
BobClawblaw Oct 12, 2026
fa22819
Qwen3.5 vision tower on CUDA: qwen_vision.cu kernels, the Tower, and …
BobClawblaw Oct 12, 2026
407cb28
Qwen image preprocessing on Linux: stb_image decode, EXIF, alpha, sma…
BobClawblaw Oct 12, 2026
ff7cc22
Native image input for Qwen3.8-27B on CUDA: tower rows spliced into t…
BobClawblaw Oct 12, 2026
5d8bf48
qwen27 CUDA: --kv-cache fp8, and attention partials sized for the adm…
BobClawblaw Oct 12, 2026
06cc811
qwen27 CUDA: a prompt cache, so a chat's next turn resumes its kept s…
BobClawblaw Oct 12, 2026
2c222ae
Merge main (1.0.8 work) into qwen27-cuda-1.0.7
BobClawblaw Oct 12, 2026
d49a906
qwen27 CUDA: no tooling that imports the Python engine in the tree
BobClawblaw Oct 12, 2026
e3b7210
Merge main (1.0.9) into qwen27-cuda-1.0.7
BobClawblaw Oct 13, 2026
72bf399
Merge main (1.0.10) into qwen27-cuda-1.0.7
BobClawblaw Oct 14, 2026
4e15fae
Merge main (1.0.11) into qwen27-cuda-1.0.7
BobClawblaw Oct 14, 2026
bcd433c
Lean rule: one-line comments and docstrings, and a vendored-source ex…
BobClawblaw Oct 14, 2026
5a4987b
Living Weights: the learner, pocket and fits move to zig/src/living, …
ZackSample Oct 15, 2026
75978a1
Living Weights learns into any family described as data: the family's…
ZackSample Oct 15, 2026
dac84b6
Merge lw-b-core (#878, Living Weights as a core module) onto #726 (Qw…
ZackSample Oct 16, 2026
e90a103
Living Weights: the learner as the 27B's lessons run it
ZackSample Oct 16, 2026
b9b3e83
CUDA: Living Weights' DeltaNet and gated attention backward as core k…
ZackSample Oct 16, 2026
018d2b2
Qwen3.8-27B on CUDA learns: Living Weights' pocket beside every MLP, …
ZackSample Oct 16, 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
qwen27 CUDA: --kv-cache fp8, and attention partials sized for the adm…
…itted streams

--kv-cache fp8 keeps the 27B's attention caches as e4m3 rows with one fp32 scale a
(position, key head) row (amax / 448), half the bytes of bf16: 256K tokens with the
image tower in one stream on a 32 GB card. bf16 stays the default and its bits are
unchanged (0.6.6 exactness: serial 4/4, windows 54/54, drafted 4/4, shared 0 replies
differ).

- tf_kv_quant (qwen_ops.cu) quantizes commits' and prompts' rows into the caches
- pattn8_kernel: prefill attention staging e4m3 rows widened to bf16, a step ahead in
  registers (within 5% of bf16 at 100K)
- _shared8/_tail8 (tests/cuda/qwen27/attention_kv8.py, captured like the other glue):
  the decode kernels over e4m3; _tail8 quantizes the window's own rows as their commit
  will, so a key's bits never depend on windows, drafts or batching (drafted equals
  serial, concurrent equals solo); attention.py's _merge folds the partials unchanged
- attention partials leave the scratch arena: sized after admission for the streams
  admitted (Engine.fit, native fit hook) and charged to each stream, not for 16 streams
  at full context (1.4 GiB back at 122,880, 2.9 GiB at 262,144)
- tf-qwen27-cuda kvcompare: fp8 against bf16 teacher-forced, top-1 agreement and KL
  • Loading branch information
BobClawblaw committed Oct 12, 2026
commit 5d8bf48592d41a6496cd907589237f7830455bb9
99 changes: 88 additions & 11 deletions zig/kernels/cuda/prefill_attention.cu
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Device code of src/tensorfold/cuda/kernels/prefill_attention.cu (lines 1-250, comments and ATen includes dropped), checked by zig/tests/cuda/copies.py.
#include <cuda_bf16.h>
#include <cuda_fp8.h>
#include <cuda_runtime.h>
#include <stdint.h>

Expand Down Expand Up @@ -56,11 +57,13 @@ __device__ __forceinline__ float rowsum(const float (&c)[8]) {
__fadd_rn(__fadd_rn(w[1], w[5]), __fadd_rn(w[3], w[7])));
}

template <int D, int WARPS, int HPC, int NS>
__global__ void __launch_bounds__(32 * WARPS, 1)
pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ kc,
const __nv_bfloat16* __restrict__ vc, __nv_bfloat16* __restrict__ out, int p0, int W, int H, int HK,
int G, float scale) {
// F8: the cache is e4m3 rows (kc, vc as bytes) with an fp32 scale a (position, key head) row (ks, vs); staging
// widens each row to bf16 times its scale, so the tiles and their dots are the bf16 kernel's.
template <int D, int WARPS, int HPC, int NS, bool F8>
__device__ __forceinline__ void pattn_body(const __nv_bfloat16* __restrict__ q, const void* __restrict__ kc,
const void* __restrict__ vc, const float* __restrict__ ks,
const float* __restrict__ vs, __nv_bfloat16* __restrict__ out, int p0,
int W, int H, int HK, int G, float scale) {
constexpr int C = D / 8, K16 = D / 16, NB = D / 8, RB = WARPS / HPC, THREADS = 32 * WARPS;
constexpr bool QREG = D <= 128; // the queries' fragments stay in registers, else in shared memory
extern __shared__ uint4 smem[];
Expand All @@ -71,14 +74,61 @@ pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restric
const int row0 = blockIdx.x * 16 * RB, last = min(row0 + 16 * RB, W) - 1;
const int head = hk * G + hg * HPC + warp % HPC, wrow = row0 + (warp / HPC) * 16;
const int tiles = (p0 + last) / BN + 1, items = 4 * tiles, limit = p0 + W;
// F8: an item's e4m3 words and scales go to registers a step ahead (fetch), then widen into its slot (put), so
// the loads land while the slot before computes
constexpr int PER = (HALF * C + THREADS - 1) / THREADS;
uint2 pre[F8 ? PER : 1];
float pre_s[F8 ? PER : 1];
auto fetch = [&](int item) {
if constexpr (F8) {
const uint8_t* src = static_cast<const uint8_t*>(item % 4 < 2 ? kc : vc);
const float* sc = item % 4 < 2 ? ks : vs;
const int key0 = (item / 4) * BN + (item % 2) * HALF;
#pragma unroll
for (int j = 0; j < PER; ++j) {
const int i = threadIdx.x + j * THREADS, key = key0 + i / C;
pre[j] = make_uint2(0u, 0u);
pre_s[j] = 0.0f;
if (i < HALF * C && key < limit) {
const int64_t r = (int64_t)key * HK + hk;
pre[j] = __ldg(reinterpret_cast<const uint2*>(src + r * D + (i % C) * 8));
pre_s[j] = __ldg(sc + r);
}
}
}
};
auto put = [&](int item) {
if constexpr (F8) {
uint4* dst = slots + (item % NS) * HALF * C;
#pragma unroll
for (int j = 0; j < PER; ++j) {
const int i = threadIdx.x + j * THREADS;
if (i >= HALF * C) continue;
uint4 w;
const __nv_fp8x2_storage_t* e = reinterpret_cast<const __nv_fp8x2_storage_t*>(&pre[j]);
uint32_t* o = reinterpret_cast<uint32_t*>(&w);
#pragma unroll
for (int k = 0; k < 4; ++k) {
const float2 x = __half22float2(__half2(__nv_cvt_fp8x2_to_halfraw2(e[k], __NV_E4M3)));
o[k] = pack(__fmul_rn(x.x, pre_s[j]), __fmul_rn(x.y, pre_s[j]));
}
dst[sw<D>(i / C, i % C)] = w;
}
}
};
auto stage = [&](int item) {
const __nv_bfloat16* src = item % 4 < 2 ? kc : vc;
const int key0 = (item / 4) * BN + (item % 2) * HALF;
uint4* dst = slots + (item % NS) * HALF * C;
for (int i = threadIdx.x; i < HALF * C; i += THREADS) {
const int key = key0 + i / C;
const bool in = key < limit; // past the cache's filled keys: zeros, never read
cp16z(dst + sw<D>(i / C, i % C), src + ((int64_t)(in ? key : 0) * HK + hk) * D + (i % C) * 8, in);
if constexpr (F8) {
fetch(item);
put(item);
} else {
const __nv_bfloat16* src = static_cast<const __nv_bfloat16*>(item % 4 < 2 ? kc : vc);
for (int i = threadIdx.x; i < HALF * C; i += THREADS) {
const int key = key0 + i / C;
const bool in = key < limit; // past the cache's filled keys: zeros, never read
cp16z(dst + sw<D>(i / C, i % C), src + ((int64_t)(in ? key : 0) * HK + hk) * D + (i % C) * 8, in);
}
}
};
uint32_t qa[QREG ? K16 : 1][4];
Expand Down Expand Up @@ -106,6 +156,9 @@ pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restric
if (i < items) stage(i);
commit();
}
if constexpr (F8) {
if (NS < items) fetch(NS);
}
float o[NB][4];
#pragma unroll
for (int i = 0; i < NB; ++i) o[i][0] = o[i][1] = o[i][2] = o[i][3] = 0.0f;
Expand All @@ -120,7 +173,12 @@ pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restric
};
auto done = [&](int it) { // the slot is free: stage the item NS ahead into it
__syncthreads();
if (it + NS < items) stage(it + NS);
if constexpr (F8) {
if (it + NS < items) {
put(it + NS);
if (it + NS + 1 < items) fetch(it + NS + 1);
}
} else if (it + NS < items) stage(it + NS);
commit();
};
auto scores = [&](float (&s)[4][4], const uint4* sl) {
Expand Down Expand Up @@ -238,6 +296,22 @@ pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restric
}
}

template <int D, int WARPS, int HPC, int NS>
__global__ void __launch_bounds__(32 * WARPS, 1)
pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ kc,
const __nv_bfloat16* __restrict__ vc, __nv_bfloat16* __restrict__ out, int p0, int W, int H, int HK,
int G, float scale) {
pattn_body<D, WARPS, HPC, NS, false>(q, kc, vc, nullptr, nullptr, out, p0, W, H, HK, G, scale);
}

template <int D, int WARPS, int HPC, int NS>
__global__ void __launch_bounds__(32 * WARPS, 1)
pattn8_kernel(const __nv_bfloat16* __restrict__ q, const uint8_t* __restrict__ kc, const uint8_t* __restrict__ vc,
const float* __restrict__ ks, const float* __restrict__ vs, __nv_bfloat16* __restrict__ out, int p0,
int W, int H, int HK, int G, float scale) {
pattn_body<D, WARPS, HPC, NS, true>(q, kc, vc, ks, vs, out, p0, W, H, HK, G, scale);
}

} // namespace tf_prefill_attention

// Head dim 128, eight warps, eight query heads a block, eight staging slots (Nemotron's 16 heads a KV head).
Expand All @@ -246,3 +320,6 @@ template __global__ void tf_prefill_attention::pattn_kernel<128, 8, 8, 8>(const
// Head dim 256, two query heads a block, two staging slots beside the staged queries (Qwen3.8's 6 heads a KV head).
template __global__ void tf_prefill_attention::pattn_kernel<256, 8, 2, 2>(const __nv_bfloat16*,
const __nv_bfloat16*, const __nv_bfloat16*, __nv_bfloat16*, int, int, int, int, int, float);
// The same over an fp8 cache (--kv-cache fp8).
template __global__ void tf_prefill_attention::pattn8_kernel<256, 8, 2, 2>(const __nv_bfloat16*, const uint8_t*,
const uint8_t*, const float*, const float*, __nv_bfloat16*, int, int, int, int, int, float);
40 changes: 40 additions & 0 deletions zig/kernels/cuda/qwen_ops.cu
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// The 27B's own small kernels: batched state copies, the drafter's taps and its fp32 RMSNorm.
#include <cuda_bf16.h>
#include <cuda_fp8.h>
#include <stdint.h>

struct TfCopy {
Expand All @@ -17,6 +18,45 @@ extern "C" __global__ void __launch_bounds__(256) tf_copy_batch(const TfCopy* __
dst[i] = src[i];
}

struct TfQuant {
unsigned long long src, dst, scale; // bf16 rows of 256, their e4m3 rows, one fp32 scale a row
unsigned long long rows;
};

// --kv-cache fp8: each 256-wide (position, key head) row as e4m3 of x * (448 / amax), its scale s = amax / 448 (1 for
// a row of zeros). A warp a row, eight rows a block, items on y; attention_kv8.py's quantize and _q8 (the window rows
// _tail8 quantizes itself) give the same bits.
extern "C" __global__ void __launch_bounds__(256) tf_kv_quant(const TfQuant* __restrict__ items) {
const TfQuant it = items[blockIdx.y];
const unsigned long long row = static_cast<unsigned long long>(blockIdx.x) * 8 + threadIdx.x / 32;
if (row >= it.rows) return;
const int lane = threadIdx.x % 32;
const uint4 w = reinterpret_cast<const uint4*>(it.src)[row * 32 + lane];
const __nv_bfloat162* h = reinterpret_cast<const __nv_bfloat162*>(&w);
float x[8];
#pragma unroll
for (int i = 0; i < 4; ++i) {
const float2 f = __bfloat1622float2(h[i]);
x[2 * i] = f.x;
x[2 * i + 1] = f.y;
}
float amax = 0.0f;
#pragma unroll
for (int i = 0; i < 8; ++i) amax = fmaxf(amax, fabsf(x[i]));
#pragma unroll
for (int o = 16; o > 0; o /= 2) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
const float s = amax > 0.0f ? __fdiv_rn(amax, 448.0f) : 1.0f;
const float inv = amax > 0.0f ? __fdiv_rn(448.0f, amax) : 1.0f;
uint2 out;
__nv_fp8x2_storage_t* q = reinterpret_cast<__nv_fp8x2_storage_t*>(&out);
#pragma unroll
for (int i = 0; i < 4; ++i)
q[i] = __nv_cvt_float2_to_fp8x2(make_float2(__fmul_rn(x[2 * i], inv), __fmul_rn(x[2 * i + 1], inv)),
__NV_SATFINITE, __NV_E4M3);
reinterpret_cast<uint2*>(it.dst)[row * 32 + lane] = out;
if (lane == 0) reinterpret_cast<float*>(it.scale)[row] = s;
}

// forward.tree_forward's taps: (x.float() + pending.float()).to(bfloat16), row r into columns [col, col + D) of OUT.
extern "C" __global__ void __launch_bounds__(256) tf_tap(const __nv_bfloat16* __restrict__ x,
const __nv_bfloat16* __restrict__ pending,
Expand Down
91 changes: 88 additions & 3 deletions zig/src/cli/qwen27_cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ const usage =
\\ Greedy shared rounds of one row a stream over every prompt, timed.
\\ tf-qwen27-cuda multi MODEL --kernels DIR --drafter DIR --prompts multi.json
\\ capture_multi.py's drafted shared rounds: each round's windows and every reply against the capture's.
\\ tf-qwen27-cuda kvcompare MODEL --kernels DIR --prompts prompts.json [--max-tokens N]
\\ --kv-cache fp8 against bf16, teacher-forced on bf16's greedy reply: top-1 agreement and KL a token.
\\ tf-qwen27-cuda vision MODEL --fixtures DIR
\\ The image tower on qwen_vision_fixtures.py's patches: each image's rows against 0.6.6's (cosine, max error).
\\
Expand All @@ -32,6 +34,7 @@ const Options = struct {
dump: ?[]const u8 = null, // windows: a case's per-norm rows into this folder
cases: ?[]const u8 = null, // windows: only these cases, comma separated
drafter: ?[]const u8 = null, // draft: the DFlash2 checkpoint
kv8: bool = false, // --kv-cache fp8: e4m3 attention caches
};

pub fn main(init: std.process.Init) !u8 {
Expand All @@ -42,9 +45,10 @@ pub fn main(init: std.process.Init) !u8 {
const rounds = args.len >= 2 and std.mem.eql(u8, args[1], "rounds");
const drafting = args.len >= 2 and std.mem.eql(u8, args[1], "draft");
const multi = args.len >= 2 and std.mem.eql(u8, args[1], "multi");
const kvcompare = args.len >= 2 and std.mem.eql(u8, args[1], "kvcompare");
if (args.len >= 5 and std.mem.eql(u8, args[1], "vision") and std.mem.eql(u8, args[3], "--fixtures"))
return checkVision(gpa, arena, init.io, args[2], args[4]);
if (args.len < 3 or !(std.mem.eql(u8, args[1], "run") or windows or rounds or drafting or multi)) {
if (args.len < 3 or !(std.mem.eql(u8, args[1], "run") or windows or rounds or drafting or multi or kvcompare)) {
std.debug.print("{s}", .{usage});
return 2;
}
Expand All @@ -53,7 +57,7 @@ pub fn main(init: std.process.Init) !u8 {
while (i + 1 < args.len) : (i += 2) {
const k = args[i];
const v = args[i + 1];
if (std.mem.eql(u8, k, "--kernels")) o.kernels = v else if (std.mem.eql(u8, k, "--prompts")) o.prompts = v else if (std.mem.eql(u8, k, "--expect")) o.expect = v else if (std.mem.eql(u8, k, "--max-tokens")) o.max_tokens = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--context")) o.context = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--device")) o.device = try std.fmt.parseInt(c_int, v, 10) else if (std.mem.eql(u8, k, "--dump")) o.dump = v else if (std.mem.eql(u8, k, "--cases")) o.cases = v else if (std.mem.eql(u8, k, "--drafter")) o.drafter = v else {
if (std.mem.eql(u8, k, "--kernels")) o.kernels = v else if (std.mem.eql(u8, k, "--prompts")) o.prompts = v else if (std.mem.eql(u8, k, "--expect")) o.expect = v else if (std.mem.eql(u8, k, "--max-tokens")) o.max_tokens = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--context")) o.context = try std.fmt.parseInt(usize, v, 10) else if (std.mem.eql(u8, k, "--device")) o.device = try std.fmt.parseInt(c_int, v, 10) else if (std.mem.eql(u8, k, "--dump")) o.dump = v else if (std.mem.eql(u8, k, "--cases")) o.cases = v else if (std.mem.eql(u8, k, "--drafter")) o.drafter = v else if (std.mem.eql(u8, k, "--kv-cache")) o.kv8 = std.mem.eql(u8, v, "fp8") else {
std.debug.print("unknown option {s}\n{s}", .{ k, usage });
return 2;
}
Expand All @@ -70,13 +74,15 @@ pub fn main(init: std.process.Init) !u8 {
defer ctx.deinit();
const clock = std.Io.Clock.awake;
var t0 = clock.now(init.io).toNanoseconds();
const e = try qwen.Engine.init(gpa, init.io, &ctx, o.model, o.kernels, .{ .context = o.context });
const e = try qwen.Engine.init(gpa, init.io, &ctx, o.model, o.kernels, .{ .context = o.context, .kv8 = o.kv8 });
defer e.deinit();
try e.fit(16); // the shared rounds' partials: up to 16 streams of the context (windows' are 4096)
std.debug.print("loaded in {d:.1}s, weights {d:.2} GiB\n", .{ @as(f64, @floatFromInt(clock.now(init.io).toNanoseconds() - t0)) / 1e9, @as(f64, @floatFromInt(e.w.bytes())) / (1 << 30) });
if (windows) return checkWindows(gpa, arena, init.io, e, prompts, o.dump, o.cases);
if (rounds) return benchRounds(gpa, arena, init.io, e, prompts, o.max_tokens);
if (drafting) return runDrafted(gpa, arena, init.io, e, o, prompts, expect);
if (multi) return runMulti(gpa, arena, init.io, e, o, prompts);
if (kvcompare) return compareKv(arena, e, prompts, o.max_tokens);
var seq = try e.sequence(o.context);
defer seq.deinit();
var mismatches: usize = 0;
Expand Down Expand Up @@ -105,6 +111,85 @@ pub fn main(init: std.process.Init) !u8 {
return if (mismatches == 0) 0 else 1;
}

/// The scratch's first logits row as fp64 log-probabilities.
fn logProbs(f: *qwen.Forward, bits: []u16, out: []f64) !void {
try f.ops.download(std.mem.sliceAsBytes(bits), f.s.logits);
try f.ops.s.synchronize();
var most: f64 = -std.math.inf(f64);
for (bits, out) |b, *x| {
x.* = @floatCast(@as(f32, @bitCast(@as(u32, b) << 16)));
most = @max(most, x.*);
}
var total: f64 = 0;
for (out) |x| total += @exp(x - most);
const log_total = most + @log(total);
for (out) |*x| x.* -= log_total;
}

fn argmaxOf(x: []const f64) u32 {
var best: usize = 0;
for (x, 0..) |v, i| if (v > x[best]) {
best = i;
};
return @intCast(best);
}

/// kvcompare: a bf16 stream and an fp8 one on each prompt, both fed bf16's greedy tokens; each step's top-1
/// agreement, KL(bf16 || fp8) and how much less log-probability fp8 gives bf16's pick.
fn compareKv(arena: std.mem.Allocator, e: *qwen.Engine, prompts: std.json.Value, steps: usize) !u8 {
const vocab = qwen.config.vocab;
const bits = try arena.alloc(u16, vocab);
const pa = try arena.alloc(f64, vocab);
const pb = try arena.alloc(f64, vocab);
var f = e.forward();
var it = prompts.object.iterator();
var all_agree: usize = 0;
var all_n: usize = 0;
while (it.next()) |entry| {
const ids = try tokenList(arena, entry.value_ptr.*);
const cap = ids.len + steps + 16;
e.kv8 = false;
var a = try e.sequence(cap);
defer a.deinit();
e.kv8 = true;
var b = try e.sequence(cap);
defer b.deinit();
e.kv8 = false;
var agree: usize = 0;
var kl_sum: f64 = 0;
var kl_most: f64 = 0;
var lp_sum: f64 = 0;
var tok: u32 = 0;
for (0..steps) |step| {
for ([_]*qwen.state.Seq{ &a, &b }, [_][]f64{ pa, pb }) |seq, out| {
if (step == 0) {
try e.prefill(seq, ids);
try f.head(seq);
} else {
const part = [_]qwen.Part{.{ .seq = seq, .tokens = &.{tok} }};
try f.round(&part);
try f.commit(&part, &.{&.{0}});
}
try logProbs(&f, bits, out);
}
const top_a = argmaxOf(pa);
if (top_a == argmaxOf(pb)) agree += 1;
var kl: f64 = 0;
for (pa, pb) |x, y| kl += @exp(x) * (x - y);
kl_sum += kl;
kl_most = @max(kl_most, kl);
lp_sum += pa[top_a] - pb[top_a];
tok = top_a;
}
const n: f64 = @floatFromInt(steps);
std.debug.print("{s}: prompt {d}, {d} steps: top-1 agree {d}/{d}, KL mean {d:.5} max {d:.5} nats, pick logprob gap {d:.5}\n", .{ entry.key_ptr.*, ids.len, steps, agree, steps, kl_sum / n, kl_most, lp_sum / n });
all_agree += agree;
all_n += steps;
}
std.debug.print("overall top-1 agree {d}/{d}\n", .{ all_agree, all_n });
return 0;
}

fn readJson(a: std.mem.Allocator, io: std.Io, path: []const u8) !std.json.Value {
const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 30));
return (try std.json.parseFromSliceLeaky(std.json.Value, a, bytes, .{}));
Expand Down
2 changes: 2 additions & 0 deletions zig/src/core/engine_api.zig
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,8 @@ pub const Open = struct {
policy: []const u8 = "",
/// --vision: load the checkpoint's image tower (null: text only; an engine without one refuses).
vision: ?VisionOpen = null,
/// --kv-cache fp8: attention caches as e4m3 with a scale a row (the CUDA Qwen3.8-27B engine only).
kv8: bool = false,
};

/// An opened engine; ``close`` stops its thread and frees its backend.
Expand Down
Loading
Loading