From 616fccaac431f90a47250ad357c77c5123f215d4 Mon Sep 17 00:00:00 2001 From: philip-pentatonic <63354535+philip-pentatonic@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:01:38 +0000 Subject: [PATCH 01/17] Lane core: requests that arrive together share their prompt passes The lane host admits every queued request at once: a lone one still goes to the backend's driver, the rest to the core's addStreams (lanes/admit.zig). It runs the backend's optional prefill_many when there is more than one, draws each stream's first token, then asks for every stream's first drafts in one request, as multi.py's _fill_batch admits a batch. addStream is its one-stream case, with the same calls in the same order; a backend without prefill_many prefills each stream as before. --- zig/src/core/lane_host.zig | 69 ++++++++++++++++++++------ zig/src/core/lanes/admit.zig | 90 ++++++++++++++++++++++++++++++++++ zig/src/core/lanes/backend.zig | 2 + zig/src/core/lanes/engine.zig | 66 +++++-------------------- zig/src/native/cuda.zig | 6 +++ 5 files changed, 166 insertions(+), 67 deletions(-) create mode 100644 zig/src/core/lanes/admit.zig diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index dc4e4db113..27dedfdc74 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -319,18 +319,60 @@ pub const LaneHost = struct { h.mutex.unlock(h.io); } - /// Prefills the next queued request into a free lane; false when none waits or no lane is free. - fn admitOne(h: *LaneHost) bool { + /// Every queued request the lanes have room for: a lone one to the backend's driver, the rest prefilled together. + fn admitAll(h: *LaneHost) void { + var batch: std.ArrayList(*Job) = .empty; + defer batch.deinit(h.gpa); + while (true) { + const job = switch (h.prepare()) { + .none => break, + .dropped => continue, + .job => |j| j, + }; + if (batch.items.len == 0 and h.loneFits(job)) { + _ = h.runLone(job, job.began); + continue; + } + batch.append(h.gpa, job) catch { + _ = h.drop(job, "out of memory"); + continue; + }; + } + if (batch.items.len == 0) return; + const streams = h.gpa.alloc(*lanes.Stream, batch.items.len) catch return h.dropAll(batch.items, "out of memory"); + defer h.gpa.free(streams); + const errs = h.gpa.alloc(?anyerror, batch.items.len) catch return h.dropAll(batch.items, "out of memory"); + defer h.gpa.free(errs); + for (streams, batch.items) |*s, job| s.* = &job.stream; + h.core.addStreams(streams, errs) catch |e| return h.dropAll(batch.items, h.words(e)); + for (batch.items, errs) |job, err| { + if (err) |e| { + _ = if (e == error.Cancelled) h.cancel(job) else h.drop(job, h.words(e)); + continue; + } + h.prefilled(job, job.began); + if (h.deliver(job)) h.remove(job); + } + } + + fn dropAll(h: *LaneHost, jobs: []const *Job, message: []const u8) void { + for (jobs) |job| _ = h.drop(job, message); + } + + const Prepared = union(enum) { none, dropped, job: *Job }; + + /// The oldest queued request admitted with its stream made, when the lanes have room. + fn prepare(h: *LaneHost) Prepared { h.lock(); if (h.queued.items.len == 0 or h.admitted.items.len >= h.info_.lanes) { h.unlock(); - return false; + return .none; } const job = h.queued.orderedRemove(0); h.admitted.append(h.gpa, job) catch { h.unlock(); h.finish(job, .failed, "out of memory"); - return true; + return .dropped; }; h.unlock(); const r = job.request; @@ -342,7 +384,10 @@ pub const LaneHost = struct { job.marks = l.marks; reuse = .{ .saved = if (l.entry) |e| e.saved else null, .at = if (l.entry) |e| e.at else 0, .marks = l.marks, .hook = .{ .ptr = job, .at = Job.kept } }; } else |_| {}; - job.proposer = lanes.SuffixLookup.init(h.gpa, .{ .min_match = h.min_match }) catch return h.drop(job, "the drafter could not start"); + job.proposer = lanes.SuffixLookup.init(h.gpa, .{ .min_match = h.min_match }) catch { + _ = h.drop(job, "the drafter could not start"); + return .dropped; + }; job.stream = lanes.Stream.init(h.gpa, .{ .id = "request", .prompt = r.prompt, @@ -362,16 +407,12 @@ pub const LaneHost = struct { .reuse = reuse, }) catch { job.proposer.deinit(); - return h.drop(job, "out of memory"); + _ = h.drop(job, "out of memory"); + return .dropped; }; job.started = true; - const began = std.Io.Clock.awake.now(h.io).toNanoseconds(); - job.began = began; - if (h.loneFits(job)) return h.runLone(job, began); - h.core.addStream(&job.stream) catch |e| return if (e == error.Cancelled) h.cancel(job) else h.drop(job, h.words(e)); - h.prefilled(job, began); - if (h.deliver(job)) h.remove(job); - return true; + job.began = std.Io.Clock.awake.now(h.io).toNanoseconds(); + return .{ .job = job }; } fn prefilled(h: *LaneHost, job: *Job, began: i96) void { @@ -480,7 +521,7 @@ pub const LaneHost = struct { fn run(h: *LaneHost) void { while (true) { h.takeCancels(); - while (h.admitOne()) {} + h.admitAll(); h.noteLive(); h.lock(); if (h.closing) { diff --git a/zig/src/core/lanes/admit.zig b/zig/src/core/lanes/admit.zig new file mode 100644 index 0000000000..37ec717b84 --- /dev/null +++ b/zig/src/core/lanes/admit.zig @@ -0,0 +1,90 @@ +//! Admitting streams: prompt passes (shared, as multi.py's _fill_batch), first tokens, then first drafts. +const std = @import("std"); +const be = @import("backend.zig"); +const ev = @import("events.zig"); +const win = @import("windows.zig"); +const trail = @import("trail.zig"); +const Engine = @import("engine.zig").Engine; +const Stream = @import("stream.zig").Stream; +const LogRow = @import("logprob.zig").Row; +const Feed = be.Feed; +const f = ev.f; +const str = trail.str; +const int = trail.int; + +/// Prompt passes (shared when the backend has them), first tokens, every stream's first drafts; failures in `errs`. +pub fn streams(e: *Engine, list: []const *Stream, errs: []?anyerror) !void { + _ = e.arena.reset(.retain_capacity); + const a = e.arena.allocator(); + @memset(errs, null); + for (list) |s| try trail.event(e, &.{ f("ev", str("add")), f("stream", str(s.id)) }); + if (list.len > 1 and e.backend.vtable.prefill_many != null) { + try e.backend.vtable.prefill_many.?(e.backend.ptr, list, errs); + } else for (list, errs) |s, *err| e.backend.prefill(s) catch |x| { + err.* = x; + }; + const feeds = try a.alloc(Feed, list.len); + const drawn = try a.alloc(u64, list.len); + const asked = try a.alloc(?u32, list.len); + var requests: std.ArrayList(be.DraftRequest) = .empty; + for (list, errs, feeds, drawn, asked) |s, *err, *feed, *handle, *ask| { + ask.* = null; + if (err.*) |x| { + if (x == error.Cancelled) e.backend.release(s); // the host finishes a cancelled stream without the core + continue; + } + if (s.isCancelled()) { // cancelled in its last chunk: no first token + e.backend.release(s); + err.* = error.Cancelled; + continue; + } + s.context.shrinkRetainingCapacity(s.prompt_len); + s.rows.clearRetainingCapacity(); + s.pending = null; + s.cache_len = s.prompt_len; + const position: u64 = s.prompt_len; + handle.* = e.backend.first(s, position) catch |x| { + err.* = x; // the host discards it, as after a failed prompt pass + continue; + }; + feed.* = .{ .handle = handle.* }; + if (try e.forcedNext(s)) |t| feed.* = .{ .value = t }; + if (e.cfg.family_mtp and s.drafts) { + // the head reads the prompt's last row and the first token, and drafts the one after it + const d: u32 = @intCast(try e.rule.depth(win.who(s))); + ask.* = d; + try requests.append(a, .{ .stream = s, .follow = &.{}, .first = feed.*, .rows = null, .start = s.prompt_len, .position = position + 1, .depth = d }); + } else if (e.cfg.pipelined and s.logprobs == null) { + try e.queueNext(s, feed.*); + } + } + if (requests.items.len > 0) try e.backend.draft(requests.items); + for (list, errs, feeds, drawn, asked) |s, err, feed, handle, ask| { + if (err != null) continue; + const position: u64 = s.prompt_len; + if (ask) |d| { + s.dropHeld(e.gpa); + s.next = .{ .count = d }; + if (e.backend.vtable.tree) |tree| if (try tree(e.backend.ptr, s, e.gpa)) |held| { + s.next = held; // a tree head's first drafts as host tokens, as every later round's + }; + } + const value = try e.readFeed(feed); + if (ask) |d| try trail.event(e, &.{ f("ev", str("draft")), f("stream", str(s.id)), f("depth", int(d)), f("position", int(position + 1)), f("follow", .{ .u32s = &.{value} }), f("rows", .null) }); + if (e.log != null) { + const first = if (feed == .handle) value else try e.backend.read(handle); + try trail.event(e, &.{ f("ev", str("first")), f("stream", str(s.id)), f("position", int(position)), f("drawn", int(first)), f("token", int(value)) }); + } + var first_row: [1]LogRow = undefined; + if (s.logprobs != null) first_row[0] = (try e.backend.firstRow(s)).forToken(value); + _ = try s.commit(e.gpa, &.{value}, if (s.logprobs != null) &first_row else &.{}); + s.pending = value; + try trail.resolve(e); + if (s.finished) { + try trail.finish(e, s); + e.release(s); + continue; + } + try e.live.append(e.gpa, s); + } +} diff --git a/zig/src/core/lanes/backend.zig b/zig/src/core/lanes/backend.zig index a10ced8675..c50ca6b10d 100644 --- a/zig/src/core/lanes/backend.zig +++ b/zig/src/core/lanes/backend.zig @@ -65,6 +65,8 @@ pub const Backend = struct { pub const VTable = struct { /// Prefill the stream's prompt into its caches (and its draft head's). prefill: *const fn (ptr: *anyopaque, s: *Stream) anyerror!void, + /// Prefill several streams in shared passes, each with `prefill`'s bits; `errs[i]` for a failure. + prefill_many: ?*const fn (ptr: *anyopaque, streams: []const *Stream, errs: []?anyerror) anyerror!void = null, /// Draw the first token from the prompt's last row at `position`; a handle to it. first: *const fn (ptr: *anyopaque, s: *Stream, position: u64) anyerror!u64, /// Feed one token and queue the draw of the next at `position` (a one-token round); a handle to it. diff --git a/zig/src/core/lanes/engine.zig b/zig/src/core/lanes/engine.zig index b752d84e85..f2ad1fd57f 100644 --- a/zig/src/core/lanes/engine.zig +++ b/zig/src/core/lanes/engine.zig @@ -12,6 +12,7 @@ const shape = @import("shape.zig"); const plan_lanes = @import("plan_lanes.zig"); const fill = @import("fill.zig"); const trail = @import("trail.zig"); +const admit = @import("admit.zig"); const Stream = sm.Stream; const Feed = be.Feed; const LogRow = @import("logprob.zig").Row; @@ -78,55 +79,14 @@ pub const Engine = struct { /// Prefill a stream, draw its first token and ask for its first drafts; it takes part from the next round. pub fn addStream(e: *Engine, s: *Stream) !void { - _ = e.arena.reset(.retain_capacity); - try trail.event(e, &.{ f("ev", str("add")), f("stream", str(s.id)) }); - e.backend.prefill(s) catch |err| { - if (err == error.Cancelled) e.backend.release(s); // the host finishes a cancelled stream without the core - return err; - }; - if (s.isCancelled()) { // cancelled in its last chunk: no first token - e.backend.release(s); - return error.Cancelled; - } - s.context.shrinkRetainingCapacity(s.prompt_len); - s.rows.clearRetainingCapacity(); - s.pending = null; - s.cache_len = s.prompt_len; - const position: u64 = s.prompt_len; - const drawn = try e.backend.first(s, position); - var feed: Feed = .{ .handle = drawn }; - if (try e.forcedNext(s)) |t| feed = .{ .value = t }; - var asked: ?u32 = null; - if (e.cfg.family_mtp and s.drafts) { - // the head reads the prompt's last row and the first token, and drafts the one after it - const d: u32 = @intCast(try e.rule.depth(win.who(s))); - asked = d; - try e.backend.draft(&.{.{ .stream = s, .follow = &.{}, .first = feed, .rows = null, .start = s.prompt_len, .position = position + 1, .depth = d }}); - s.dropHeld(e.gpa); - s.next = .{ .count = d }; - if (e.backend.vtable.tree) |tree| if (try tree(e.backend.ptr, s, e.gpa)) |held| { - s.next = held; // a tree head's first drafts as host tokens, as every later round's - }; - } else if (e.cfg.pipelined and s.logprobs == null) { - try e.queueNext(s, feed); - } - const value = try e.readFeed(feed); - if (asked) |d| try trail.event(e, &.{ f("ev", str("draft")), f("stream", str(s.id)), f("depth", int(d)), f("position", int(position + 1)), f("follow", .{ .u32s = &.{value} }), f("rows", .null) }); - if (e.log != null) { - const first = if (feed == .handle) value else try e.backend.read(drawn); - try trail.event(e, &.{ f("ev", str("first")), f("stream", str(s.id)), f("position", int(position)), f("drawn", int(first)), f("token", int(value)) }); - } - var first_row: [1]LogRow = undefined; - if (s.logprobs != null) first_row[0] = (try e.backend.firstRow(s)).forToken(value); - _ = try s.commit(e.gpa, &.{value}, if (s.logprobs != null) &first_row else &.{}); - s.pending = value; - try trail.resolve(e); - if (s.finished) { - try trail.finish(e, s); - e.release(s); - return; - } - try e.live.append(e.gpa, s); + var errs = [_]?anyerror{null}; + try e.addStreams(&.{s}, &errs); + if (errs[0]) |err| return err; + } + + /// addStream for several streams, their prompt passes shared (admit.zig). + pub fn addStreams(e: *Engine, streams: []const *Stream, errs: []?anyerror) !void { + return admit.streams(e, streams, errs); } /// A stream another driver prefilled and drew `token` for: drafts asked, the token committed, rounds from here. @@ -568,7 +528,7 @@ pub const Engine = struct { } /// Feed a token and queue the draw of the next at the new cache length. - fn queueNext(e: *Engine, s: *Stream, feed: Feed) !void { + pub fn queueNext(e: *Engine, s: *Stream, feed: Feed) !void { s.cache_len += 1; const h = try e.backend.queue(s, feed, s.cache_len); s.inflight = h; @@ -579,20 +539,20 @@ pub const Engine = struct { } /// The thinking budget's or a forced fix's token at the next position instead of the draw. - fn forcedNext(e: *Engine, s: *Stream) !?u32 { + pub fn forcedNext(e: *Engine, s: *Stream) !?u32 { if (s.popForce()) |t| return t; if (s.cutsNext()) return try s.startClose(e.gpa); return null; } - fn readFeed(e: *Engine, feed: Feed) !u32 { + pub fn readFeed(e: *Engine, feed: Feed) !u32 { return switch (feed) { .handle => |h| try e.backend.read(h), .value => |v| v, }; } - fn release(e: *Engine, s: *Stream) void { + pub fn release(e: *Engine, s: *Stream) void { s.dropRoundState(e.gpa); e.backend.release(s); } diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 668bd82c4b..296aa21409 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -248,6 +248,12 @@ const Host = struct { return x.inner.vtable.prefill(x.inner.ptr, s); } }.f, + .prefill_many = if (v.prefill_many != null) struct { + fn f(p: *anyopaque, streams: []const *lanes.Stream, errs: []?anyerror) anyerror!void { + const x = bind(p); + return x.inner.vtable.prefill_many.?(x.inner.ptr, streams, errs); + } + }.f else null, .first = struct { fn f(p: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { const x = bind(p); From 82d87215b015bf132808c9cffa07abfea11c87fe Mon Sep 17 00:00:00 2001 From: philip-pentatonic <63354535+philip-pentatonic@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:01:38 +0000 Subject: [PATCH 02/17] Nemotron: the checkpoint Source copies to a Target, so other CUDA families share it Source needed Nemotron's kernel handles only for the driver, the stream and whether the card is discrete; it now takes those as a Target (Target.of(ops) for Nemotron's own loader). cuda.zig exports the source module and the torch ops for the 27B's CUDA engine. --- zig/src/families/nemotron/cuda.zig | 4 ++++ zig/src/families/nemotron/cuda_source.zig | 26 ++++++++++++++++------ zig/src/families/nemotron/cuda_weights.zig | 2 +- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/zig/src/families/nemotron/cuda.zig b/zig/src/families/nemotron/cuda.zig index 7177181a4d..5bb9a91c96 100644 --- a/zig/src/families/nemotron/cuda.zig +++ b/zig/src/families/nemotron/cuda.zig @@ -26,6 +26,10 @@ pub const train = @import("cuda_train.zig"); pub const train_ops = @import("cuda_train_ops.zig"); pub const sites = @import("cuda_sites.zig"); pub const slide_dims = @import("slide_dims.zig"); +/// Checkpoint bytes to the GPU with direct reads in flight: shared with the other CUDA families. +pub const source = @import("cuda_source.zig"); +/// The torch-op replacements (argmax, topk, casts): shared with the other CUDA families. +pub const torch_ops = @import("cuda_torch_ops.zig"); test { _ = @import("config.zig"); diff --git a/zig/src/families/nemotron/cuda_source.zig b/zig/src/families/nemotron/cuda_source.zig index ffc4ba2eec..dcf89a40d4 100644 --- a/zig/src/families/nemotron/cuda_source.zig +++ b/zig/src/families/nemotron/cuda_source.zig @@ -33,9 +33,20 @@ const Job = struct { } }; +/// Where a Source's copies go: the driver, the stream, and whether the card has its own memory. +pub const Target = struct { + d: *const cuda.Driver, + s: cuda.Stream, + discrete: bool, + + pub fn of(ops: kern.Ops) Target { + return .{ .d = ops.k.d, .s = ops.s, .discrete = ops.k.discrete }; + } +}; + pub const Source = struct { gpa: std.mem.Allocator, - ops: kern.Ops, + ops: Target, files: std.ArrayList(Mapped) = .empty, slots: [slot_count]dio.Buffer = undefined, pinned: [slot_count]?cuda.HostBuffer = @splat(null), // a discrete card's slots, page-locked: copies run at the link's speed @@ -48,21 +59,21 @@ pub const Source = struct { next: u64 = 0, /// Page-aligned slots; on a discrete card page-locked, each with an event its copies record. - pub fn init(gpa: std.mem.Allocator, ops: kern.Ops) !Source { + pub fn init(gpa: std.mem.Allocator, ops: Target) !Source { var s: Source = .{ .gpa = gpa, .ops = ops }; var made: usize = 0; errdefer s.freeSlots(made); while (made < slot_count) : (made += 1) { - if (!ops.k.discrete) { + if (!ops.discrete) { s.slots[made] = try gpa.alignedAlloc(u8, .fromByteUnits(dio.alignment), slot_bytes); continue; } - var h = try cuda.HostBuffer.alloc(ops.k.d, slot_bytes); + var h = try cuda.HostBuffer.alloc(ops.d, slot_bytes); if (@intFromPtr(h.bytes.ptr) % dio.alignment != 0) { h.free(); return error.UnalignedPinnedSlot; } - s.copied[made] = cuda.Event.init(ops.k.d, false) catch |err| { + s.copied[made] = cuda.Event.init(ops.d, false) catch |err| { h.free(); return err; }; @@ -126,7 +137,8 @@ pub const Source = struct { pub fn upload(s: *Source, dst: u64, bytes: []const u8) !void { const at = s.locate(bytes) orelse { try s.flush(); - return s.ops.upload(dst, bytes); + if (bytes.len == 0) return; + return s.ops.d.check(s.ops.d.api.cuMemcpyHtoDAsync_v2(dst, bytes.ptr, bytes.len, s.ops.s.handle), "cuMemcpyHtoDAsync"); }; var done: usize = 0; while (done < bytes.len) { @@ -212,7 +224,7 @@ pub const Source = struct { /// Page-locked slots record their copy event; pageable slots wait for the driver to stage their bytes. fn finish(s: *Source, k: usize, p: Pending, got: []u8) !void { if (got.len == 0) return; - try s.ops.k.d.check(s.ops.k.d.api.cuMemcpyHtoDAsync_v2(p.dst, got.ptr, got.len, s.ops.s.handle), "cuMemcpyHtoDAsync"); + try s.ops.d.check(s.ops.d.api.cuMemcpyHtoDAsync_v2(p.dst, got.ptr, got.len, s.ops.s.handle), "cuMemcpyHtoDAsync"); if (s.copied[k]) |e| return e.record(s.ops.s); try s.ops.s.synchronize(); } diff --git a/zig/src/families/nemotron/cuda_weights.zig b/zig/src/families/nemotron/cuda_weights.zig index e3a6f64385..0319ba41e9 100644 --- a/zig/src/families/nemotron/cuda_weights.zig +++ b/zig/src/families/nemotron/cuda_weights.zig @@ -352,7 +352,7 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, ops: kern.Ops, dir: []const u8, if (c.group_size != 64 or c.bits != 4) return error.UnsupportedQuantization; var w: Weights = .{ .gpa = gpa, .config = c }; errdefer w.deinit(); - var src = try Source.init(gpa, ops); + var src = try Source.init(gpa, .of(ops)); defer src.deinit(); var L: Loader = .{ .gpa = gpa, .ops = ops, .w = &w, .src = &src, .scratch = try cuda.DeviceBuffer.alloc(ops.k.d, 1 << 20) }; defer { From 99bcc5b29805e29a4baf2cd4beade0f7fe1a5fe8 Mon Sep 17 00:00:00 2001 From: philip-pentatonic <63354535+philip-pentatonic@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:01:38 +0000 Subject: [PATCH 03/17] Qwen3.8-27B on CUDA: the qwen27 family's engine for NVIDIA GPUs, every stream drafted A qwen3_5 checkpoint with the 27B's shapes opens zig/src/families/qwen27/cuda in tensorfold-native, beside the family's Metal engine. It reads the family's config.zig and refuses other shapes (cuda/shape.zig). The forward is the Python 0.6.6 engine's: its CUDA kernels (qmm_group, qmm_prefill at prompt tile 9, the GDN tree, replay and prompt chain, prefill attention) built from zig/kernels/cuda, and its Triton glue from a set captured on the chip (TENSORFOLD_CUDA_KERNELS). Verify rounds take every stream's window together, up to 16 streams of 16 rows, as multi_tree_forward lays them out, and commit only each stream's accepted path. DFlash2 (--drafter, else the pulled z-lab/Qwen3.8-27B-DFlash2) drafts every stream in one batch: each stream's kept taps absorbed together, every block in one forward, a best-first tree per stream, or a copied continuation where the context repeats. The lane core verifies the trees and trims them by each node's chance against a cost curve timed at load. Prompts that arrive together share one prefill pass (prefill_rows). Checked against captures of the Python engine (zig/tests/cuda/qwen27), on an RTX PRO 6000 and on one DGX Spark (GB10): serial replies equal token for token (a 4722-token prompt among them); 54 verify windows (chains, trees, shared rounds of 2 to 16 streams and up to 256 rows, every alignment of the packed inputs) equal row for row in their logits' bytes; drafted replies and each stream's rounds equal Python's; served replies of 1, 4 and 16 concurrent requests, greedy and sampled, equal the same request alone and its "draft": false decode. --- zig/build/cuda.zig | 35 +- zig/kernels/cuda/gdn_prefill.cu | 150 +++++ zig/kernels/cuda/prefill_attention.cu | 3 + zig/kernels/cuda/qmm_group.cu | 7 + zig/kernels/cuda/qmm_prefill.cu | 4 + zig/kernels/cuda/qwen_ops.cu | 68 +++ zig/src/cli/qwen27_cuda.zig | 459 +++++++++++++++ zig/src/cuda/kernels.zig | 3 + zig/src/families/qwen27/cuda.zig | 33 ++ zig/src/families/qwen27/cuda/draft.zig | 423 ++++++++++++++ zig/src/families/qwen27/cuda/draft_load.zig | 274 +++++++++ zig/src/families/qwen27/cuda/draft_policy.zig | 122 ++++ zig/src/families/qwen27/cuda/drafts.zig | 103 ++++ zig/src/families/qwen27/cuda/engine.zig | 118 ++++ zig/src/families/qwen27/cuda/forward.zig | 436 ++++++++++++++ zig/src/families/qwen27/cuda/kernels.zig | 365 ++++++++++++ zig/src/families/qwen27/cuda/lanes.zig | 549 ++++++++++++++++++ zig/src/families/qwen27/cuda/lone.zig | 181 ++++++ zig/src/families/qwen27/cuda/native.zig | 111 ++++ zig/src/families/qwen27/cuda/round.zig | 230 ++++++++ zig/src/families/qwen27/cuda/shape.zig | 102 ++++ zig/src/families/qwen27/cuda/state.zig | 304 ++++++++++ zig/src/families/qwen27/cuda/tree.zig | 181 ++++++ zig/src/families/qwen27/cuda/triton.zig | 141 +++++ zig/src/families/qwen27/cuda/weights.zig | 252 ++++++++ zig/src/native/cuda.zig | 17 +- zig/tests/cuda/qwen27/capture.py | 208 +++++++ zig/tests/cuda/qwen27/capture_draft.py | 74 +++ zig/tests/cuda/qwen27/capture_multi.py | 108 ++++ zig/tests/cuda/qwen27/capture_windows.py | 143 +++++ 30 files changed, 5187 insertions(+), 17 deletions(-) create mode 100644 zig/kernels/cuda/gdn_prefill.cu create mode 100644 zig/kernels/cuda/qwen_ops.cu create mode 100644 zig/src/cli/qwen27_cuda.zig create mode 100644 zig/src/families/qwen27/cuda.zig create mode 100644 zig/src/families/qwen27/cuda/draft.zig create mode 100644 zig/src/families/qwen27/cuda/draft_load.zig create mode 100644 zig/src/families/qwen27/cuda/draft_policy.zig create mode 100644 zig/src/families/qwen27/cuda/drafts.zig create mode 100644 zig/src/families/qwen27/cuda/engine.zig create mode 100644 zig/src/families/qwen27/cuda/forward.zig create mode 100644 zig/src/families/qwen27/cuda/kernels.zig create mode 100644 zig/src/families/qwen27/cuda/lanes.zig create mode 100644 zig/src/families/qwen27/cuda/lone.zig create mode 100644 zig/src/families/qwen27/cuda/native.zig create mode 100644 zig/src/families/qwen27/cuda/round.zig create mode 100644 zig/src/families/qwen27/cuda/shape.zig create mode 100644 zig/src/families/qwen27/cuda/state.zig create mode 100644 zig/src/families/qwen27/cuda/tree.zig create mode 100644 zig/src/families/qwen27/cuda/triton.zig create mode 100644 zig/src/families/qwen27/cuda/weights.zig create mode 100644 zig/tests/cuda/qwen27/capture.py create mode 100644 zig/tests/cuda/qwen27/capture_draft.py create mode 100644 zig/tests/cuda/qwen27/capture_multi.py create mode 100644 zig/tests/cuda/qwen27/capture_windows.py diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 5602af1007..676bda8c88 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -13,6 +13,7 @@ const glue = &[_][]const u8{ "-O3", "--fmad=false", "--ftz=false", "--prec-div=t const kernels = [_]Kernel{ .{ .name = "gdn", .flags = &.{ "-O3", "--fmad=false" } }, // cuda/kernels/gdn.py, tensorfold_gdn_v2 + .{ .name = "gdn_prefill", .flags = &.{ "-O3", "--fmad=false" } }, // the same extension's prompt chain .{ .name = "probe", .flags = &.{"-O3"} }, .{ .name = "qmm_group", .flags = &.{"-O3"} }, // cuda/kernels/qmm.py, tensorfold_qmm_v5 .{ .name = "qmm_prefill", .flags = &.{"-O3"} }, @@ -25,6 +26,7 @@ const kernels = [_]Kernel{ .{ .name = "affine4_pack", .flags = &.{"-O3"} }, // ours: the MLX affine-4 repack into qlinear's tiles .{ .name = "lane_gemv", .flags = &.{"-O3"} }, // ours: qmm_group's arithmetic, a column tile's K slices in one CTA .{ .name = "sample", .flags = &.{ "-O3", "--fmad=false", "--ftz=false" } }, // ours: the Metal engine's keyed draws + .{ .name = "qwen_ops", .flags = &.{"-O3"} }, // ours: the 27B's batched state copies, taps, drafter norms and rotary .{ .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 }, @@ -39,6 +41,7 @@ const kernels = [_]Kernel{ .{ .name = "torch_indexing", .src = "torch_ops/indexing", .flags = torch_ops }, .{ .name = "torch_movement", .src = "torch_ops/movement", .flags = torch_ops }, .{ .name = "torch_nemotron_constants", .src = "torch_ops/nemotron_constants", .flags = torch_ops }, + .{ .name = "torch_norm_rotary", .src = "torch_ops/norm_rotary", .flags = torch_ops }, // F.rms_norm of 5120 columns }; /// torch.utils.cpp_extension's own nvcc flags (torch 2.13): C++20 and which half/bf16 operators the headers define. @@ -69,7 +72,7 @@ fn runtime(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builti return cuda; } -fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, draft_ids: *std.Build.Module) struct { core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, tokenizer: *std.Build.Module, heat: *std.Build.Module } { +fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, draft_ids: *std.Build.Module) struct { core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, qwen27: *std.Build.Module, tokenizer: *std.Build.Module, heat: *std.Build.Module } { const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }); const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); core.addImport("tokenizer", tokenizer); @@ -81,7 +84,13 @@ fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin nemotron.addImport("lanes", lanes); nemotron.addImport("heat", heat); nemotron.addImport("nemotron_draft_ids", draft_ids); - return .{ .core = core, .lanes = lanes, .nemotron = nemotron, .tokenizer = tokenizer, .heat = heat }; + // the 27B's CUDA engine, beside its Metal one in the family's folder (it reads the family's config.zig) + const qwen27 = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen27/cuda.zig"), .target = target, .optimize = optimize, .link_libc = true }); + qwen27.addImport("cuda", cuda); + qwen27.addImport("core", core); + qwen27.addImport("lanes", lanes); + qwen27.addImport("nemotron", nemotron); // the checkpoint Source and torch ops the CUDA families share + return .{ .core = core, .lanes = lanes, .nemotron = nemotron, .qwen27 = qwen27, .tokenizer = tokenizer, .heat = heat }; } /// Linux targets: fatbins (-Dnvcc builds them, -Dfatbins embeds prebuilt ones), `tensorfold` and `tf-cuda-test`. @@ -113,7 +122,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu cli.addImport("core", mods.core); cli.addImport("lanes", mods.lanes); cli.addImport("nemotron", mods.nemotron); - const native = engines(b, target, optimize, cuda, mods.lanes, mods.nemotron); + const native = engines(b, target, optimize, cuda, mods.lanes, mods.nemotron, mods.qwen27); cli.addOptions("build_options", build_options); cli.addImport("checkpoint_cli", checkpointCli(b, target, optimize, strip, native.engines)); b.installArtifact(b.addExecutable(.{ .name = "tensorfold", .root_module = cli })); @@ -122,18 +131,22 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu runner.addImport("lanes", mods.lanes); runner.addImport("nemotron", mods.nemotron); b.installArtifact(b.addExecutable(.{ .name = "tf-cuda-test", .root_module = runner })); - nativeServer(b, target, optimize, cuda, mods.lanes, mods.nemotron, mods.tokenizer, build_options, true).root_module.strip = strip; + const qwen_cli = b.createModule(.{ .root_source_file = b.path("zig/src/cli/qwen27_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true }); + qwen_cli.addImport("cuda", cuda); + qwen_cli.addImport("qwen27", mods.qwen27); + b.installArtifact(b.addExecutable(.{ .name = "tf-qwen27-cuda", .root_module = qwen_cli })); + nativeServer(b, target, optimize, cuda, mods.lanes, mods.nemotron, mods.qwen27, mods.tokenizer, build_options, true).root_module.strip = strip; } /// The CUDA engines a native server opens (native/cuda.zig), over the given runtime and families. -fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module) struct { api: *std.Build.Module, engines: *std.Build.Module } { +fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, qwen27: *std.Build.Module) struct { api: *std.Build.Module, engines: *std.Build.Module } { const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); const mod = b.createModule(.{ .root_source_file = b.path("zig/src/native/cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "engine_api", .module = api }, .{ .name = "lanes", .module = lanes }, .{ .name = "nemotron", .module = nemotron } }, + .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "engine_api", .module = api }, .{ .name = "lanes", .module = lanes }, .{ .name = "nemotron", .module = nemotron }, .{ .name = "qwen27", .module = qwen27 } }, }); return .{ .api = api, .engines = mod }; } @@ -144,8 +157,8 @@ fn checkpointCli(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std. } /// `zig build native`: tensorfold-native with the CUDA engines into zig-out/native/bin, as the Metal build makes it. -fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, tokenizer: *std.Build.Module, build_options: *std.Build.Step.Options, install_native: bool) *std.Build.Step.Compile { - const m = engines(b, target, optimize, cuda, lanes, nemotron); +fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, qwen27: *std.Build.Module, tokenizer: *std.Build.Module, build_options: *std.Build.Step.Options, install_native: bool) *std.Build.Step.Compile { + const m = engines(b, target, optimize, cuda, lanes, nemotron, qwen27); // the HTTP side keeps its safety checks; the engine below it runs at `optimize` (the tokenizer is the family's) const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); const exe = b.addExecutable(.{ .name = "tensorfold-native", .root_module = b.createModule(.{ @@ -172,7 +185,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st const host = b.graph.host; const cuda = runtime(b, host, .debug, &.{}); const mods = family(b, host, .debug, cuda, draft_ids); - const native_modules = engines(b, host, .debug, cuda, mods.lanes, mods.nemotron); + const native_modules = engines(b, host, .debug, cuda, mods.lanes, mods.nemotron, mods.qwen27); const native = native_modules.engines; // the HTTP server's unit tests (zig/src/server/root.zig), which the macOS build runs, on Linux hosts too const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = host, .optimize = .debug, .link_libc = true }); @@ -186,7 +199,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st const server_test = b.addRunArtifact(b.addTest(.{ .root_module = server_tests })); step.dependOn(&server_test.step); b.step("test-server-cpu", "The HTTP server's unit tests (routes, templates, tool parsing) without a GPU").dependOn(&server_test.step); - for ([_]*std.Build.Module{ cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, native, stagger(b, host, .debug) }) |m| step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); + for ([_]*std.Build.Module{ cuda, mods.core, mods.lanes, mods.nemotron, mods.qwen27, mods.heat, native, stagger(b, host, .debug) }) |m| step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); const cli = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cuda_main.zig"), .target = host, .optimize = .debug, .link_libc = true }); cli.addImport("cuda", cuda); cli.addImport("core", mods.core); @@ -222,7 +235,7 @@ pub fn distServer(b: *std.Build, target: std.Build.ResolvedTarget, draft_ids: *s }; const cuda = runtime(b, target, .fast, if (prebuilt != null) &images else &.{}); const mods = family(b, target, .fast, cuda, draft_ids); - return nativeServer(b, target, .fast, cuda, mods.lanes, mods.nemotron, mods.tokenizer, build_options, false); + return nativeServer(b, target, .fast, cuda, mods.lanes, mods.nemotron, mods.qwen27, mods.tokenizer, build_options, false); } /// Validate the complete named input set, including images unused by today's server. diff --git a/zig/kernels/cuda/gdn_prefill.cu b/zig/kernels/cuda/gdn_prefill.cu new file mode 100644 index 0000000000..a892ad52d7 --- /dev/null +++ b/zig/kernels/cuda/gdn_prefill.cu @@ -0,0 +1,150 @@ +// Device code of src/tensorfold/cuda/kernels/gdn_prefill.cu (lines 1-145, comments and ATen includes dropped). + +#include +#include +#include + +namespace tf_gdn_prefill { + +constexpr int DK = 128; +constexpr int DV = 128; + +__device__ __forceinline__ float4 widen(uint2 w) { + const __nv_bfloat162 a = *reinterpret_cast(&w.x); + const __nv_bfloat162 b = *reinterpret_cast(&w.y); + return make_float4(__low2float(a), __high2float(a), __low2float(b), __high2float(b)); +} + +__device__ __forceinline__ float4 widen(float4 w) { return w; } + +template +struct Prefetch { + using Raw = typename std::conditional::value, float4, uint2>::type; + static constexpr int KQ = STEPS * (DK / 4) / THREADS, VV = STEPS * ROWS / 8 / THREADS; + static_assert(KQ * THREADS == STEPS * (DK / 4) && VV * THREADS * 8 == STEPS * ROWS, "whole slots a thread"); + Raw kr[KQ], qr[KQ]; + uint4 vr[VV]; + float gr, br; + + __device__ __forceinline__ void fetch(const QK* q, const QK* k, const __nv_bfloat16* v, const float* g, + const float* beta, int t0, int W, int hk, int hv, int head, int key_head, + int col0) { +#pragma unroll + for (int it = 0; it < KQ; ++it) { + const int i = threadIdx.x + it * THREADS, st = i / (DK / 4), c = i % (DK / 4); + const size_t at = (static_cast(min(t0 + st, W - 1)) * hk + key_head) * DK + 4 * c; + kr[it] = *reinterpret_cast(k + at); + qr[it] = *reinterpret_cast(q + at); + } +#pragma unroll + for (int it = 0; it < VV; ++it) { + const int i = threadIdx.x + it * THREADS, st = i / (ROWS / 8), c = i % (ROWS / 8); + vr[it] = *reinterpret_cast(v + (static_cast(min(t0 + st, W - 1)) * hv + head) * DV + + col0 + 8 * c); + } + if (threadIdx.x < STEPS) { + const size_t at = static_cast(min(t0 + static_cast(threadIdx.x), W - 1)) * hv + head; + gr = g[at]; + br = beta[at]; + } + } + + __device__ __forceinline__ void store(float4 (*ks)[DK / 4], float4 (*qs)[DK / 4], float* gs, float* bs, + __nv_bfloat16 (*vs)[ROWS]) const { +#pragma unroll + for (int it = 0; it < KQ; ++it) { + const int i = threadIdx.x + it * THREADS; + ks[i / (DK / 4)][i % (DK / 4)] = widen(kr[it]); + qs[i / (DK / 4)][i % (DK / 4)] = widen(qr[it]); + } +#pragma unroll + for (int it = 0; it < VV; ++it) { + const int i = threadIdx.x + it * THREADS; + *reinterpret_cast(&vs[i / (ROWS / 8)][8 * (i % (ROWS / 8))]) = vr[it]; + } + if (threadIdx.x < STEPS) { + gs[threadIdx.x] = gr; + bs[threadIdx.x] = br; + } + } +}; + +template +__global__ void __launch_bounds__(2 * ROWS) chain_kernel( + const QK* __restrict__ q, const QK* __restrict__ k, const __nv_bfloat16* __restrict__ v, + const float* __restrict__ g, const float* __restrict__ beta, const float* __restrict__ state, + float* __restrict__ last, __nv_bfloat16* __restrict__ y, int W, int hk, int hv) { + __shared__ float4 ks[STEPS][DK / 4], qs[STEPS][DK / 4]; + __shared__ float gs[STEPS], bs[STEPS]; + __shared__ __align__(16) __nv_bfloat16 vs[STEPS][ROWS]; + const int head = blockIdx.x, row = blockIdx.y * ROWS + (threadIdx.x >> 1), half = threadIdx.x & 1; + const int key_head = head / (hv / hk); + float s[64]; + const float* s0 = state + (static_cast(head) * DV + row) * DK; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const float4 t = *reinterpret_cast(s0 + 8 * j + 4 * half); + s[4 * j] = t.x; s[4 * j + 1] = t.y; s[4 * j + 2] = t.z; s[4 * j + 3] = t.w; + } + Prefetch pf; // each stage's loads in flight during the one before + pf.fetch(q, k, v, g, beta, 0, W, hk, hv, head, key_head, blockIdx.y * ROWS); + for (int t0 = 0; t0 < W; t0 += STEPS) { + const int n = min(STEPS, W - t0); + __syncthreads(); + pf.store(ks, qs, gs, bs, vs); + __syncthreads(); + if (t0 + STEPS < W) pf.fetch(q, k, v, g, beta, t0 + STEPS, W, hk, hv, head, key_head, blockIdx.y * ROWS); + for (int tt = 0; tt < n; ++tt) { + const float gt = gs[tt], bt = bs[tt]; + const size_t vat = (static_cast(t0 + tt) * hv + head) * DV + row; + const float vt = __bfloat162float(vs[tt][threadIdx.x >> 1]); + float m[4] = {0.0f, 0.0f, 0.0f, 0.0f}; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const float4 kk = ks[tt][2 * j + half]; + s[4 * j] = s[4 * j] * gt; + s[4 * j + 1] = s[4 * j + 1] * gt; + s[4 * j + 2] = s[4 * j + 2] * gt; + s[4 * j + 3] = s[4 * j + 3] * gt; + m[0] = __fmaf_rn(s[4 * j], kk.x, m[0]); + m[1] = __fmaf_rn(s[4 * j + 1], kk.y, m[1]); + m[2] = __fmaf_rn(s[4 * j + 2], kk.z, m[2]); + m[3] = __fmaf_rn(s[4 * j + 3], kk.w, m[3]); + } + float mem = (m[0] + m[1]) + (m[2] + m[3]); + mem = mem + __shfl_xor_sync(0xffffffffu, mem, 1); + const float delta = (vt - mem) * bt; + float o[4] = {0.0f, 0.0f, 0.0f, 0.0f}; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const float4 kk = ks[tt][2 * j + half], qq = qs[tt][2 * j + half]; + s[4 * j] = __fmaf_rn(kk.x, delta, s[4 * j]); + s[4 * j + 1] = __fmaf_rn(kk.y, delta, s[4 * j + 1]); + s[4 * j + 2] = __fmaf_rn(kk.z, delta, s[4 * j + 2]); + s[4 * j + 3] = __fmaf_rn(kk.w, delta, s[4 * j + 3]); + o[0] = __fmaf_rn(s[4 * j], qq.x, o[0]); + o[1] = __fmaf_rn(s[4 * j + 1], qq.y, o[1]); + o[2] = __fmaf_rn(s[4 * j + 2], qq.z, o[2]); + o[3] = __fmaf_rn(s[4 * j + 3], qq.w, o[3]); + } + float out = (o[0] + o[1]) + (o[2] + o[3]); + out = out + __shfl_xor_sync(0xffffffffu, out, 1); + if (half == 0) y[vat] = __float2bfloat16_rn(out); + } + } + float* s1 = last + (static_cast(head) * DV + row) * DK; +#pragma unroll + for (int j = 0; j < 16; ++j) + *reinterpret_cast(s1 + 8 * j + 4 * half) = make_float4(s[4 * j], s[4 * j + 1], s[4 * j + 2], + s[4 * j + 3]); +} + +} // namespace tf_gdn_prefill + +// The instantiations gdn_prefill_cuda launches for bf16 keys: 128 value rows a block, or 64 when heads < SMs. +template __global__ void tf_gdn_prefill::chain_kernel<__nv_bfloat16, 128, 32>(const __nv_bfloat16*, + const __nv_bfloat16*, const __nv_bfloat16*, const float*, const float*, const float*, float*, __nv_bfloat16*, int, + int, int); +template __global__ void tf_gdn_prefill::chain_kernel<__nv_bfloat16, 64, 32>(const __nv_bfloat16*, + const __nv_bfloat16*, const __nv_bfloat16*, const float*, const float*, const float*, float*, __nv_bfloat16*, int, + int, int); diff --git a/zig/kernels/cuda/prefill_attention.cu b/zig/kernels/cuda/prefill_attention.cu index 122f404495..cd9a012fc3 100644 --- a/zig/kernels/cuda/prefill_attention.cu +++ b/zig/kernels/cuda/prefill_attention.cu @@ -243,3 +243,6 @@ pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restric // Head dim 128, eight warps, eight query heads a block, eight staging slots (Nemotron's 16 heads a KV head). template __global__ void tf_prefill_attention::pattn_kernel<128, 8, 8, 8>(const __nv_bfloat16*, const __nv_bfloat16*, const __nv_bfloat16*, __nv_bfloat16*, int, int, int, int, int, float); +// 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); diff --git a/zig/kernels/cuda/qmm_group.cu b/zig/kernels/cuda/qmm_group.cu index f3f65e184f..9c97ddfa71 100644 --- a/zig/kernels/cuda/qmm_group.cu +++ b/zig/kernels/cuda/qmm_group.cu @@ -339,3 +339,10 @@ __global__ void __launch_bounds__(WM * WN * 32) group_kernel( // The instantiations Nemotron's windows launch on sm_121 (tile 2: rows <= 16, bf16 out). template __global__ void tf_qmm_group::group_kernel<64, 16, 64, 1, 4, 8, false, false, false, false>( const __nv_bfloat16*, const float*, const __grid_constant__ tf_qmm_group::Parts, int, int, int, int, int); +// Tiles 3-5 (rows <= 32, <= 64, more), which a GB10 takes for wider verify rounds; tiles never change bits. +template __global__ void tf_qmm_group::group_kernel<64, 32, 64, 1, 4, 4, false, false, false, false>( + const __nv_bfloat16*, const float*, const __grid_constant__ tf_qmm_group::Parts, int, int, int, int, int); +template __global__ void tf_qmm_group::group_kernel<64, 64, 64, 1, 4, 4, false, false, false, false>( + const __nv_bfloat16*, const float*, const __grid_constant__ tf_qmm_group::Parts, int, int, int, int, int); +template __global__ void tf_qmm_group::group_kernel<64, 64, 128, 2, 4, 3, false, false, false, false>( + const __nv_bfloat16*, const float*, const __grid_constant__ tf_qmm_group::Parts, int, int, int, int, int); diff --git a/zig/kernels/cuda/qmm_prefill.cu b/zig/kernels/cuda/qmm_prefill.cu index 1610b22704..b90d3eb2af 100644 --- a/zig/kernels/cuda/qmm_prefill.cu +++ b/zig/kernels/cuda/qmm_prefill.cu @@ -151,3 +151,7 @@ __global__ void __launch_bounds__(WM * WN * 32) prefill_kernel( template __global__ void tf_qmm_prefill::prefill_kernel<64, 128, 128, 2, 4, 3, false>( const __nv_bfloat16*, const uint32_t*, const __nv_bfloat16*, const __nv_bfloat16*, void*, int, int, int, int, int, int); +// prompt_tile 9 (the 27B's: 128x128 on 2x2 warps, 2 stages, two blocks an SM on a GB10), bf16 out. +template __global__ void tf_qmm_prefill::prefill_kernel<64, 128, 128, 2, 2, 2, false>( + const __nv_bfloat16*, const uint32_t*, const __nv_bfloat16*, const __nv_bfloat16*, void*, int, int, int, + int, int, int); diff --git a/zig/kernels/cuda/qwen_ops.cu b/zig/kernels/cuda/qwen_ops.cu new file mode 100644 index 0000000000..778cc1f16e --- /dev/null +++ b/zig/kernels/cuda/qwen_ops.cu @@ -0,0 +1,68 @@ +// The 27B's own small kernels: batched state copies, the drafter's taps and its fp32 RMSNorm. +#include +#include + +struct TfCopy { + unsigned long long dst, src, bytes; // 16-byte aligned pointers, bytes a multiple of 16 +}; + +// One block an item, its threads striding through the item's 16-byte words. +extern "C" __global__ void __launch_bounds__(256) tf_copy_batch(const TfCopy* __restrict__ items) { + const TfCopy it = items[blockIdx.x]; + const uint4* src = reinterpret_cast(it.src); + uint4* dst = reinterpret_cast(it.dst); + const unsigned long long n = it.bytes / 16; + for (unsigned long long i = threadIdx.x + static_cast(blockIdx.y) * blockDim.x; i < n; + i += static_cast(blockDim.x) * gridDim.y) + dst[i] = src[i]; +} + +// 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, + __nv_bfloat16* __restrict__ out, int D, int out_stride, int col) { + const long long row = blockIdx.x; + for (int i = threadIdx.x + blockIdx.y * blockDim.x; i < D; i += blockDim.x * gridDim.y) + out[row * out_stride + col + i] = + __float2bfloat16_rn(__bfloat162float(x[row * D + i]) + __bfloat162float(pending[row * D + i])); +} + +// The drafter's RMSNorm in fp32: y = bf16(x * rsqrt(mean(x^2) + eps) * w), a 256-thread block a row. +extern "C" __global__ void __launch_bounds__(256) tf_rms_norm(const __nv_bfloat16* __restrict__ x, int x_stride, + const __nv_bfloat16* __restrict__ w, + __nv_bfloat16* __restrict__ y, int D, float eps) { + __shared__ float part[8]; + const long long row = blockIdx.x; + const __nv_bfloat16* xr = x + row * x_stride; + float s = 0.0f; + for (int i = threadIdx.x; i < D; i += 256) { + const float v = __bfloat162float(xr[i]); + s += v * v; + } + for (int off = 16; off > 0; off >>= 1) s += __shfl_xor_sync(0xFFFFFFFFu, s, off); + if ((threadIdx.x & 31) == 0) part[threadIdx.x >> 5] = s; + __syncthreads(); + float total = 0.0f; + for (int k = 0; k < 8; ++k) total += part[k]; + const float inv = rsqrtf(total / D + eps); + for (int i = threadIdx.x; i < D; i += 256) + y[row * D + i] = __float2bfloat16_rn(__bfloat162float(xr[i]) * inv * __bfloat162float(w[i])); +} + +// The drafter's inverse frequencies as dflash2 makes them on the GPU: 1 / theta ** (2i / dim), fp32 powf then a divide. +extern "C" __global__ void tf_inv_freq(float* __restrict__ inv, float theta, int half, int dim) { + const int i = threadIdx.x; + if (i < half) inv[i] = 1.0f / powf(theta, static_cast(i) * 2.0f / static_cast(dim)); +} + +// dflash2._rotary and add_taps_streams' tables: cos and sin of float(position) * inv_freq, fp32, a block a row. +extern "C" __global__ void tf_rotary(const int* __restrict__ pos, const float* __restrict__ inv, + float* __restrict__ cos_out, float* __restrict__ sin_out, int half) { + const int row = blockIdx.x; + const float p = static_cast(pos[row]); + for (int i = threadIdx.x; i < half; i += blockDim.x) { + const float phase = p * inv[i]; + cos_out[row * half + i] = cosf(phase); + sin_out[row * half + i] = sinf(phase); + } +} diff --git a/zig/src/cli/qwen27_cuda.zig b/zig/src/cli/qwen27_cuda.zig new file mode 100644 index 0000000000..a92416ce7b --- /dev/null +++ b/zig/src/cli/qwen27_cuda.zig @@ -0,0 +1,459 @@ +//! tf-qwen27-cuda: the 27B's Zig CUDA engine against the Python engine's capture (prompts.json, results.json). + +const std = @import("std"); +const cuda = @import("cuda"); +const qwen = @import("qwen27"); + +const usage = + \\usage: tf-qwen27-cuda run MODEL --kernels DIR --prompts prompts.json [--expect results.json] + \\ [--max-tokens N] [--context N] [--device N] + \\ Greedy, drafts off: each prompt's tokens and their sha against the capture's. + \\ tf-qwen27-cuda windows MODEL --kernels DIR --prompts windows.json + \\ capture_windows.py's chains and shared rounds: each row's logits against the capture's sha256. + \\ tf-qwen27-cuda draft MODEL --kernels DIR --drafter DIR --prompts prompts.json [--expect draft.json] + \\ draft_decode with DFlash2, greedy: tokens (equal to serial) and rounds against capture_draft.py's. + \\ tf-qwen27-cuda rounds MODEL --kernels DIR --prompts windows.json [--max-tokens ROUNDS] + \\ 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. + \\ +; + +const Options = struct { + model: []const u8, + kernels: []const u8 = "", + prompts: []const u8 = "", + expect: ?[]const u8 = null, + max_tokens: usize = 128, + context: usize = 16384, + device: c_int = 0, + 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 +}; + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const arena = init.arena.allocator(); + const args = try init.minimal.args.toSlice(arena); + const windows = args.len >= 2 and std.mem.eql(u8, args[1], "windows"); + 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"); + if (args.len < 3 or !(std.mem.eql(u8, args[1], "run") or windows or rounds or drafting or multi)) { + std.debug.print("{s}", .{usage}); + return 2; + } + var o: Options = .{ .model = args[2] }; + var i: usize = 3; + 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 { + std.debug.print("unknown option {s}\n{s}", .{ k, usage }); + return 2; + } + } + if (o.kernels.len == 0 or o.prompts.len == 0) { + std.debug.print("{s}", .{usage}); + return 2; + } + const prompts = try readJson(arena, init.io, o.prompts); + const expect = if (o.expect) |p| try readJson(arena, init.io, p) else null; + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, o.device); + 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 }); + defer e.deinit(); + 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); + var seq = try e.sequence(o.context); + defer seq.deinit(); + var mismatches: usize = 0; + var it = prompts.object.iterator(); + while (it.next()) |entry| { + const name = entry.key_ptr.*; + const ids = try tokenList(arena, entry.value_ptr.*); + var out: std.ArrayList(u32) = .empty; + defer out.deinit(gpa); + t0 = clock.now(init.io).toNanoseconds(); + try e.generate(&seq, ids, o.max_tokens, &out); + const seconds = @as(f64, @floatFromInt(clock.now(init.io).toNanoseconds() - t0)) / 1e9; + const sha = try sha12(arena, out.items); + var verdict: []const u8 = ""; + if (expect) |x| blk: { + const want_v = (x.object.get("results") orelse break :blk).object.get(name) orelse break :blk; + const want = try tokenList(arena, want_v.object.get("tokens").?); + const same = std.mem.eql(u32, want, out.items); + if (!same) mismatches += 1; + var first: usize = 0; + while (first < @min(want.len, out.items.len) and want[first] == out.items[first]) first += 1; + verdict = if (same) " MATCH" else try std.fmt.allocPrint(arena, " DIFFER at token {d} (python sha {s})", .{ first, try sha12(arena, want) }); + } + std.debug.print("{s}: prompt {d}, {d} tokens sha {s} in {d:.2}s{s}\n", .{ name, ids.len, out.items.len, sha, seconds, verdict }); + } + return if (mismatches == 0) 0 else 1; +} + +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, .{})); +} + +fn tokenList(a: std.mem.Allocator, v: std.json.Value) ![]u32 { + if (v != .array) return error.BadPromptFile; + const out = try a.alloc(u32, v.array.items.len); + for (v.array.items, out) |x, *t| t.* = @intCast(x.integer); + return out; +} + +/// The capture's sha12: sha256 of json.dumps(tokens), "[1, 2, 3]", its first 12 hex digits. +fn sha12(a: std.mem.Allocator, tokens: []const u32) ![]const u8 { + var text: std.ArrayList(u8) = .empty; + try text.append(a, '['); + for (tokens, 0..) |t, i| { + if (i > 0) try text.appendSlice(a, ", "); + try text.print(a, "{d}", .{t}); + } + try text.append(a, ']'); + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(text.items, &digest, .{}); + const hex = std.fmt.bytesToHex(digest, .lower); + return a.dupe(u8, hex[0..12]); +} + +/// Each case's streams prefilled afresh, its round run, every row's logits hashed; shared cases commit and go on. +fn checkWindows(gpa: std.mem.Allocator, a: std.mem.Allocator, io: std.Io, e: *qwen.Engine, doc: std.json.Value, dump: ?[]const u8, only: ?[]const u8) !u8 { + const root = doc.object; + const prompts = root.get("prompts").?.array.items; + const cases = root.get("cases").?.array.items; + var bad: usize = 0; + const row_bytes = qwen.config.vocab * 2; + const host = try gpa.alloc(u8, row_bytes); + defer gpa.free(host); + for (cases, 0..) |case, ci| { + if (only) |list| { + var it = std.mem.splitScalar(u8, list, ','); + const listed = while (it.next()) |x| { + if (std.fmt.parseInt(usize, x, 10) catch null == ci) break true; + } else false; + if (!listed) continue; + } + const streams = case.object.get("streams").?.array.items; + std.debug.print("case {d}: {s}, {d} streams\n", .{ ci, case.object.get("kind").?.string, streams.len }); + var seqs: [qwen.state.max_streams]qwen.state.Seq = undefined; + var parts: [qwen.state.max_streams]qwen.Part = undefined; + var made: usize = 0; + defer for (seqs[0..made]) |*sq| sq.deinit(); + for (streams, 0..) |sv, k| { + const sid: usize = @intCast(sv.object.get("stream").?.integer); + const ids = try tokenList(a, prompts[sid]); + seqs[k] = try e.sequence(4096); + made += 1; + try e.prefill(&seqs[k], ids); + parts[k] = .{ .seq = &seqs[k], .tokens = try tokenList(a, sv.object.get("tokens").?) }; + if (sv.object.get("parents")) |pv| { + const ps = try a.alloc(i32, pv.array.items.len); + for (pv.array.items, ps) |x, *y| y.* = @intCast(x.integer); + parts[k].parents = ps; + } + } + const n = streams.len; + var f = e.forward(); + if (dump) |dir| f.dump = .{ .io = io, .dir = dir }; + try f.round(parts[0..n]); + f.dump = null; + bad += try compareRows(&f, host, case.object.get("rows").?.array.items, ci, "rows"); + if (case.object.get("paths")) |paths_v| { + var paths: [qwen.state.max_streams][]const u32 = undefined; + var next: [qwen.state.max_streams]u32 = undefined; + for (paths_v.array.items, 0..) |pv, k| paths[k] = try tokenList(a, pv); + try f.commit(parts[0..n], paths[0..n]); + for (case.object.get("next").?.array.items, 0..) |nv, k| { + next[k] = @intCast(nv.integer); + parts[k].tokens = next[k .. k + 1]; + parts[k].parents = null; + } + try f.round(parts[0..n]); + bad += try compareRows(&f, host, case.object.get("after").?.array.items, ci, "after"); + } + if (case.object.get("keep")) |keep_v| { + var kept: [qwen.state.max_streams]usize = undefined; + var next: [qwen.state.max_streams]u32 = undefined; + const prefix = [_]u32{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; + var paths: [qwen.state.max_streams][]const u32 = undefined; + for (keep_v.array.items, 0..) |kv, k| { + kept[k] = @intCast(kv.integer); + paths[k] = prefix[0..kept[k]]; + } + try f.commit(parts[0..n], paths[0..n]); + const reply_rows = doc.object.get("replies").?.array.items; + for (streams, 0..) |sv, k| { + const sid: usize = @intCast(sv.object.get("stream").?.integer); + next[k] = @intCast(reply_rows[sid].array.items[kept[k]].integer); + parts[k].tokens = next[k .. k + 1]; + } + try f.round(parts[0..n]); + bad += try compareRows(&f, host, case.object.get("after").?.array.items, ci, "after"); + } + } + std.debug.print("{d} cases, {d} rows differ\n", .{ cases.len, bad }); + return if (bad == 0) 0 else 1; +} + +fn compareRows(f: *qwen.Forward, host: []u8, want: []const std.json.Value, case: usize, what: []const u8) !usize { + var bad: usize = 0; + for (want, 0..) |rv, r| { + try f.ops.download(host, f.s.logits + r * host.len); + try f.ops.s.synchronize(); + var digest: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(host, &digest, .{}); + const hex = std.fmt.bytesToHex(digest, .lower); + if (!std.mem.eql(u8, &hex, rv.object.get("sha").?.string)) { + std.debug.print("case {d} {s} row {d}: logits differ\n", .{ case, what, r }); + bad += 1; + } + } + return bad; +} + +/// Every prompt prefilled, then greedy shared rounds of one row a stream; ms a round and tokens a second. +fn benchRounds(gpa: std.mem.Allocator, a: std.mem.Allocator, io: std.Io, e: *qwen.Engine, doc: std.json.Value, count: usize) !u8 { + { + // the served engine's cost curve: the forward's ms by a round's rows + var lanes_ = try qwen.Lanes.init(gpa, e, qwen.state.max_streams); + defer lanes_.deinit(); + try lanes_.calibrate(io, qwen.state.max_streams); + for (lanes_.costs[0..lanes_.cost_count]) |cst| std.debug.print("{d} rows: {d:.2} ms\n", .{ cst.width, cst.ms }); + } + const prompts = doc.object.get("prompts").?.array.items; + const n = @min(prompts.len, qwen.state.max_streams); + var seqs: [qwen.state.max_streams]qwen.state.Seq = undefined; + var parts: [qwen.state.max_streams]qwen.Part = undefined; + var next: [qwen.state.max_streams]u32 = undefined; + var ones: [qwen.state.max_streams][]const u32 = @splat(&.{0}); + var made: usize = 0; + defer for (seqs[0..made]) |*sq| sq.deinit(); + var f = e.forward(); + for (prompts[0..n], 0..) |pv, k| { + seqs[k] = try e.sequence(4096); + made += 1; + try e.prefill(&seqs[k], try tokenList(a, pv)); + try f.head(&seqs[k]); + var pick: [1]u32 = undefined; + try f.picks(1, &pick); + next[k] = pick[0]; + } + const clock = std.Io.Clock.awake; + const t0 = clock.now(io).toNanoseconds(); + for (0..count) |_| { + for (0..n) |k| parts[k] = .{ .seq = &seqs[k], .tokens = next[k .. k + 1] }; + try f.round(parts[0..n]); + try f.picks(n, next[0..n]); + try f.commit(parts[0..n], ones[0..n]); + } + try f.ops.s.synchronize(); + const ms = @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e6; + std.debug.print("{d} streams, {d} rounds: {d:.2} ms a round, {d:.1} tok/s\n", .{ n, count, ms / @as(f64, @floatFromInt(count)), @as(f64, @floatFromInt(n * count)) / ms * 1e3 }); + return 0; +} + +/// Each prompt drafted with DFlash2 as capture_draft.py runs it: tokens, rounds and accepted drafts. +fn runDrafted(gpa: std.mem.Allocator, a: std.mem.Allocator, io: std.Io, e: *qwen.Engine, o: Options, prompts: std.json.Value, expect: ?std.json.Value) !u8 { + const clock = std.Io.Clock.awake; + var t0 = clock.now(io).toNanoseconds(); + const f0 = e.forward(); + const d = try qwen.draft.DFlash2.init(gpa, io, f0.ops, f0.t, &e.w, o.drafter orelse return error.NoDrafter, o.model); + defer d.deinit(); + std.debug.print("drafter loaded in {d:.1}s\n", .{@as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e9}); + var ctx = try qwen.draft.Context.init(f0.ops.k.d); + defer ctx.deinit(); + var seq = try e.sequence(o.context); + defer seq.deinit(); + var bad: usize = 0; + var it = prompts.object.iterator(); + while (it.next()) |entry| { + const name = entry.key_ptr.*; + const ids = try tokenList(a, entry.value_ptr.*); + var out: std.ArrayList(u32) = .empty; + defer out.deinit(gpa); + var stats: qwen.lone.Stats = .{}; + t0 = clock.now(io).toNanoseconds(); + try qwen.lone.prefill(e, &seq, &ctx, d, ids); + var f = e.forward(); + try f.head(&seq); + var pick: [1]u32 = undefined; + try f.picks(1, &pick); + const t1 = clock.now(io).toNanoseconds(); + try qwen.lone.decode(e, &seq, &ctx, d, ids, pick[0], o.max_tokens, 12, &out, &stats); + const secs = @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t1)) / 1e9; + var verdict: []const u8 = ""; + if (expect) |x| blk: { + const want_v = (x.object.get("results") orelse break :blk).object.get(name) orelse break :blk; + const want = try tokenList(a, want_v.object.get("tokens").?); + const same = std.mem.eql(u32, want, out.items); + if (!same) bad += 1; + verdict = try std.fmt.allocPrint(a, " {s}; python rounds {d} accepted {d}", .{ if (same) "MATCH" else "DIFFER", want_v.object.get("rounds").?.integer, want_v.object.get("accepted").?.integer }); + } + std.debug.print("{s}: {d} tokens sha {s}, rounds {d} accepted {d}, {d:.1} tok/s{s}\n", .{ name, out.items.len, try sha12(a, out.items), stats.rounds, stats.accepted, @as(f64, @floatFromInt(out.items.len)) / secs, verdict }); + } + return if (bad == 0) 0 else 1; +} + +/// One stream of the multi check: its state, drafting, context (prompt and reply) and reply. +const MultiStream = struct { + seq: qwen.state.Seq, + d: qwen.drafts.Stream, + context: std.ArrayList(u32) = .empty, + out: std.ArrayList(u32) = .empty, + done: bool = false, + rounds: usize = 0, + accepted: usize = 0, +}; + +/// MultiDecoder's rounds as capture_multi.py runs them (greedy, no costs: whole trees, blocks of 16 rows). +fn runMulti(gpa: std.mem.Allocator, a: std.mem.Allocator, io: std.Io, e: *qwen.Engine, o: Options, doc: std.json.Value) !u8 { + const clock = std.Io.Clock.awake; + const f0 = e.forward(); + const d = try qwen.draft.DFlash2.init(gpa, io, f0.ops, f0.t, &e.w, o.drafter orelse return error.NoDrafter, o.model); + defer d.deinit(); + const prompts = doc.object.get("prompts").?.array.items; + const count: usize = @intCast(doc.object.get("max_tokens").?.integer); + const want_rounds = doc.object.get("rounds").?.array.items; + const S = prompts.len; + const ms = try a.alloc(MultiStream, S); + var made: usize = 0; + defer for (ms[0..made]) |*m| { + m.seq.deinit(); + m.d.deinit(); + m.context.deinit(gpa); + m.out.deinit(gpa); + }; + for (prompts, ms) |pv, *m| { + const ids = try tokenList(a, pv); + m.* = .{ .seq = try e.sequence(o.context), .d = qwen.drafts.Stream.init(gpa, try qwen.draft.Context.init(f0.ops.k.d)) }; + made += 1; + try qwen.lone.prefill(e, &m.seq, &m.d.ctx, d, ids); + var f = e.forward(); + try f.head(&m.seq); + var pick: [1]u32 = undefined; + try f.picks(1, &pick); + try m.context.appendSlice(gpa, ids); + try m.context.append(gpa, pick[0]); + try m.out.append(gpa, pick[0]); + } + var differ: usize = 0; + var round: usize = 0; + const t0 = clock.now(io).toNanoseconds(); + var tokens: [qwen.state.round_rows]u32 = undefined; + var parents: [qwen.state.round_rows]i32 = undefined; + var picks: [qwen.state.round_rows]u32 = undefined; + var path_rows: [qwen.state.round_rows]u32 = undefined; + var kept_rows: [qwen.state.round_rows]u32 = undefined; + while (true) : (round += 1) { + var live: [qwen.state.max_streams]usize = undefined; + var n: usize = 0; + for (ms, 0..) |m, k| if (!m.done) { + live[n] = k; + n += 1; + }; + if (n == 0) break; + var asks: [qwen.state.max_streams]qwen.drafts.Ask = undefined; + for (live[0..n], 0..) |k, j| asks[j] = .{ .x = &ms[k].d, .context = ms[k].context.items, .sampling = null }; + try qwen.drafts.propose(d, asks[0..n]); + // the windows: the pending token, then the drafts (tree parents shifted under it) + var parts: [qwen.state.max_streams]qwen.Part = undefined; + var starts: [qwen.state.max_streams + 1]usize = undefined; + var total: usize = 0; + const want = if (round < want_rounds.len) want_rounds[round].array.items else &.{}; + for (live[0..n], 0..) |k, j| { + const m = &ms[k]; + starts[j] = total; + tokens[total] = m.out.items[m.out.items.len - 1]; + parents[total] = -1; + for (m.d.tokens.items, m.d.parents.items, 1..) |t, p, r| { + tokens[total + r] = t; + parents[total + r] = if (p < 0) 0 else p + 1; + } + const rows = 1 + m.d.tokens.items.len; + parts[j] = .{ .seq = &m.seq, .tokens = tokens[total..][0..rows], .parents = parents[total..][0..rows] }; + if (j < want.len) { + const w = want[j].object; + const wt = try tokenList(a, w.get("tokens").?); + const wp = w.get("parents").?.array.items; + var same = @as(usize, @intCast(w.get("stream").?.integer)) == k and std.mem.eql(u32, wt, tokens[total..][0..rows]) and wp.len == rows; + if (same) for (wp, parents[total..][0..rows]) |x, y| { + if (x.integer != y) same = false; + }; + if (!same) { + differ += 1; + if (differ == 1) std.debug.print("round {d} stream {d}: first window that differs from Python's ({s} {d} rows, python {s} {d})\n", .{ round, k, @tagName(m.d.kind), rows, w.get("mode").?.string, wt.len }); + } + } else differ += 1; + total += rows; + } + starts[n] = total; + var f = e.forward(); + f.taps = e.scratch.taps; + try f.round(parts[0..n]); + try f.picks(total, &picks); + var paths: [qwen.state.max_streams][]const u32 = undefined; + var kept: [qwen.state.max_streams]qwen.drafts.Kept = undefined; + for (live[0..n], 0..) |k, j| { + const m = &ms[k]; + const base = starts[j]; + const rows = starts[j + 1] - base; + const room = count - m.out.items.len; + // accept: children equal to their parent's draw, within the room, none past an end token + var len: usize = 1; + path_rows[base] = 0; + var terminal = picks[base]; + while (len < room and !e.w.isEos(terminal)) { + const child = for (1..rows) |r| { + if (parents[base + r] == @as(i32, @intCast(path_rows[base + len - 1])) and tokens[base + r] == terminal) break r; + } else break; + path_rows[base + len] = @intCast(child); + len += 1; + terminal = picks[base + child]; + } + paths[j] = path_rows[base..][0..len]; + for (paths[j], kept_rows[base..][0..len]) |r, *g| g.* = @intCast(base + r); + kept[j] = .{ .x = &m.d, .rows = kept_rows[base..][0..len] }; + for (paths[j][1..]) |r| { + try m.out.append(gpa, tokens[base + r]); + try m.context.append(gpa, tokens[base + r]); + } + try m.out.append(gpa, terminal); + try m.context.append(gpa, terminal); + m.rounds += 1; + m.accepted += len - 1; + } + try f.commit(parts[0..n], paths[0..n]); + try qwen.drafts.absorb(d, f.ops, e.scratch.taps, e.scratch.copy_items, kept[0..n]); + for (live[0..n]) |k| { + const m = &ms[k]; + if (m.out.items.len >= count or e.w.isEos(m.out.items[m.out.items.len - 1])) m.done = true; + } + } + const secs = @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e9; + if (round != want_rounds.len) differ += 1; + var bad: usize = 0; + var produced: usize = 0; + const results = doc.object.get("results").?.array.items; + for (ms, results, 0..) |m, rv, k| { + const want = try tokenList(a, rv.object.get("tokens").?); + const same = std.mem.eql(u32, want, m.out.items); + if (!same or m.rounds != rv.object.get("rounds").?.integer) bad += 1; + produced += m.out.items.len; + std.debug.print("stream {d}: {d} tokens sha {s} rounds {d} accepted {d} {s}; python rounds {d} accepted {d}\n", .{ k, m.out.items.len, try sha12(a, m.out.items), m.rounds, m.accepted, if (same) "MATCH" else "DIFFER", rv.object.get("rounds").?.integer, rv.object.get("accepted").?.integer }); + } + // replies and every stream's rounds must match; a tree may order its nodes otherwise where drafts round otherwise + std.debug.print("{d} rounds (python {d}), {d} windows differ from Python's, {d} replies differ; {d:.1} tok/s\n", .{ round, want_rounds.len, differ, bad, @as(f64, @floatFromInt(produced)) / secs }); + return if (bad == 0 and round == want_rounds.len) 0 else 1; +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 8c0a384051..ac6c026282 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -13,6 +13,7 @@ fn Blob(comptime import_name: []const u8) type { pub const available = options.with_kernels; pub const gdn: []const u8 = if (available) &Blob("fatbin_gdn").bytes else &.{}; +pub const gdn_prefill: []const u8 = if (available) &Blob("fatbin_gdn_prefill").bytes else &.{}; pub const probe: []const u8 = if (available) &Blob("fatbin_probe").bytes else &.{}; pub const qmm_group: []const u8 = if (available) &Blob("fatbin_qmm_group").bytes else &.{}; pub const qmm_prefill: []const u8 = if (available) &Blob("fatbin_qmm_prefill").bytes else &.{}; @@ -24,6 +25,7 @@ pub const scan_rows: []const u8 = if (available) &Blob("fatbin_scan_rows").bytes pub const nemotron_ops: []const u8 = if (available) &Blob("fatbin_nemotron_ops").bytes else &.{}; pub const lane_gemv: []const u8 = if (available) &Blob("fatbin_lane_gemv").bytes else &.{}; pub const affine4_pack: []const u8 = if (available) &Blob("fatbin_affine4_pack").bytes else &.{}; +pub const qwen_ops: []const u8 = if (available) &Blob("fatbin_qwen_ops").bytes else &.{}; pub const sample: []const u8 = if (available) &Blob("fatbin_sample").bytes else &.{}; pub const fp8_lane: []const u8 = if (available) &Blob("fatbin_fp8_lane").bytes else &.{}; pub const torch_argmax: []const u8 = if (available) &Blob("fatbin_torch_argmax").bytes else &.{}; @@ -39,6 +41,7 @@ pub const nemotron_attention: []const u8 = if (available) &Blob("fatbin_nemotron pub const nemotron_keyed: []const u8 = if (available) &Blob("fatbin_nemotron_keyed").bytes else &.{}; pub const train: []const u8 = if (available) &Blob("fatbin_train").bytes else &.{}; pub const train_mixers: []const u8 = if (available) &Blob("fatbin_train_mixers").bytes else &.{}; +pub const torch_norm_rotary: []const u8 = if (available) &Blob("fatbin_torch_norm_rotary").bytes else &.{}; /// Symbols in the gdn image as cuobjdump lists them for the built fatbin (named namespace tf_gdn). pub const gdn_symbols = struct { diff --git a/zig/src/families/qwen27/cuda.zig b/zig/src/families/qwen27/cuda.zig new file mode 100644 index 0000000000..3532c69cde --- /dev/null +++ b/zig/src/families/qwen27/cuda.zig @@ -0,0 +1,33 @@ +//! Qwen3.8-27B on CUDA in Zig: the Python 0.6.6 engine's kernels and layouts, beside the family's Metal engine. + +pub const config = @import("cuda/shape.zig"); +pub const kernels = @import("cuda/kernels.zig"); +pub const triton = @import("cuda/triton.zig"); +pub const weights = @import("cuda/weights.zig"); +pub const state = @import("cuda/state.zig"); +pub const Forward = @import("cuda/forward.zig").Forward; +pub const Part = @import("cuda/forward.zig").Part; +pub const engine = @import("cuda/engine.zig"); +pub const Engine = engine.Engine; +pub const Lanes = @import("cuda/lanes.zig").Cuda; +pub const native = @import("cuda/native.zig"); +pub const draft = @import("cuda/draft.zig"); +pub const lone = @import("cuda/lone.zig"); +pub const drafts = @import("cuda/drafts.zig"); + +test { + _ = config; + _ = kernels; + _ = triton; + _ = weights; + _ = state; + _ = engine; + _ = @import("cuda/forward.zig"); + _ = @import("cuda/lanes.zig"); + _ = @import("cuda/tree.zig"); + _ = @import("cuda/draft_load.zig"); + _ = @import("cuda/draft_policy.zig"); + _ = draft; + _ = lone; + _ = native; +} diff --git a/zig/src/families/qwen27/cuda/draft.zig b/zig/src/families/qwen27/cuda/draft.zig new file mode 100644 index 0000000000..587554ef05 --- /dev/null +++ b/zig/src/families/qwen27/cuda/draft.zig @@ -0,0 +1,423 @@ +//! DFlash2 on CUDA as dflash2's fast path runs it: a context from the target's taps, a masked block, the host tree. + +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const aot = cuda.aot; +const c = @import("shape.zig"); +const kern = @import("kernels.zig"); +const tri = @import("triton.zig"); +const st = @import("state.zig"); +const wts = @import("weights.zig"); +const dl = @import("draft_load.zig"); +const policy = @import("draft_policy.zig"); + +const bf = 2; +const H = dl.hidden; +const D = dl.head_dim; +pub const block = 16; // masked rows a round drafts at most (dflash2.block) +/// Block rows a batch takes: every stream's block in one forward (launch_blocks). +pub const most_rows = block * st.max_streams; +/// Copy items a batch takes: every layer's keys and values of every stream, two pieces a head (or the head's rows). +const most_copies = @max(dl.layers * st.max_streams * 2 * dl.kv_heads * 2, 2 * most_rows); + +/// A stream's drafting context: each layer's keys and values ([kv heads, len, head dim], two buffers to swap). +pub const Context = struct { + arena: st.Arena, + keys: [dl.layers][2]u64, + values: [dl.layers][2]u64, + cur: u1 = 0, + len: usize = 0, // rows held (at most dl.window) + end: usize = 0, // the target position after the last absorbed row + + pub fn bytes() usize { + return dl.layers * 4 * std.mem.alignForward(usize, dl.kv_heads * dl.window * D * bf, 256); + } + + pub fn init(d: *const cuda.Driver) !Context { + var x: Context = .{ .arena = try st.Arena.init(d, bytes()), .keys = undefined, .values = undefined }; + for (0..dl.layers) |l| for (0..2) |j| { + x.keys[l][j] = try x.arena.take(dl.kv_heads * dl.window * D * bf); + x.values[l][j] = try x.arena.take(dl.kv_heads * dl.window * D * bf); + }; + return x; + } + + pub fn deinit(x: *Context) void { + x.arena.deinit(); + } + + /// dflash2.skip: `n` rows go untapped, so the context starts again after them. + pub fn skip(x: *Context, n: usize) void { + x.len = 0; + x.end += n; + } +}; + +/// One stream's share of a batch absorb: its context and how many of the gathered tap rows are its own (in turn). +pub const Absorb = struct { ctx: *Context, rows: usize }; +/// One stream's block: its context and the pending token heading it. +pub const Block = struct { ctx: *const Context, pending: u32 }; + +pub const DFlash2 = struct { + gpa: std.mem.Allocator, + w: dl.Weights, + target: *const wts.Weights, + ops: kern.Ops, + t: tri.Tri, + arena: st.Arena, + inv_freq: u64, // (D / 2) fp32 on the device, as dflash2 makes them + positions: []i32, // a call's row positions on the host + // a block's buffers (block rows) and absorbing's (up to the window's rows) + x: u64, + normed: u64, + conv: u64, + dyn: u64, + xs: u64, + qkv: u64, + q: u64, + k: u64, + v: u64, + attn: u64, + o: u64, + gate: u64, + up: u64, + act: u64, + act_xs: u64, + head_h: u64, + selected: u64, + logits: u64, + logits_tail: u64, + logits32: u64, + cand_values: u64, + cand_ids: u64, + topk_scratch: u64, + pos: u64, + cos: u64, + sin: u64, + table: u64, + copies: u64, + ids: u64, + // host copies of a round's candidates + host_ids: []i64, + host_values: []f32, + host_selected: []u16, + cands: []u32, + unary: []f64, + projected: []f64, + tree: policy.Tree = .{}, + launched: usize = 0, // the last batch's block rows a stream (0: none) + + pub fn init(gpa: std.mem.Allocator, io: std.Io, ops: kern.Ops, t: tri.Tri, target: *const wts.Weights, dir: []const u8, target_dir: []const u8) !*DFlash2 { + const x = try gpa.create(DFlash2); + errdefer gpa.destroy(x); + x.* = undefined; + x.gpa = gpa; + x.ops = ops; + x.t = t; + x.target = target; + x.tree = .{}; + x.w = try dl.load(gpa, io, ops, dir, target_dir); + errdefer x.w.deinit(); + const R = dl.window + 1; // rows absorbed at once at most (the prompt's tail) + const W = most_rows; + x.arena = .{ .buf = null }; + for (0..2) |pass| { + if (pass == 1) x.arena = try st.Arena.init(ops.k.d, x.arena.used); + x.arena.used = 0; + const A = &x.arena; + x.x = try A.take(R * H * bf); + x.normed = try A.take(R * H * bf); + x.conv = try A.take(W * H * bf); + x.dyn = try A.take(W * 4 * (H / dl.conv_group) * bf); + x.xs = try A.take(R * (H * 5) / 64 * 4); + x.qkv = try A.take(R * (dl.heads + 2 * dl.kv_heads) * D * bf); + x.q = try A.take(W * dl.heads * D * bf); + x.k = try A.take(R * dl.kv_heads * D * bf); + x.v = try A.take(R * dl.kv_heads * D * bf); + x.attn = try A.take(W * dl.heads * D * bf); + x.o = try A.take(W * H * bf); + x.gate = try A.take(W * 17408 * bf); + x.up = try A.take(W * 17408 * bf); + x.act = try A.take(W * 17408 * bf); + x.act_xs = try A.take(W * 17408 / 64 * 4); + x.head_h = try A.take(W * H * bf); + x.selected = try A.take(W * dl.selector_rank * bf); + x.logits = try A.take(W * dl.head_rows * bf); + x.logits_tail = try A.take(W * (dl.spans[1][1] - dl.spans[1][0]) * bf); + x.logits32 = try A.take(W * dl.head_rows * 4); + x.cand_values = try A.take(W * policy.top * 4); + x.cand_ids = try A.take(W * policy.top * 8); + x.topk_scratch = try A.take(kern.torch_ops.topkScratchBytes(W, dl.head_rows)); + x.inv_freq = try A.take(D / 2 * 4); + x.pos = try A.take(R * 4); + x.cos = try A.take(R * D / 2 * 4); + x.sin = try A.take(R * D / 2 * 4); + x.table = try A.take(dl.layers * st.max_streams * 24); + x.copies = try A.take(most_copies * @sizeOf(kern.Copy)); + x.ids = try A.take(W * 4); + } + errdefer x.arena.deinit(); + { + var a: cuda.Args = .{}; + a.add(x.inv_freq); + a.add(@as(f32, @floatCast(dl.theta))); + a.add(@as(c_int, D / 2)); + a.add(@as(c_int, D)); + try cuda.launch.launch(ops.k.inv_freq, .{ .grid = .{ .x = 1 }, .block = .{ .x = D / 2 } }, ops.s, &a); + } + x.positions = try gpa.alloc(i32, dl.window + 1); + errdefer gpa.free(x.positions); + x.host_ids = try gpa.alloc(i64, W * policy.top); + x.host_values = try gpa.alloc(f32, W * policy.top); + x.host_selected = try gpa.alloc(u16, W * dl.selector_rank); + x.cands = try gpa.alloc(u32, W * policy.top); + x.unary = try gpa.alloc(f64, W * policy.top); + x.projected = try gpa.alloc(f64, W * dl.selector_rank); + return x; + } + + pub fn deinit(x: *DFlash2) void { + x.gpa.free(x.positions); + x.gpa.free(x.host_ids); + x.gpa.free(x.host_values); + x.gpa.free(x.host_selected); + x.gpa.free(x.cands); + x.gpa.free(x.unary); + x.gpa.free(x.projected); + x.tree.tokens.deinit(x.gpa); + x.tree.parents.deinit(x.gpa); + x.tree.scores.deinit(x.gpa); + x.arena.deinit(); + x.w.deinit(); + const gpa = x.gpa; + gpa.destroy(x); + } + + /// _lin: a packed projection of `rows` rows (each row's bits its own at any count), group sums first. + fn lin(x: *DFlash2, in: u64, q: kern.QLinear, out: u64, rows: usize) !void { + try x.t.groupSums(in, x.xs, q.k, rows, q.k); + try x.ops.dense(in, x.xs, q, out, rows); + } + + /// F.rms_norm over `rows` contiguous rows of the hidden width (the layers' and the head's norms). + fn torchNorm(x: *DFlash2, in: u64, weight: u64, out: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(in); + a.add(weight); + a.add(out); + a.add(@as(u64, 0)); + a.add(@as(f32, 1e-6)); + try cuda.launch.launch(x.ops.k.torch_rms, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 128 } }, x.ops.s, &a); + } + + fn rmsNorm(x: *DFlash2, in: u64, stride: usize, weight: u64, out: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(in); + a.add(@as(c_int, @intCast(stride))); + a.add(weight); + a.add(out); + a.add(@as(c_int, H)); + a.add(@as(f32, 1e-6)); + try cuda.launch.launch(x.ops.k.rms_norm, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 256 } }, x.ops.s, &a); + } + + /// dflash2._rotary: cos and sin of each run's positions [start, start + rows) times the inverse frequencies, fp32. + fn rotary(x: *DFlash2, runs: []const [2]usize) !void { + var rows: usize = 0; + for (runs) |run| for (0..run[1]) |j| { + x.positions[rows] = @intCast(run[0] + j); + rows += 1; + }; + try x.ops.upload(x.pos, std.mem.sliceAsBytes(x.positions[0..rows])); + var a: cuda.Args = .{}; + for ([_]u64{ x.pos, x.inv_freq, x.cos, x.sin }) |v| a.add(v); + a.add(@as(c_int, D / 2)); + try cuda.launch.launch(x.ops.k.rotary, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = D / 2 } }, x.ops.s, &a); + } + + /// dflash2._prep: q (heads, rows, D), k and v (kv heads, rows, D) from [q | k | v] rows, normed and rotated. + fn prep(x: *DFlash2, qkv: u64, layer: usize, rows: usize, with_q: bool, q: u64, k: u64, v: u64) !void { + const l = x.w.layers[layer]; + const h: usize = if (with_q) dl.heads else 0; + const stride = (h + 2 * dl.kv_heads) * D; + const p = aot.ptr; + try x.t.set.run(x.t.s, "_prep_kernel", .{ @intCast(rows), @intCast(h + 2 * dl.kv_heads), 1 }, &.{ + p("QKV", "*bf16", qkv), p("QN", "*bf16", l.q_norm), p("KN", "*bf16", l.k_norm), p("COS", "*fp32", x.cos), p("SIN", "*fp32", x.sin), + p("QO", "*bf16", if (with_q) q else qkv), p("KO", "*bf16", k), p("VO", "*bf16", v), aot.int("L", @intCast(rows)), aot.int("stride", @intCast(stride)), + aot.float("eps", 1e-6), + }, &.{ aot.ci("H", @intCast(h)), aot.ci("HKV", dl.kv_heads), aot.ci("HALF", D / 2) }); + } + + /// dflash2._dconv: the two-tap dynamic conv of each `seg`-row block, plus a residual. + fn dconv(x: *DFlash2, in: u64, dyn: u64, base: u64, branch: usize, res: ?u64, out: u64, rows: usize, seg: usize) !void { + const p = aot.ptr; + try x.t.set.run(x.t.s, "_dconv_kernel", .{ @intCast(rows), (H + 1023) / 1024, 1 }, &.{ + p("X", "*bf16", in), p("DYN", "*bf16", dyn), p("BASE", "*bf16", base), p("RES", "*bf16", res orelse in), p("OUT", "*bf16", out), aot.int("SEG", @intCast(seg)), + }, &.{ aot.ci("D", H), aot.ci("G", H / dl.conv_group), aot.ci("GS", dl.conv_group), aot.ci("BRANCH", @intCast(branch)), aot.ci("HAS_RES", @intFromBool(res != null)), aot.ci("BLOCK", 1024) }); + } + + /// add_taps: the target's taps (rows of 5 x hidden bf16) projected into the context's layers. + pub fn absorb(x: *DFlash2, ctx: *Context, taps: u64, rows: usize) !void { + return x.absorbMany(&.{.{ .ctx = ctx, .rows = rows }}, taps); + } + + /// add_taps_streams: every stream's rows (in turn) through each projection once, each context its last window. + pub fn absorbMany(x: *DFlash2, items: []const Absorb, taps: u64) !void { + var total: usize = 0; + for (items) |it| total += it.rows; + if (total == 0) return; + if (total > dl.window + 1 or items.len > st.max_streams) return error.TooManyDraftTaps; + try x.lin(taps, x.w.fc, x.qkv, total); // fc's (rows, hidden) output, in a buffer of the window's rows + try x.rmsNorm(x.qkv, H, x.w.hidden_norm, x.normed, total); + var runs: [st.max_streams][2]usize = undefined; + for (items, 0..) |it, j| runs[j] = .{ it.ctx.end, it.rows }; + try x.rotary(runs[0..items.len]); + // every layer's copies: the last `keep` rows of [context | new rows], a head at a time, both halves once + var list: std.ArrayList(kern.Copy) = .empty; + defer list.deinit(x.gpa); + var starts: [dl.layers + 1]usize = undefined; + for (0..dl.layers) |l| { + starts[l] = list.items.len; + var first: usize = 0; + for (items) |it| { + const ctx = it.ctx; + const keep = @min(dl.window, ctx.len + it.rows); + const old_n = ctx.len; + const drop = old_n + it.rows - keep; // rows of [old | new] that fall out of the window + const from_old = old_n -| drop; + const new_from = drop -| old_n; + const nxt: u1 = ctx.cur ^ 1; + for ([_][2]u64{ x.ctxPair(ctx.keys[l], ctx.cur, nxt), x.ctxPair(ctx.values[l], ctx.cur, nxt) }, [_]u64{ x.k, x.v }) |pair, fresh| { + for (0..dl.kv_heads) |h| { + if (from_old > 0) try list.append(x.gpa, .{ .dst = pair[1] + h * keep * D * bf, .src = pair[0] + (h * old_n + drop) * D * bf, .bytes = from_old * D * bf }); + try list.append(x.gpa, .{ .dst = pair[1] + (h * keep + from_old) * D * bf, .src = fresh + (h * total + first + new_from) * D * bf, .bytes = (it.rows - new_from) * D * bf }); + } + } + first += it.rows; + } + } + starts[dl.layers] = list.items.len; + if (list.items.len > most_copies) return error.TooManyDraftTaps; + try x.ops.upload(x.copies, std.mem.sliceAsBytes(list.items)); + for (0..dl.layers) |l| { + try x.lin(x.normed, x.w.layers[l].kv, x.qkv, total); + try x.prep(x.qkv, l, total, false, 0, x.k, x.v); + try x.ops.copies(x.copies + starts[l] * @sizeOf(kern.Copy), starts[l + 1] - starts[l]); + } + try x.ops.s.synchronize(); + for (items) |it| { + it.ctx.cur ^= 1; + it.ctx.len = @min(dl.window, it.ctx.len + it.rows); + it.ctx.end += it.rows; + } + } + + fn ctxPair(_: *DFlash2, bufs: [2]u64, cur: u1, nxt: u1) [2]u64 { + return .{ bufs[cur], bufs[nxt] }; + } + + /// launch_blocks: each stream's pending token then masks through the layers in one forward; candidates on the host. + pub fn launchMany(x: *DFlash2, blocks: []const Block, L: usize) !void { + const S = blocks.len; + const rows = S * L; + if (S == 0 or S > st.max_streams or L < 2 or L > block) return error.NoDraftContext; + for (blocks) |b| if (b.ctx.len == 0) return error.NoDraftContext; + var ids: [most_rows]i32 = @splat(dl.mask_id); + var runs: [st.max_streams][2]usize = undefined; + // each layer's table: the streams' (keys, values) pointers, then their context lengths + const per = std.mem.alignForward(usize, S * 20, 16); // 16-byte aligned tables, as fresh torch tensors are + var table: [dl.layers * (st.max_streams * 20 + 16)]u8 align(8) = undefined; + for (blocks, 0..) |b, j| { + ids[j * L] = @intCast(b.pending); + runs[j] = .{ b.ctx.end, L }; + for (0..dl.layers) |l| { + const at = table[l * per ..]; + std.mem.writeInt(u64, at[j * 16 ..][0..8], b.ctx.keys[l][b.ctx.cur], .little); + std.mem.writeInt(u64, at[j * 16 + 8 ..][0..8], b.ctx.values[l][b.ctx.cur], .little); + std.mem.writeInt(i32, at[S * 16 + j * 4 ..][0..4], @intCast(b.ctx.len), .little); + } + } + try x.ops.upload(x.ids, std.mem.sliceAsBytes(ids[0..rows])); + try x.ops.upload(x.table, table[0 .. dl.layers * per]); + const tw = x.target; + try x.t.embed(x.ids, tw.embed.w, tw.embed.s, tw.embed.b, x.x, rows, H); + try x.rotary(runs[0..S]); + const scale: f32 = @floatCast(std.math.pow(f64, D, -0.5)); + for (x.w.layers, 0..) |l, i| { + try x.torchNorm(x.x, l.in_norm, x.normed, rows); + try x.lin(x.normed, l.attn_proj, x.dyn, rows); + try x.dconv(x.normed, x.dyn, l.attn_base, 0, null, x.conv, rows, L); + try x.lin(x.conv, l.qkv, x.qkv, rows); + try x.prep(x.qkv, i, rows, true, x.q, x.k, x.v); + const tb = x.table + i * per; + const p = aot.ptr; + try x.t.set.run(x.t.s, "_block_attention", .{ @intCast(S), dl.kv_heads, 1 }, &.{ + p("Q", "*bf16", x.q), p("KB", "*bf16", x.k), p("VB", "*bf16", x.v), p("TABLE", "*i64", tb), p("LENS", "*i32", tb + S * 16), p("O", "*bf16", x.attn), + aot.float("scale", scale), aot.int("window", dl.window), aot.int("R", @intCast(rows)), + }, &.{ aot.ci("G", dl.heads / dl.kv_heads), aot.ci("HKV", dl.kv_heads), aot.ci("L", @intCast(L)), aot.ci("LP", @intCast(@max(16, std.math.ceilPowerOfTwo(usize, L) catch unreachable))), aot.ci("D", D), aot.ci("BN", 64), aot.ci("CAUSAL", 0) }); + try x.lin(x.attn, l.o, x.o, rows); + try x.dconv(x.o, x.dyn, l.attn_base, 1, x.x, x.x, rows, L); + try x.torchNorm(x.x, l.post_norm, x.normed, rows); + try x.lin(x.normed, l.mlp_proj, x.dyn, rows); + try x.dconv(x.normed, x.dyn, l.mlp_base, 0, null, x.conv, rows, L); + try x.t.groupSums(x.conv, x.xs, H, rows, H); + try x.ops.dense(x.conv, x.xs, l.gate, x.gate, rows); + try x.ops.dense(x.conv, x.xs, l.up, x.up, rows); + try x.t.swiglu(x.gate, x.up, x.act, x.act_xs, rows, l.gate.n); + try x.ops.dense(x.act, x.act_xs, l.down, x.o, rows); + try x.dconv(x.o, x.dyn, l.mlp_base, 1, x.x, x.x, rows, L); + } + // every block but its pending row, normed into stacked depths + const depths = L - 1; + const total = S * depths; + for (0..S) |j| try x.torchNorm(x.x + (j * L + 1) * H * bf, x.w.norm, x.head_h + j * depths * H * bf, depths); + try x.lin(x.head_h, x.w.select, x.selected, total); + // matmul_rows: the head's spans at the stacked rows' K split (1), then joined column-wise + try x.t.groupSums(x.head_h, x.xs, H, total, H); + const head = tw.head; + const first: kern.QLinear = .{ .w = head.w, .s = head.s, .b = head.b, .n = dl.spans[0][1], .k = head.k, .npad = head.npad }; + try x.ops.denseSplit(x.head_h, x.xs, first, x.logits32, total, 1); // a scratch of the right size + try x.ops.denseSplit(x.head_h, x.xs, x.w.head_tail, x.logits_tail, total, 1); + var items: std.ArrayList(kern.Copy) = .empty; + defer items.deinit(x.gpa); + const na = dl.spans[0][1]; + const nb = dl.spans[1][1] - dl.spans[1][0]; + for (0..total) |r| { + try items.append(x.gpa, .{ .dst = x.logits + r * dl.head_rows * bf, .src = x.logits32 + r * na * bf, .bytes = na * bf }); + try items.append(x.gpa, .{ .dst = x.logits + (r * dl.head_rows + na) * bf, .src = x.logits_tail + r * nb * bf, .bytes = nb * bf }); + } + try x.ops.upload(x.copies, std.mem.sliceAsBytes(items.items)); + try x.ops.copies(x.copies, items.items.len); + const torch = x.ops.torch(); + try torch.toF32(x.logits, x.logits32, total * dl.head_rows); + try torch.topk(x.logits32, dl.head_rows, total, policy.top, x.cand_values, x.cand_ids, x.topk_scratch); + try x.ops.download(std.mem.sliceAsBytes(x.host_values[0 .. total * policy.top]), x.cand_values); + try x.ops.download(std.mem.sliceAsBytes(x.host_ids[0 .. total * policy.top]), x.cand_ids); + try x.ops.download(std.mem.sliceAsBytes(x.host_selected[0 .. total * dl.selector_rank]), x.selected); + try x.ops.s.synchronize(); + for (0..total * policy.top) |j| { + const local: usize = @intCast(x.host_ids[j]); + x.cands[j] = @intCast(if (local < na) local else dl.spans[1][0] + local - na); + x.unary[j] = x.host_values[j]; + } + for (0..total * dl.selector_rank) |j| x.projected[j] = @as(f32, @bitCast(@as(u32, x.host_selected[j]) << 16)); + x.launched = L; + } + + /// finish_tree for the batch's `j`th block: best_first into `out` (parents -1: under the pending row). + pub fn finish(x: *DFlash2, j: usize, pending: u32, context_length: usize, max_nodes: usize, sampling: ?lanes.Sampling, out: *policy.Tree) !void { + const depths = x.launched - 1; + const at = j * depths; + try policy.bestFirst(x.gpa, .{ .ids = x.cands[at * policy.top ..][0 .. depths * policy.top], .unary = x.unary[at * policy.top ..][0 .. depths * policy.top], .projected = x.projected[at * dl.selector_rank ..][0 .. depths * dl.selector_rank], .depths = depths }, x.w.pred, x.w.succ, pending, @min(127, max_nodes), sampling, context_length, out); + } + + /// finish_tree: best_first over the launched block's candidates; nodes and parents (-1: under the pending row). + pub fn propose(x: *DFlash2, ctx: *const Context, pending: u32, context_length: usize, max_nodes: usize, sampling: ?lanes.Sampling) !struct { tokens: []const u32, parents: []const i32 } { + if (ctx.len == 0 or max_nodes == 0) return .{ .tokens = &.{}, .parents = &.{} }; + const rows: usize = @min(block, max_nodes + 1); + try x.launchMany(&.{.{ .ctx = ctx, .pending = pending }}, rows); + try x.finish(0, pending, context_length, max_nodes, sampling, &x.tree); + return .{ .tokens = x.tree.tokens.items, .parents = x.tree.parents.items }; + } +}; diff --git a/zig/src/families/qwen27/cuda/draft_load.zig b/zig/src/families/qwen27/cuda/draft_load.zig new file mode 100644 index 0000000000..8f9b0a7404 --- /dev/null +++ b/zig/src/families/qwen27/cuda/draft_load.zig @@ -0,0 +1,274 @@ +//! DFlash2's weights as dflash2 holds them: projections quantize4'd and tiled, codebooks fp32 on the host. + +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const kern = @import("kernels.zig"); +const st = @import("state.zig"); + +pub const QLinear = kern.QLinear; +const Tensor = core.checkpoint.Tensor; + +pub const hidden = 5120; +pub const layers = 5; +pub const heads = 32; +pub const kv_heads = 8; +pub const head_dim = 128; +pub const conv_group = 16; +pub const mask_id = 248070; +pub const window = 2047; // sliding_window - 1: context rows each layer keeps +pub const taps = [_]usize{ 5, 19, 33, 47, 61 }; // dflash_config.target_layer_ids +pub const selector_rank = 256; +pub const theta: f64 = 10000000; +/// The head's rows the drafter reads: the first 98,304 tokens and the last 288 (dflash2.vocab_spans). +pub const spans = [2][2]usize{ .{ 0, 98304 }, .{ 248032, 248320 } }; +pub const head_rows = spans[0][1] - spans[0][0] + spans[1][1] - spans[1][0]; + +pub const Layer = struct { + in_norm: u64, + post_norm: u64, + attn_proj: QLinear, // attention_conv.kernel_projection: the conv's dynamic taps (2 x 2 x 320) + attn_base: u64, // attention_conv.base_kernel (2, 2, 5120) bf16 + mlp_proj: QLinear, + mlp_base: u64, + qkv: QLinear, // [q | k | v] stacked + kv: QLinear, // [k | v] stacked: the context's projection + o: QLinear, + q_norm: u64, + k_norm: u64, + gate: QLinear, + up: QLinear, + down: QLinear, +}; + +pub const Weights = struct { + gpa: std.mem.Allocator, + layers: [layers]Layer = undefined, + fc: QLinear = undefined, // five taps (25,600) to the hidden width + hidden_norm: u64 = 0, + norm: u64 = 0, + select: QLinear = undefined, // candidate_selector.hidden_projection + head_tail: QLinear = undefined, // the target head's last 288 rows, tiled on their own (rows() copies them) + pred: []f32 = &.{}, // candidate_selector.predecessor_codebook (vocab, 256) + succ: []f32 = &.{}, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.gpa.free(w.pred); + w.gpa.free(w.succ); + w.* = undefined; + } +}; + +fn bf16Value(word: u16) f32 { + return @bitCast(@as(u32, word) << 16); +} + +fn toBf16(x: f32) u16 { + const b: u32 = @bitCast(x); + return @intCast((b + 0x7FFF + ((b >> 16) & 1)) >> 16); +} + +/// torch.round: halves to even. +fn roundEven(x: f32) f32 { + const r = @round(x); + return if (@abs(x - @trunc(x)) == 0.5) 2.0 * @round(x / 2.0) else r; +} + +/// dflash2.quantize4 on the host, bit for bit: (n, k) bf16 to MLX affine 4-bit words, bf16 scales and biases. +pub fn quantize4(src: []const u8, n: usize, k: usize, words: []u32, scales: []u16, biases: []u16) void { + const kg = k / 64; + for (0..n) |r| for (0..kg) |gi| { + var vals: [64]f32 = undefined; + for (&vals, 0..) |*v, j| v.* = bf16Value(std.mem.readInt(u16, src[(r * k + gi * 64 + j) * 2 ..][0..2], .little)); + var lo = vals[0]; + var hi = vals[0]; + for (vals[1..]) |v| { + lo = @min(lo, v); + hi = @max(hi, v); + } + const s = toBf16(@max((hi - lo) / 15.0, 1e-8)); + const b = toBf16(lo); + scales[r * kg + gi] = s; + biases[r * kg + gi] = b; + const sf = bf16Value(s); + const bf = bf16Value(b); + for (0..8) |wi| { + var word: u32 = 0; + for (0..8) |j| { + const q = std.math.clamp(roundEven((vals[wi * 8 + j] - bf) / sf), 0.0, 15.0); + word |= @as(u32, @intFromFloat(q)) << @intCast(4 * j); + } + words[r * (k / 8) + gi * 8 + wi] = word; + } + }; +} + +const Loader = struct { + gpa: std.mem.Allocator, + ops: kern.Ops, + w: *Weights, + words: std.ArrayList(u32) = .empty, + scales: std.ArrayList(u16) = .empty, + biases: std.ArrayList(u16) = .empty, + staging: ?cuda.DeviceBuffer = null, + + fn alloc(L: *Loader, len: usize) !u64 { + const b = try cuda.DeviceBuffer.alloc(L.ops.k.d, len); + try L.w.buffers.append(L.gpa, b); + return b.ptr; + } + + fn raw(L: *Loader, t: Tensor) !u64 { + const ptr = try L.alloc(t.bytes.len); + try L.ops.upload(ptr, t.bytes); + try L.ops.s.synchronize(); + return ptr; + } + + /// qmm_fast.tile of host MLX words, scales and biases (n rows of k inputs): the lane matmul's layout. + fn tile(L: *Loader, words: []const u32, scales: []const u16, biases: []const u16, n: usize, k: usize) !QLinear { + const k8 = k / 8; + const kg = k / 64; + const npad = (n + 127) / 128 * 128; + const sizes = [3]usize{ n * k8 * 4, n * kg * 2, n * kg * 2 }; + const total_in = sizes[0] + sizes[1] + sizes[2]; + if (L.staging == null or L.staging.?.len < total_in) { + if (L.staging) |*b| b.free(); + L.staging = try cuda.DeviceBuffer.alloc(L.ops.k.d, total_in); + } + const base = L.staging.?.ptr; + try L.ops.upload(base, std.mem.sliceAsBytes(words)); + try L.ops.upload(base + sizes[0], std.mem.sliceAsBytes(scales)); + try L.ops.upload(base + sizes[0] + sizes[1], std.mem.sliceAsBytes(biases)); + const q: QLinear = .{ .w = try L.alloc(npad * k / 2), .s = try L.alloc(kg * npad * 2), .b = try L.alloc(kg * npad * 2), .n = n, .k = k, .npad = npad }; + const total: u64 = @as(u64, npad / 64) * kg * 512; + var a: cuda.Args = .{}; + a.add(base); + for ([_]usize{ n, k8, kg }) |v| a.add(@as(c_int, @intCast(v))); + a.add(q.w); + a.add(@as(c_longlong, @intCast(total))); + try cuda.launch.launch(L.ops.k.pack_dense, .{ .grid = .{ .x = @intCast((total + 255) / 256) }, .block = .{ .x = 256 } }, L.ops.s, &a); + for ([_]u64{ q.s, q.b }, [_]usize{ sizes[0], sizes[0] + sizes[1] }) |out, off| { + var t: cuda.Args = .{}; + t.add(base + off); + for ([_]usize{ n, kg, npad }) |v| t.add(@as(c_int, @intCast(v))); + t.add(out); + const cells = @as(u64, kg) * npad; + try cuda.launch.launch(L.ops.k.transpose16, .{ .grid = .{ .x = @intCast((cells + 255) / 256) }, .block = .{ .x = 256 } }, L.ops.s, &t); + } + try L.ops.s.synchronize(); // the staging buffer and host arrays are reused next + return q; + } + + /// One bf16 (n, k) checkpoint tensor (or several stacked by rows) quantized and tiled. + fn quantized(L: *Loader, parts: []const Tensor, k: usize) !QLinear { + var n: usize = 0; + for (parts) |t| { + if (t.dtype != .bf16 or t.rank != 2 or t.dim(1) != k) return error.UnexpectedDraftTensor; + n += t.dim(0); + } + try L.words.resize(L.gpa, n * k / 8); + try L.scales.resize(L.gpa, n * k / 64); + try L.biases.resize(L.gpa, n * k / 64); + var row: usize = 0; + for (parts) |t| { + const r = t.dim(0); + quantize4(t.bytes, r, k, L.words.items[row * k / 8 ..][0 .. r * k / 8], L.scales.items[row * k / 64 ..][0 .. r * k / 64], L.biases.items[row * k / 64 ..][0 .. r * k / 64]); + row += r; + } + return L.tile(L.words.items, L.scales.items, L.biases.items, n, k); + } + + fn get(ck: *core.Checkpoint, comptime fmt: []const u8, args: anytype) !Tensor { + var buf: [160]u8 = undefined; + return ck.get(try std.fmt.bufPrint(&buf, fmt, args)); + } + + /// The codebook as fp32 on the host (dflash2 keeps tensor.float().numpy()). + fn codebook(L: *Loader, t: Tensor) ![]f32 { + if (t.dtype != .bf16 or t.rank != 2 or t.dim(1) != selector_rank) return error.UnexpectedDraftTensor; + const out = try L.gpa.alloc(f32, t.dim(0) * selector_rank); + for (out, 0..) |*o, i| o.* = bf16Value(std.mem.readInt(u16, t.bytes[2 * i ..][0..2], .little)); + return out; + } +}; + +/// The drafter at `dir`, and the target head's last span tiled from the target checkpoint at `target_dir`. +pub fn load(gpa: std.mem.Allocator, io: std.Io, ops: kern.Ops, dir: []const u8, target_dir: []const u8) !Weights { + var w: Weights = .{ .gpa = gpa }; + errdefer w.deinit(); + var L: Loader = .{ .gpa = gpa, .ops = ops, .w = &w }; + defer { + L.words.deinit(gpa); + L.scales.deinit(gpa); + L.biases.deinit(gpa); + if (L.staging) |*b| b.free(); + } + var ck = try core.Checkpoint.openModel(gpa, io, dir); + defer ck.close(); + for (&w.layers, 0..) |*l, i| { + const q = try Loader.get(&ck, "layers.{d}.self_attn.q_proj.weight", .{i}); + const k = try Loader.get(&ck, "layers.{d}.self_attn.k_proj.weight", .{i}); + const v = try Loader.get(&ck, "layers.{d}.self_attn.v_proj.weight", .{i}); + l.qkv = try L.quantized(&.{ q, k, v }, hidden); + l.kv = try L.quantized(&.{ k, v }, hidden); + l.o = try L.quantized(&.{try Loader.get(&ck, "layers.{d}.self_attn.o_proj.weight", .{i})}, heads * head_dim); + l.q_norm = try L.raw(try Loader.get(&ck, "layers.{d}.self_attn.q_norm.weight", .{i})); + l.k_norm = try L.raw(try Loader.get(&ck, "layers.{d}.self_attn.k_norm.weight", .{i})); + l.in_norm = try L.raw(try Loader.get(&ck, "layers.{d}.input_layernorm.weight", .{i})); + l.post_norm = try L.raw(try Loader.get(&ck, "layers.{d}.post_attention_layernorm.weight", .{i})); + l.attn_proj = try L.quantized(&.{try Loader.get(&ck, "layers.{d}.attention_conv.kernel_projection.weight", .{i})}, hidden); + l.attn_base = try L.raw(try Loader.get(&ck, "layers.{d}.attention_conv.base_kernel", .{i})); + l.mlp_proj = try L.quantized(&.{try Loader.get(&ck, "layers.{d}.mlp_conv.kernel_projection.weight", .{i})}, hidden); + l.mlp_base = try L.raw(try Loader.get(&ck, "layers.{d}.mlp_conv.base_kernel", .{i})); + l.gate = try L.quantized(&.{try Loader.get(&ck, "layers.{d}.mlp.gate_proj.weight", .{i})}, hidden); + l.up = try L.quantized(&.{try Loader.get(&ck, "layers.{d}.mlp.up_proj.weight", .{i})}, hidden); + const down = try Loader.get(&ck, "layers.{d}.mlp.down_proj.weight", .{i}); + l.down = try L.quantized(&.{down}, down.dim(1)); + } + const fc = try ck.get("fc.weight"); + w.fc = try L.quantized(&.{fc}, fc.dim(1)); + w.hidden_norm = try L.raw(try ck.get("hidden_norm.weight")); + w.norm = try L.raw(try ck.get("norm.weight")); + w.select = try L.quantized(&.{try ck.get("candidate_selector.hidden_projection.weight")}, hidden); + w.pred = try L.codebook(try ck.get("candidate_selector.predecessor_codebook")); + w.succ = try L.codebook(try ck.get("candidate_selector.successor_codebook")); + if (ck.unused() != 0) return error.UnusedDraftTensors; + // dflash2's sub-head: rows() of the tiled head copies a span off the 64-row tile grid, packed on its own + var tk = try core.Checkpoint.openModelPrefix(gpa, io, target_dir, "language_model.lm_head"); + defer tk.close(); + const hw = try tk.get("language_model.lm_head.weight"); + const hs = try tk.get("language_model.lm_head.scales"); + const hb = try tk.get("language_model.lm_head.biases"); + const a = spans[1][0]; + const n = spans[1][1] - a; + const k8 = hidden / 8; + const kg = hidden / 64; + // mapped tensors may sit at odd offsets: the rows go through aligned host arrays + try L.words.resize(gpa, n * k8); + try L.scales.resize(gpa, n * kg); + try L.biases.resize(gpa, n * kg); + @memcpy(std.mem.sliceAsBytes(L.words.items), hw.bytes[a * k8 * 4 ..][0 .. n * k8 * 4]); + @memcpy(std.mem.sliceAsBytes(L.scales.items), hs.bytes[a * kg * 2 ..][0 .. n * kg * 2]); + @memcpy(std.mem.sliceAsBytes(L.biases.items), hb.bytes[a * kg * 2 ..][0 .. n * kg * 2]); + w.head_tail = try L.tile(L.words.items, L.scales.items, L.biases.items, n, hidden); + return w; +} + +test "quantize4 rounds as torch does" { + // one group: values 0..63 / 4 -> lo 0, scale bf16(63/4/15 = 1.05), each q round-half-even of v / 1.046875 + var src: [64 * 2]u8 = undefined; + for (0..64) |j| std.mem.writeInt(u16, src[2 * j ..][0..2], toBf16(@as(f32, @floatFromInt(j)) / 4.0), .little); + var words: [8]u32 = undefined; + var scales: [1]u16 = undefined; + var biases: [1]u16 = undefined; + quantize4(&src, 1, 64, &words, &scales, &biases); + try std.testing.expectEqual(toBf16(63.0 / 4.0 / 15.0), scales[0]); + try std.testing.expectEqual(@as(u16, 0), biases[0]); + try std.testing.expectEqual(@as(u32, 15), words[7] >> 28); + try std.testing.expectEqual(roundEven(2.5), 2.0); + try std.testing.expectEqual(roundEven(3.5), 4.0); +} diff --git a/zig/src/families/qwen27/cuda/draft_policy.zig b/zig/src/families/qwen27/cuda/draft_policy.zig new file mode 100644 index 0000000000..83888d435a --- /dev/null +++ b/zig/src/families/qwen27/cuda/draft_policy.zig @@ -0,0 +1,122 @@ +//! draft_tree.best_first on the host: which of DFlash2's candidates a round verifies, and where each hangs. + +const std = @import("std"); +const lanes = @import("lanes"); + +pub const branch = 4; +const edge_weight = 0.6; +const noise_weight = 0.7; +const scale = 1.5; +pub const rank = 256; // the selector's codebook width +pub const top = 16; // candidates a depth + +/// A drafted block's candidates: each depth's 16 token ids, their logits (unary) and the selector's projection. +pub const Candidates = struct { ids: []const u32, unary: []const f64, projected: []const f64, depths: usize }; + +/// The tree: nodes in pop order (parents first), each node's parent (-1: hangs from the anchor), path scores. +pub const Tree = struct { tokens: std.ArrayList(u32) = .empty, parents: std.ArrayList(i32) = .empty, scores: std.ArrayList(f64) = .empty }; + +const Item = struct { score: f64, parent: i32, token: u32, depth: usize }; + +fn before(_: void, a: Item, b: Item) std.math.Order { + // heapq's tuple order: score, then parent, then token, then depth + if (a.score != b.score) return std.math.order(a.score, b.score); + if (a.parent != b.parent) return std.math.order(a.parent, b.parent); + if (a.token != b.token) return std.math.order(a.token, b.token); + return std.math.order(a.depth, b.depth); +} + +/// best_first: expand the anchor's candidates, then pop the best path score until `max_nodes` are placed. +pub fn bestFirst(gpa: std.mem.Allocator, c: Candidates, pred: []const f32, succ: []const f32, anchor: u32, max_nodes: usize, sampling: ?lanes.Sampling, first_position: u64, out: *Tree) !void { + out.tokens.clearRetainingCapacity(); + out.parents.clearRetainingCapacity(); + out.scores.clearRetainingCapacity(); + const temp: f64 = if (sampling) |s| @max(s.temperature, 1e-6) else 1.0; + var heap: std.PriorityQueue(Item, void, before) = .empty; + defer heap.deinit(gpa); + const Ctx = struct { + gpa: std.mem.Allocator, + c: Candidates, + pred: []const f32, + succ: []const f32, + temp: f64, + sampling: ?lanes.Sampling, + first_position: u64, + heap: *std.PriorityQueue(Item, void, before), + + fn expand(x: @This(), token: u32, depth: usize, parent: i32, path: f64) !void { + var values: [top]f64 = undefined; + const p = x.pred[@as(usize, token) * rank ..][0..rank]; + const proj = x.c.projected[depth * rank ..][0..rank]; + var weighted: [rank]f64 = undefined; + for (&weighted, p, proj) |*wgt, a, b| wgt.* = @as(f64, a) * b; + for (&values, 0..) |*v, i| { + const cand = x.c.ids[depth * top + i]; + const s = x.succ[@as(usize, cand) * rank ..][0..rank]; + var edge: f64 = 0; + for (s, weighted) |a, b| edge += @as(f64, a) * b; + v.* = (x.c.unary[depth * top + i] + edge_weight * edge) / x.temp; + if (x.sampling) |smp| v.* += noise_weight * -@log(-@log(lanes.sampling.uniform(smp.seed, x.first_position + depth, cand))); + v.* /= scale; + } + var most = values[0]; + for (values[1..]) |v| most = @max(most, v); + var total: f64 = 0; + for (&values) |*v| { + v.* -= most; + total += @exp(v.*); + } + const log_total = @log(total); + var order: [top]usize = undefined; + for (&order, 0..) |*o, i| o.* = i; + std.mem.sort(usize, &order, &values, struct { + fn more(vals: *const [top]f64, a: usize, b: usize) bool { + return vals[a] > vals[b] or (vals[a] == vals[b] and a < b); + } + }.more); + for (order[0..branch]) |i| { + const logp = values[i] - log_total; + if (!std.math.isFinite(logp)) break; + try x.heap.push(x.gpa, .{ .score = path - logp, .parent = parent, .token = x.c.ids[depth * top + i], .depth = depth }); + } + } + }; + const ctx: Ctx = .{ .gpa = gpa, .c = c, .pred = pred, .succ = succ, .temp = temp, .sampling = sampling, .first_position = first_position, .heap = &heap }; + try ctx.expand(anchor, 0, -1, 0.0); + while (heap.count() > 0 and out.tokens.items.len < max_nodes) { + const it = heap.pop().?; + const me: i32 = @intCast(out.tokens.items.len); + try out.tokens.append(gpa, it.token); + try out.parents.append(gpa, it.parent); + try out.scores.append(gpa, it.score); + if (it.depth + 1 < c.depths) try ctx.expand(it.token, it.depth + 1, me, it.score); + } +} + +test "best_first pops by path score, parents before children, ties by parent" { + const gpa = std.testing.allocator; + const vocab = 32; + const pred = try gpa.alloc(f32, vocab * rank); + defer gpa.free(pred); + const succ = try gpa.alloc(f32, vocab * rank); + defer gpa.free(succ); + @memset(pred, 0); + @memset(succ, 0); + var ids: [2 * top]u32 = undefined; + var unary: [2 * top]f64 = undefined; + for (0..2) |d| for (0..top) |i| { + ids[d * top + i] = @intCast(i); + unary[d * top + i] = -@as(f64, @floatFromInt(i)); + }; + const projected: [2 * rank]f64 = @splat(0); + var tree: Tree = .{}; + defer { + tree.tokens.deinit(gpa); + tree.parents.deinit(gpa); + tree.scores.deinit(gpa); + } + try bestFirst(gpa, .{ .ids = &ids, .unary = &unary, .projected = &projected, .depths = 2 }, pred, succ, 3, 5, null, 100, &tree); + // logp_i = -i / 1.5 - ln(sum): the anchor's 0 and 1 (score 0.72, 1.39) come before 0's child 0 (1.44) + try std.testing.expectEqualSlices(u32, &.{ 0, 1, 0, 2, 1 }, tree.tokens.items); + try std.testing.expectEqualSlices(i32, &.{ -1, -1, 0, -1, 0 }, tree.parents.items); +} diff --git a/zig/src/families/qwen27/cuda/drafts.zig b/zig/src/families/qwen27/cuda/drafts.zig new file mode 100644 index 0000000000..02e3659524 --- /dev/null +++ b/zig/src/families/qwen27/cuda/drafts.zig @@ -0,0 +1,103 @@ +//! DFlash2 for a shared round's streams (multi.py's drafter halves): copies first, else every block in one batch. + +const std = @import("std"); +const lanes = @import("lanes"); +const st = @import("state.zig"); +const kern = @import("kernels.zig"); +const dr = @import("draft.zig"); +const dl = @import("draft_load.zig"); +const lone = @import("lone.zig"); + +const bf = 2; +pub const taps_width = dl.taps.len * dl.hidden; +/// A shared window's drafts at most (MultiDecoder's max_rows - 1). +pub const max_nodes = st.max_rows - 1; + +pub const Kind = enum { none, copy, tree }; + +/// One stream's drafting: its drafter context, its copy index, and the drafts it holds for its next window. +pub const Stream = struct { + gpa: std.mem.Allocator, + ctx: dr.Context, + copies: lone.CopyIndex, + kind: Kind = .none, + tokens: std.ArrayList(u32) = .empty, + parents: std.ArrayList(i32) = .empty, // each draft's parent draft (-1: under the pending row) + scores: std.ArrayList(f64) = .empty, // each draft's path score (best_first's; 0 for a copy) + + pub fn init(gpa: std.mem.Allocator, ctx: dr.Context) Stream { + return .{ .gpa = gpa, .ctx = ctx, .copies = .{ .gpa = gpa } }; + } + + pub fn deinit(x: *Stream) void { + x.ctx.deinit(); + x.copies.deinit(); + x.tokens.deinit(x.gpa); + x.parents.deinit(x.gpa); + x.scores.deinit(x.gpa); + } + + fn clear(x: *Stream) void { + x.kind = .none; + x.tokens.clearRetainingCapacity(); + x.parents.clearRetainingCapacity(); + x.scores.clearRetainingCapacity(); + } +}; + +/// A stream asking for its next drafts: its context through the pending token, and its sampling. +pub const Ask = struct { x: *Stream, context: []const u32, sampling: ?lanes.Sampling }; + +/// _mode, launch_blocks and finish_tree: a copied continuation where the context repeats, else a DFlash2 tree. +pub fn propose(d: *dr.DFlash2, asks: []const Ask) !void { + var blocks: [st.max_streams]dr.Block = undefined; + var which: [st.max_streams]usize = undefined; + var n: usize = 0; + for (asks, 0..) |a, k| { + const x = a.x; + x.clear(); + const copied = try x.copies.propose(a.context, max_nodes); + if (copied.len > 0) { + x.kind = .copy; + try x.tokens.appendSlice(x.gpa, copied); + for (0..copied.len) |r| { + try x.parents.append(x.gpa, @as(i32, @intCast(r)) - 1); + try x.scores.append(x.gpa, 0); + } + } else if (x.ctx.len > 0) { + blocks[n] = .{ .ctx = &x.ctx, .pending = a.context[a.context.len - 1] }; + which[n] = k; + n += 1; + } + } + if (n == 0) return; + try d.launchMany(blocks[0..n], @min(dr.block, max_nodes + 1)); + for (blocks[0..n], which[0..n], 0..) |b, k, j| { + const a = asks[k]; + try d.finish(j, b.pending, a.context.len, max_nodes, a.sampling, &d.tree); + a.x.kind = .tree; + try a.x.tokens.appendSlice(a.x.gpa, d.tree.tokens.items); + try a.x.parents.appendSlice(a.x.gpa, d.tree.parents.items); + try a.x.scores.appendSlice(a.x.gpa, d.tree.scores.items); + } +} + +/// A stream's kept rows of the last round (rows of the round's taps, in path order). +pub const Kept = struct { x: *Stream, rows: []const u32 }; + +/// add_taps_streams: every stream's kept rows' taps gathered after the round's rows, then absorbed in one batch. +pub fn absorb(d: *dr.DFlash2, ops: kern.Ops, taps: u64, copy_items: u64, kept: []const Kept) !void { + var items: std.ArrayList(kern.Copy) = .empty; + defer items.deinit(d.gpa); + var absorbs: [st.max_streams]dr.Absorb = undefined; + const row = taps_width * bf; + const gathered = taps + st.round_rows * row; + for (kept, 0..) |k, j| { + for (k.rows) |r| try items.append(d.gpa, .{ .dst = gathered + items.items.len * row, .src = taps + r * row, .bytes = row }); + absorbs[j] = .{ .ctx = &k.x.ctx, .rows = k.rows.len }; + } + if (items.items.len == 0) return; + try ops.upload(copy_items, std.mem.sliceAsBytes(items.items)); + try ops.copies(copy_items, items.items.len); + try d.absorbMany(absorbs[0..kept.len], gathered); +} diff --git a/zig/src/families/qwen27/cuda/engine.zig b/zig/src/families/qwen27/cuda/engine.zig new file mode 100644 index 0000000000..52576d7cd3 --- /dev/null +++ b/zig/src/families/qwen27/cuda/engine.zig @@ -0,0 +1,118 @@ +//! The 27B's CUDA engine for one stream: the weights, kernels and scratch, prefill and greedy serial decode. + +const std = @import("std"); +const cuda = @import("cuda"); +const c = @import("shape.zig"); +const kern = @import("kernels.zig"); +const tri = @import("triton.zig"); +const st = @import("state.zig"); +const wts = @import("weights.zig"); +const Forward = @import("forward.zig").Forward; +const Part = @import("forward.zig").Part; + +/// prefill.CHUNK: a prompt chunk's rows (prompt_rows on a GPU of 80 GB or more). +pub const prompt_rows = 4096; + +/// prefill.chunks: even chunks of at most `size` rows of [start, end); any bounds give the same bits. +pub fn chunkBounds(start: usize, end: usize, size: usize, j: usize) [2]usize { + const n = (end - start + size - 1) / size; + return .{ start + (end - start) * j / n, start + (end - start) * (j + 1) / n }; +} + +pub const Options = struct { context: usize }; + +pub const Engine = struct { + gpa: std.mem.Allocator, + ctx: *const cuda.Context, + s: cuda.Stream, + k: kern.Kernels, + w: wts.Weights, + scratch: st.Scratch, + context: usize, + + pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: []const u8, o: Options) !*Engine { + const cfg = try c.Config.read(gpa, io, dir); + const g = cfg.g; + const e = try gpa.create(Engine); + errdefer gpa.destroy(e); + e.gpa = gpa; + e.ctx = ctx; + e.context = o.context; + e.s = try cuda.Stream.init(ctx.d, true); + errdefer e.s.deinit(); + e.k = try kern.Kernels.load(gpa, io, ctx, kernels, g.linear_v_heads); + errdefer e.k.deinit(); + e.w = try wts.load(gpa, io, e.ops(), dir, cfg); + errdefer e.w.deinit(); + e.scratch = try st.Scratch.init(gpa, ctx.d, g, prompt_rows, o.context); + errdefer e.scratch.deinit(); + try e.s.synchronize(); + return e; + } + + pub fn deinit(e: *Engine) void { + e.scratch.deinit(); + e.w.deinit(); + e.k.deinit(); + e.s.deinit(); + e.gpa.destroy(e); + } + + pub fn ops(e: *Engine) kern.Ops { + return .{ .k = &e.k, .s = e.s }; + } + + pub fn forward(e: *Engine) Forward { + return .{ .gpa = e.gpa, .w = &e.w, .ops = e.ops(), .t = .{ .set = &e.k.triton, .s = e.s }, .s = &e.scratch }; + } + + /// A stream's state for `capacity` positions (its caches, recurrences and conv windows), empty. + pub fn sequence(e: *Engine, capacity: usize) !st.Seq { + return st.Seq.init(e.gpa, e.ops(), e.w.g, capacity); + } + + /// prefill_state from an empty state: the prompt in even chunks of at most `prompt_rows`, its last row normed. + pub fn prefill(e: *Engine, seq: *st.Seq, prompt: []const u32) !void { + if (prompt.len == 0) return error.EmptyPrompt; + if (prompt.len >= seq.capacity) return error.PromptTooLong; + try seq.reset(e.ops(), e.w.g); + var f = e.forward(); + const n = (prompt.len + prompt_rows - 1) / prompt_rows; + for (0..n) |j| { + const b = chunkBounds(0, prompt.len, prompt_rows, j); + try f.chunk(prompt[b[0]..b[1]], seq, j == n - 1); + } + } + + /// decode.serial_decode, greedy: one-row windows from `pending` until `count` tokens or an end token. + pub fn decode(e: *Engine, seq: *st.Seq, pending: u32, count: usize, out: *std.ArrayList(u32)) !void { + var f = e.forward(); + try out.append(e.gpa, pending); + var pick: [1]u32 = undefined; + while (out.items.len < count and !e.w.isEos(out.items[out.items.len - 1])) { + const last = out.items[out.items.len - 1]; + const part = [_]Part{.{ .seq = seq, .tokens = &.{last} }}; + try f.round(&part); + try f.picks(1, &pick); + try f.commit(&part, &.{&.{0}}); + try out.append(e.gpa, pick[0]); + } + } + + /// The prompt, then up to `max_tokens` greedy tokens (the first included), as generate(draft=False) gives them. + pub fn generate(e: *Engine, seq: *st.Seq, prompt: []const u32, max_tokens: usize, out: *std.ArrayList(u32)) !void { + const room = @min(max_tokens, seq.capacity - prompt.len); + try e.prefill(seq, prompt); + var f = e.forward(); + try f.head(seq); + var pick: [1]u32 = undefined; + try f.picks(1, &pick); + try e.decode(seq, pick[0], @max(1, room), out); + } +}; + +test "prefill.chunks splits evenly" { + try std.testing.expectEqual([2]usize{ 0, 2539 }, chunkBounds(0, 5078, 4096, 0)); + try std.testing.expectEqual([2]usize{ 2539, 5078 }, chunkBounds(0, 5078, 4096, 1)); + try std.testing.expectEqual([2]usize{ 0, 40 }, chunkBounds(0, 40, 4096, 0)); +} diff --git a/zig/src/families/qwen27/cuda/forward.zig b/zig/src/families/qwen27/cuda/forward.zig new file mode 100644 index 0000000000..4e4964be4e --- /dev/null +++ b/zig/src/families/qwen27/cuda/forward.zig @@ -0,0 +1,436 @@ +//! The 27B's forward on CUDA: verify rounds (tree_forward, multi_tree_forward), their commit, and prompt chunks. + +const std = @import("std"); +const c = @import("shape.zig"); +const kern = @import("kernels.zig"); +const tri = @import("triton.zig"); +const st = @import("state.zig"); +const wts = @import("weights.zig"); +const rnd = @import("round.zig"); + +const bf = 2; +pub const Part = rnd.Part; +/// The target layers DFlash2 reads (dflash_config.target_layer_ids). +pub const tap_layers = [_]usize{ 5, 19, 33, 47, 61 }; + +pub const Forward = struct { + gpa: std.mem.Allocator, + w: *const wts.Weights, + ops: kern.Ops, + t: tri.Tri, + s: *st.Scratch, + dump: ?Dump = null, // a debugging copy of every norm's (h, y) rows, as capture.py's hook writes them + taps: ?u64 = null, // rows of the drafter's five layer taps (5 x hidden bf16), written by round and chunk + + pub const Dump = struct { io: std.Io, dir: []const u8, n: usize = 0, rows: usize = 0 }; + + fn g(f: *const Forward) c.Geometry { + return f.w.g; + } + + fn gdnShape(f: *const Forward) tri.Gdn { + const g_ = f.g(); + return .{ .c = g_.convDim(), .kh = g_.linear_k_heads, .vh = g_.linear_v_heads, .dk = c.linear_dim, .keep = c.conv_taps - 1 }; + } + + fn heads(f: *const Forward) kern.Heads { + return .{ .hk = f.g().linear_k_heads, .hv = f.g().linear_v_heads, .dv = c.linear_dim }; + } + + fn attnShape(f: *const Forward) tri.Attn { + return .{ .heads = f.g().query_heads, .kv_heads = f.g().kv_heads, .dim = c.head_dim, .half = c.rotary_dim / 2 }; + } + + fn upload32(f: *Forward, dst: u64, values: []const i32) !void { + try f.ops.upload(dst, std.mem.sliceAsBytes(values)); + try f.ops.s.synchronize(); // the host copy must outlive the async upload + } + + /// add_rmsnorm into the scratch's other residual buffer; returns the residual stream's new home. + fn norm(f: *Forward, x: u64, r: ?u64, weight: u64, rows: usize) !u64 { + const out = if (r == null) x else if (x == f.s.x) f.s.h else f.s.x; + try f.t.addRmsnorm(x, r, weight, out, f.s.y, f.s.xs, rows, f.g().hidden, c.eps); + if (f.dump) |*d| try f.saveRows(d, out, f.s.y, rows); + return out; + } + + /// Layer `i`'s tap, when the drafter reads it: (x + pending) of the call's rows into the taps buffer. + fn tapLayer(f: *Forward, i: usize, x: u64, rows: usize) !void { + const out = f.taps orelse return; + const j = std.mem.indexOfScalar(usize, &tap_layers, i) orelse return; + const h = f.g().hidden; + try f.ops.tap(x, f.s.pending, out, rows, h, tap_layers.len * h, j * h); + } + + fn saveRows(f: *Forward, d: *Dump, h: u64, y: u64, rows: usize) !void { + const bytes = try f.gpa.alloc(u8, rows * f.g().hidden * bf); + defer f.gpa.free(bytes); + for ([_]u64{ h, y }, [_][]const u8{ "h", "y" }) |src, name| { + try f.ops.download(bytes, src); + try f.ops.s.synchronize(); + var buf: [256]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, "{s}/{d:0>3}_{s}.bin", .{ d.dir, d.n, name }); + try std.Io.Dir.cwd().writeFile(d.io, .{ .sub_path = path, .data = bytes }); + } + d.n += 1; + } + + /// The window of one stream at its position (tree_forward): logits (rows, vocab) bf16 in the scratch, records kept. + pub fn window(f: *Forward, tokens: []const u32, seq: *st.Seq) !void { + return f.round(&.{.{ .seq = seq, .tokens = tokens }}); + } + + /// Several streams' chain windows in one forward (multi_tree_forward; one stream: tree_forward), rows in order. + pub fn round(f: *Forward, parts: []const Part) !void { + const s = f.s; + const g_ = f.g(); + const w = f.w; + const r = try rnd.stage(f.gpa, f.ops, f.t, s, g_, parts); + const W = r.rows; + try f.t.embed(r.ids, w.embed.w, w.embed.s, w.embed.b, s.x, W, g_.hidden); + var x = s.x; + var pending: ?u64 = null; + var lin: usize = 0; + var att: usize = 0; + for (w.layers, 0..) |layer, i| { + x = try f.norm(x, pending, layer.input_norm, W); + switch (layer.mixer) { + .delta => |d| { + const rec = s.records[i]; + try f.ops.dense(s.y, s.xs, d.qkv, rec.qkv, W); + try f.ops.dense(s.y, s.xs, d.z, s.z, W); + try f.ops.dense(s.y, s.xs, d.b, s.b, W); + try f.ops.dense(s.y, s.xs, d.a, s.a, W); + const sid: ?u64 = if (r.multi) r.sids else null; + try f.t.gdnPre(rec.qkv, r.conv(parts, s, g_, i, lin), d.conv, r.windows, sid, s.a, s.b, d.a_log, d.dt_bias, rec.q, rec.k, rec.v, rec.g, rec.beta, W, f.gdnShape()); + const state = if (r.multi) 0 else parts[0].seq.rec[i]; + const table = if (r.multi) r.table(lin) else 0; + try f.ops.gdnTree(rec.q, rec.k, rec.v, rec.g, rec.beta, state, table, if (r.multi) r.starts else 0, r.plan, s.yr, W, r.streams, r.slots, r.most, f.heads()); + try f.t.gatedNorm(s.yr, s.z, d.norm, s.gated, s.gated_xs, W, g_.linear_v_heads, c.linear_dim, c.eps); + try f.ops.dense(s.gated, s.gated_xs, d.out, s.r, W); + lin += 1; + }, + .attention => |a| { + const rec = s.attn_records[i]; + try f.ops.dense(s.y, s.xs, a.q, s.qg, W); + try f.ops.dense(s.y, s.xs, a.k, s.key, W); + try f.ops.dense(s.y, s.xs, a.v, rec.v, W); + try f.t.attnPrep(s.qg, s.key, a.q_norm, a.k_norm, r.pos, w.inv_freq, s.q_rot, rec.k, W, f.attnShape(), c.eps); + try f.t.attention(s.q_rot, rec.k, rec.v, s.origin, r.offsets(i, att), r.attn, .{ .o = s.part_o, .m = s.part_m, .l = s.part_l }, s.attn, f.attnShape()); + try f.t.gateMul(s.attn, s.qg, s.gated, s.gated_xs, W, g_.query_heads, c.head_dim); + try f.ops.dense(s.gated, s.gated_xs, a.o, s.r, W); + att += 1; + }, + } + x = try f.norm(x, s.r, layer.post_norm, W); + try f.ops.dense(s.y, s.xs, layer.gate, s.gate, W); + try f.ops.dense(s.y, s.xs, layer.up, s.up, W); + try f.t.swiglu(s.gate, s.up, s.act, s.act_xs, W, g_.intermediate); + try f.ops.dense(s.act, s.act_xs, layer.down, s.pending, W); + pending = s.pending; + try f.tapLayer(i, x, W); + } + const spare = if (x == s.x) s.h else s.x; + try f.t.addRmsnorm(x, pending, w.norm, spare, s.last_h, s.last_xs, W, g_.hidden, c.eps); + if (f.dump) |*d| try f.saveRows(d, spare, s.last_h, W); + try f.ops.dense(s.last_h, s.last_xs, w.head, s.logits, W); + } + + /// commit_streams after a round over `parts`: each stream keeps the window rows of its accepted path. + pub fn commit(f: *Forward, parts: []const Part, paths: []const []const u32) !void { + const s = f.s; + const g_ = f.g(); + const S = parts.len; + var width: usize = 0; + for (parts, paths) |p, path| { + if (path.len < 1 or path.len > p.tokens.len) return error.InvalidQwenCommit; + for (path) |row| if (row >= p.tokens.len) return error.InvalidQwenCommit; + width += p.tokens.len; + } + // gdn.replay_table: each DeltaNet layer's k, v, g, beta, then each stream's state of each layer + var table: std.ArrayList(u64) = .empty; + defer table.deinit(f.gpa); + var layers: usize = 0; + for (0..g_.layers) |i| if (c.linear(i)) { + const rc = s.records[i]; + try table.appendSlice(f.gpa, &.{ rc.k, rc.v, rc.g, rc.beta }); + layers += 1; + }; + for (parts) |p| for (0..g_.layers) |i| if (c.linear(i)) try table.append(f.gpa, p.seq.rec[i]); + try f.ops.upload(s.replay_table, std.mem.sliceAsBytes(table.items)); + // path_indices: each stream's accepted rows (round rows) padded to the round's width, then its count + var rows: std.ArrayList(i32) = .empty; + defer rows.deinit(f.gpa); + var base: usize = 0; + for (parts, paths) |p, path| { + for (0..width) |j| try rows.append(f.gpa, if (j < path.len) @intCast(base + path[j]) else 0); + try rows.append(f.gpa, @intCast(path.len)); + base += p.tokens.len; + } + try f.ops.upload(s.replay_rows, std.mem.sliceAsBytes(rows.items)); + try f.ops.s.synchronize(); + try f.ops.gdnReplay(s.replay_table, layers, S, s.replay_rows, width + 1, s.replay_rows + width * 4, width + 1, f.heads()); + const row = g_.convDim() * bf; + const keep = c.conv_taps - 1; + const kv = g_.kvInner() * bf; + // conv rows: the last three of [committed | accepted rows]; old ones saved first, then written with the rest + var save: std.ArrayList(kern.Copy) = .empty; + defer save.deinit(f.gpa); + var write: std.ArrayList(kern.Copy) = .empty; + defer write.deinit(f.gpa); + base = 0; + for (parts, paths, 0..) |p, path, k| { + const n = path.len; + var lin: usize = 0; + for (0..g_.layers) |i| { + if (c.linear(i)) { + const old = s.conv_old + (k * g_.layers + lin) * keep * row; + const stay = keep -| n; // committed rows that stay: old[n..3) go to new[0..3-n) + if (stay > 0) { + try save.append(f.gpa, .{ .dst = old, .src = p.seq.conv[i] + n * row, .bytes = stay * row }); + try write.append(f.gpa, .{ .dst = p.seq.conv[i], .src = old, .bytes = stay * row }); + } + for (path[n - (keep - stay) ..], stay..) |acc, j| try write.append(f.gpa, .{ .dst = p.seq.conv[i] + j * row, .src = s.records[i].qkv + (base + acc) * row, .bytes = row }); + lin += 1; + } else { + for (path, 0..) |acc, j| { + const at = (p.seq.pos + j) * kv; + try write.append(f.gpa, .{ .dst = p.seq.keys[i] + at, .src = s.attn_records[i].k + (base + acc) * kv, .bytes = kv }); + try write.append(f.gpa, .{ .dst = p.seq.values[i] + at, .src = s.attn_records[i].v + (base + acc) * kv, .bytes = kv }); + } + } + } + base += p.tokens.len; + p.seq.pos += n; + } + const second = s.copy_items + st.copy_items * @sizeOf(kern.Copy); + try f.ops.upload(s.copy_items, std.mem.sliceAsBytes(save.items)); + try f.ops.upload(second, std.mem.sliceAsBytes(write.items)); + try f.ops.copies(s.copy_items, save.items.len); + try f.ops.copies(second, write.items.len); + try f.ops.s.synchronize(); // the tables' host copies go when this returns + } + + /// prefill_chunk: `ids` committed at the stream's position; `last` leaves the last row normed, with group_sums. + pub fn chunk(f: *Forward, ids: []const u32, seq: *st.Seq, last: bool) !void { + const W = ids.len; + const s = f.s; + const g_ = f.g(); + const w = f.w; + if (W < 1 or W > s.rows) return error.ChunkTooLong; + if (seq.pos + W > seq.capacity) return error.PromptTooLong; + const p0 = seq.pos; + { + const host = try f.gpa.alloc(i32, W * (2 + c.conv_taps)); + defer f.gpa.free(host); + for (ids, 0..) |tok, r| { + host[r] = @intCast(tok); + host[W + r] = @intCast(p0 + r); + for (0..c.conv_taps) |j| host[2 * W + r * c.conv_taps + j] = @intCast(r + j); + } + try f.upload32(s.ids, host[0..W]); + try f.upload32(s.pos, host[W .. 2 * W]); + try f.upload32(s.windows, host[2 * W ..]); + } + try f.t.embed(s.ids, w.embed.w, w.embed.s, w.embed.b, s.x, W, g_.hidden); + var x = s.x; + var pending: ?u64 = null; + const kv = g_.kvInner() * bf; + const row = g_.convDim() * bf; + const keep = c.conv_taps - 1; + for (w.layers, 0..) |layer, i| { + x = try f.norm(x, pending, layer.input_norm, W); + switch (layer.mixer) { + .delta => |d| { + try f.ops.prefillDense(s.y, d.qkv, s.qkv, W); + try f.ops.prefillDense(s.y, d.z, s.z, W); + try f.ops.prefillDense(s.y, d.b, s.b, W); + try f.ops.prefillDense(s.y, d.a, s.a, W); + try f.t.gdnPre(s.qkv, seq.conv[i], d.conv, s.windows, null, s.a, s.b, d.a_log, d.dt_bias, s.gq, s.gk, s.gv, s.gg, s.gbeta, W, f.gdnShape()); + // each thread reads its state rows before it writes them: the chain may end in place + try f.ops.gdnPrompt(s.gq, s.gk, s.gv, s.gg, s.gbeta, seq.rec[i], seq.rec[i], s.yr, W, f.heads()); + if (W >= keep) { + try f.ops.copy(seq.conv[i], s.qkv + (W - keep) * row, keep * row); + } else { + try f.ops.copy(s.conv_tmp, seq.conv[i], keep * row); + try f.ops.copy(s.conv_tmp + keep * row, s.qkv, W * row); + try f.ops.copy(seq.conv[i], s.conv_tmp + W * row, keep * row); + } + try f.t.gatedNorm(s.yr, s.z, d.norm, s.gated, s.gated_xs, W, g_.linear_v_heads, c.linear_dim, c.eps); + try f.ops.prefillDense(s.gated, d.out, s.r, W); + }, + .attention => |a| { + try f.ops.prefillDense(s.y, a.q, s.qg, W); + try f.ops.prefillDense(s.y, a.k, s.key, W); + try f.ops.prefillDense(s.y, a.v, seq.values[i] + p0 * kv, W); + try f.t.attnPrep(s.qg, s.key, a.q_norm, a.k_norm, s.pos, w.inv_freq, s.q_rot, seq.keys[i] + p0 * kv, W, f.attnShape(), c.eps); + const scale: f32 = @floatCast(std.math.pow(f64, c.head_dim, -0.5)); + try f.ops.prefillAttention(s.q_rot, seq.keys[i], seq.values[i], s.attn, p0, W, g_.query_heads, g_.kv_heads, scale); + try f.t.gateMul(s.attn, s.qg, s.gated, s.gated_xs, W, g_.query_heads, c.head_dim); + try f.ops.prefillDense(s.gated, a.o, s.r, W); + }, + } + x = try f.norm(x, s.r, layer.post_norm, W); + try f.ops.prefillDense(s.y, layer.gate, s.gate, W); + try f.ops.prefillDense(s.y, layer.up, s.up, W); + try f.t.swiglu(s.gate, s.up, s.act, s.act_xs, W, g_.intermediate); + try f.ops.prefillDense(s.act, layer.down, s.pending, W); + pending = s.pending; + try f.tapLayer(i, x, W); + } + seq.pos = p0 + W; + if (!last) return; + const at = (W - 1) * g_.hidden * bf; + const spare = if (x == s.x) s.h else s.x; + try f.t.addRmsnorm(x + at, pending.? + at, w.norm, spare, seq.head_in, s.last_xs, 1, g_.hidden, c.eps); + try f.t.groupSums(seq.head_in, seq.head_xs, g_.hidden, 1, g_.hidden); + } + + /// One stream's share of a batched prompt pass: its ids, committed at its position; `last` normalizes its last row. + pub const Piece = struct { ids: []const u32, seq: *st.Seq, last: bool }; + + /// prefill_rows: several streams' prompt chunks in one pass (each stream's conv, DeltaNet and attention its own). + pub fn chunks(f: *Forward, pieces: []const Piece) !void { + const s = f.s; + const g_ = f.g(); + const w = f.w; + const S = pieces.len; + if (S == 0 or S > st.max_streams) return error.InvalidQwenWindows; + var starts: [st.max_streams + 1]usize = undefined; + starts[0] = 0; + for (pieces, 0..) |p, k| { + if (p.ids.len == 0) return error.ChunkTooLong; + if (p.seq.pos + p.ids.len > p.seq.capacity) return error.PromptTooLong; + starts[k + 1] = starts[k] + p.ids.len; + } + const W = starts[S]; + if (W > s.rows) return error.ChunkTooLong; + const keep = c.conv_taps - 1; + const kv = g_.kvInner() * bf; + const row = g_.convDim() * bf; + { + // ids, positions, each row's stream and its conv window: [the streams' kept rows; every prompt row] + const host = try f.gpa.alloc(i32, W * (3 + c.conv_taps)); + defer f.gpa.free(host); + for (pieces, 0..) |p, k| for (p.ids, 0..) |tok, r| { + const at = starts[k] + r; + host[at] = @intCast(tok); + host[W + at] = @intCast(p.seq.pos + r); + host[2 * W + at] = @intCast(k); + for (0..c.conv_taps) |j| host[3 * W + at * c.conv_taps + j] = @intCast(if (r + j < keep) r + j else r + j + starts[k]); + }; + try f.upload32(s.ids, host[0..W]); + try f.upload32(s.pos, host[W .. 2 * W]); + try f.upload32(s.sids, host[2 * W .. 3 * W]); + try f.upload32(s.windows, host[3 * W ..]); + } + // copies the pass needs: every stream's conv rows stacked by DeltaNet layer, then each layer's writes + var items: std.ArrayList(kern.Copy) = .empty; + defer items.deinit(f.gpa); + var lin_n: usize = 0; + for (0..g_.layers) |i| if (c.linear(i)) { + const cat = s.conv_cat + lin_n * st.max_streams * keep * row; + for (pieces, 0..) |p, k| try items.append(f.gpa, .{ .dst = cat + k * keep * row, .src = p.seq.conv[i], .bytes = keep * row }); + lin_n += 1; + }; + const staged = items.items.len; + var at_layer: [256]usize = undefined; // each layer's first write, then the end + lin_n = 0; + for (0..g_.layers) |i| { + at_layer[i] = items.items.len; + if (c.linear(i)) { + // the last `keep` rows of [kept rows; the stream's prompt rows] + const cat = s.conv_cat + lin_n * st.max_streams * keep * row; + for (pieces, 0..) |p, k| { + const n = p.ids.len; + const o = starts[k]; + if (n >= keep) { + try items.append(f.gpa, .{ .dst = p.seq.conv[i], .src = s.qkv + (o + n - keep) * row, .bytes = keep * row }); + } else { + try items.append(f.gpa, .{ .dst = p.seq.conv[i], .src = cat + (k * keep + n) * row, .bytes = (keep - n) * row }); + try items.append(f.gpa, .{ .dst = p.seq.conv[i] + (keep - n) * row, .src = s.qkv + o * row, .bytes = n * row }); + } + } + lin_n += 1; + } else { + for (pieces, 0..) |p, k| { + const o = starts[k]; + const n = p.ids.len; + try items.append(f.gpa, .{ .dst = p.seq.keys[i] + p.seq.pos * kv, .src = s.prompt_keys + o * kv, .bytes = n * kv }); + try items.append(f.gpa, .{ .dst = p.seq.values[i] + p.seq.pos * kv, .src = s.prompt_values + o * kv, .bytes = n * kv }); + } + } + } + at_layer[g_.layers] = items.items.len; + if (items.items.len > 2 * st.copy_items) return error.InvalidQwenWindows; + try f.ops.upload(s.copy_items, std.mem.sliceAsBytes(items.items)); + try f.ops.copies(s.copy_items, staged); + const item = @sizeOf(kern.Copy); + try f.t.embed(s.ids, w.embed.w, w.embed.s, w.embed.b, s.x, W, g_.hidden); + var x = s.x; + var pending: ?u64 = null; + lin_n = 0; + for (w.layers, 0..) |layer, i| { + x = try f.norm(x, pending, layer.input_norm, W); + switch (layer.mixer) { + .delta => |d| { + try f.ops.prefillDense(s.y, d.qkv, s.qkv, W); + try f.ops.prefillDense(s.y, d.z, s.z, W); + try f.ops.prefillDense(s.y, d.b, s.b, W); + try f.ops.prefillDense(s.y, d.a, s.a, W); + const cat = s.conv_cat + lin_n * st.max_streams * keep * row; + try f.t.gdnPre(s.qkv, cat, d.conv, s.windows, s.sids, s.a, s.b, d.a_log, d.dt_bias, s.gq, s.gk, s.gv, s.gg, s.gbeta, W, f.gdnShape()); + for (pieces, 0..) |p, k| { + const o = starts[k]; + // each thread reads its state rows before it writes them: the chain may end in place + try f.ops.gdnPrompt(s.gq + o * g_.kInner() * bf, s.gk + o * g_.kInner() * bf, s.gv + o * g_.vInner() * bf, s.gg + o * g_.linear_v_heads * 4, s.gbeta + o * g_.linear_v_heads * 4, p.seq.rec[i], p.seq.rec[i], s.yr + o * g_.vInner() * bf, p.ids.len, f.heads()); + } + try f.ops.copies(s.copy_items + at_layer[i] * item, at_layer[i + 1] - at_layer[i]); + try f.t.gatedNorm(s.yr, s.z, d.norm, s.gated, s.gated_xs, W, g_.linear_v_heads, c.linear_dim, c.eps); + try f.ops.prefillDense(s.gated, d.out, s.r, W); + lin_n += 1; + }, + .attention => |a| { + try f.ops.prefillDense(s.y, a.q, s.qg, W); + try f.ops.prefillDense(s.y, a.k, s.key, W); + try f.ops.prefillDense(s.y, a.v, s.prompt_values, W); + try f.t.attnPrep(s.qg, s.key, a.q_norm, a.k_norm, s.pos, w.inv_freq, s.q_rot, s.prompt_keys, W, f.attnShape(), c.eps); + try f.ops.copies(s.copy_items + at_layer[i] * item, at_layer[i + 1] - at_layer[i]); + const scale: f32 = @floatCast(std.math.pow(f64, c.head_dim, -0.5)); + const qrow = g_.query_heads * c.head_dim * bf; + for (pieces, 0..) |p, k| try f.ops.prefillAttention(s.q_rot + starts[k] * qrow, p.seq.keys[i], p.seq.values[i], s.attn + starts[k] * qrow, p.seq.pos, p.ids.len, g_.query_heads, g_.kv_heads, scale); + try f.t.gateMul(s.attn, s.qg, s.gated, s.gated_xs, W, g_.query_heads, c.head_dim); + try f.ops.prefillDense(s.gated, a.o, s.r, W); + }, + } + x = try f.norm(x, s.r, layer.post_norm, W); + try f.ops.prefillDense(s.y, layer.gate, s.gate, W); + try f.ops.prefillDense(s.y, layer.up, s.up, W); + try f.t.swiglu(s.gate, s.up, s.act, s.act_xs, W, g_.intermediate); + try f.ops.prefillDense(s.act, layer.down, s.pending, W); + pending = s.pending; + try f.tapLayer(i, x, W); + } + const spare = if (x == s.x) s.h else s.x; + for (pieces, 0..) |p, k| { + p.seq.pos += p.ids.len; + if (!p.last) continue; + const at = (starts[k + 1] - 1) * g_.hidden * bf; + try f.t.addRmsnorm(x + at, pending.? + at, w.norm, spare, p.seq.head_in, s.last_xs, 1, g_.hidden, c.eps); + try f.t.groupSums(p.seq.head_in, p.seq.head_xs, g_.hidden, 1, g_.hidden); + } + try f.ops.s.synchronize(); // the copy table's host list goes when this returns + } + + /// The head over the stream's last prompt row: logits (1, vocab) in the scratch. + pub fn head(f: *Forward, seq: *const st.Seq) !void { + try f.ops.dense(seq.head_in, seq.head_xs, f.w.head, f.s.logits, 1); + } + + /// Greedy picks of the scratch's first `rows` logits rows (torch.argmax, the first maximum). + pub fn picks(f: *Forward, rows: usize, out: []u32) !void { + try f.ops.argmax(f.s.logits, c.vocab, c.vocab, f.s.picks, rows); + try f.ops.download(std.mem.sliceAsBytes(out[0..rows]), f.s.picks); + try f.ops.s.synchronize(); + } +}; diff --git a/zig/src/families/qwen27/cuda/kernels.zig b/zig/src/families/qwen27/cuda/kernels.zig new file mode 100644 index 0000000000..4b486922f8 --- /dev/null +++ b/zig/src/families/qwen27/cuda/kernels.zig @@ -0,0 +1,365 @@ +//! The 27B's CUDA kernels: our .cu fatbins with the Python wrappers' launch logic, and the captured Triton set. + +const std = @import("std"); +const cuda = @import("cuda"); +pub const torch_ops = @import("nemotron").torch_ops; + +/// Mangled names of the instantiations the copies in zig/kernels/cuda export (cuobjdump -symbols of each fatbin). +const sym = struct { + const group = "_ZN12tf_qmm_group12group_kernelILi64ELi16ELi64ELi1ELi4ELi8ELb0ELb0ELb0ELb0EEEvPK13__nv_bfloat16PKfNS_5PartsEiiiii"; + const wide = [_][:0]const u8{ + "_ZN12tf_qmm_group12group_kernelILi64ELi32ELi64ELi1ELi4ELi4ELb0ELb0ELb0ELb0EEEvPK13__nv_bfloat16PKfNS_5PartsEiiiii", + "_ZN12tf_qmm_group12group_kernelILi64ELi64ELi64ELi1ELi4ELi4ELb0ELb0ELb0ELb0EEEvPK13__nv_bfloat16PKfNS_5PartsEiiiii", + "_ZN12tf_qmm_group12group_kernelILi64ELi64ELi128ELi2ELi4ELi3ELb0ELb0ELb0ELb0EEEvPK13__nv_bfloat16PKfNS_5PartsEiiiii", + }; + const gemv = "_ZN12tf_lane_gemv11gemv_kernelILi64ELi64ELi8EEEvPK13__nv_bfloat16PKfNS_4PartEiii"; + const prefill_mm = "_ZN14tf_qmm_prefill14prefill_kernelILi64ELi128ELi128ELi2ELi2ELi2ELb0EEEvPK13__nv_bfloat16PKjS3_S3_Pviiiiii"; + const pattn = "_ZN20tf_prefill_attention12pattn_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiif"; + const chain128 = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16Li128ELi32EEEvPKT_S4_PKS1_PKfS8_S8_PfPS1_iii"; + const chain64 = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16Li64ELi32EEEvPKT_S4_PKS1_PKfS8_S8_PfPS1_iii"; + const argmax = "tf_argmax_rows_i32_kernel"; +}; + +/// qmm_group.cu's Part and Parts, passed by value: four projections at most, one used here. +pub const Part = extern struct { w: u64, scales: u64, biases: u64, out: u64, n: c_int, npad: c_int, sk: c_int, tiles: c_int, first: c_int }; +pub const Parts = extern struct { p: [4]Part, count: c_int }; + +/// lane_gemv.cu's Part: one projection whose column tiles the CTAs share out. +pub const GemvPart = extern struct { w: u64, scales: u64, biases: u64, out: u64, n: c_int, npad: c_int, sk: c_int, tiles: c_int }; + +/// gdn.cu's Pending (the tree kernel's rows still to fold): all null here, commits replay instead. +pub const Pending = extern struct { k: u64 = 0, v: u64 = 0, g: u64 = 0, beta: u64 = 0, rows: u64 = 0, row_stride: c_int = 0, counts: u64 = 0, count_stride: c_int = 0 }; + +comptime { + std.debug.assert(@sizeOf(Part) == 56 and @sizeOf(Parts) == 232 and @sizeOf(GemvPart) == 48 and @sizeOf(Pending) == 64); +} + +pub const group_smem: u32 = 35328; // LaneTile<64, 16, 64, 1, 4, 8>::SMEM +/// qmm_group's GB10 tiles 3-5 for wider rounds: rows a tile, columns a tile, threads, LaneTile::SMEM. +pub const Wide = struct { bm: usize, bn: usize, threads: u32, smem: u32 }; +pub const wide = [_]Wide{ .{ .bm = 32, .bn = 64, .threads = 128, .smem = 26112 }, .{ .bm = 64, .bn = 64, .threads = 128, .smem = 43008 }, .{ .bm = 64, .bn = 128, .threads = 256, .smem = 39168 } }; +pub const prefill_mm_smem: u32 = 41984; // Tile<64, 128, 128, 2, 2, 2>::SMEM: prompt_tile 9, two stages +pub const pattn_smem: u32 = 98304; // two 32-key slots of 256 dims beside eight warps' staged queries + +/// One item of a batched copy: 16-byte aligned pointers, a multiple of 16 bytes. +pub const Copy = extern struct { dst: u64, src: u64, bytes: u64 }; + +/// A tiled 4-bit projection: packed words, (kg, npad) scales and biases, n outputs from k inputs. +pub const QLinear = struct { w: u64, s: u64, b: u64, n: usize, k: usize, npad: usize }; + +pub const Kernels = struct { + d: *const cuda.Driver, + mods: [15]cuda.Module, + triton: cuda.aot.Set, + group: cuda.Function, + wide: [wide.len]cuda.Function, // tiles 3-5: rows <= 32, <= 64, more + gemv: cuda.Function, + prefill_mm: cuda.Function, + pattn: cuda.Function, + trees: [cuda.kernels.gdn_variants.len]cuda.Function, // tree_kernel by gdn_variants: [0] the chain one + chip: [3]c_int, // major, minor, SMs: what dispatch_tree reads + replay: cuda.Function, + prompt_chain: cuda.Function, + prompt_rows: usize, // the prompt chain's value rows a block: 64 when heads < SMs + pack_dense: cuda.Function, + transpose16: cuda.Function, + argmax: cuda.Function, + torch: torch_ops.Functions, + copy_batch: cuda.Function, + tap: cuda.Function, + rms_norm: cuda.Function, + inv_freq: cuda.Function, + torch_rms: cuda.Function, // F.rms_norm's bits on bf16 rows of 5120 (torch_ops/norm_rotary.cu) + rotary: cuda.Function, + gemv_blocks: usize, // resident lane_gemv CTAs: per SM times SMs + gemv_rows: usize, // windows of at most this many rows take lane_gemv (none; TF_QWEN27_GEMV_ROWS) + gb10: bool, + discrete: bool, // the card has its own memory: checkpoint bytes reach it through page-locked slots + + /// Loads every module; `triton_dir` holds the captured aot.json and cubins for this GPU. + pub fn load(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, triton_dir: []const u8, heads: usize) !Kernels { + const d = ctx.d; + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var k: Kernels = undefined; + k.d = d; + const kk = cuda.kernels; + const images = [_][]const u8{ kk.qmm_group, kk.qmm_prefill, kk.lane_gemv, kk.prefill_attention, kk.gdn, kk.gdn_prefill, kk.affine4_pack, kk.torch_argmax, kk.torch_topk, kk.torch_pointwise, kk.torch_indexing, kk.torch_movement, kk.torch_nemotron_constants, kk.qwen_ops, kk.torch_norm_rotary }; + var loaded: usize = 0; + errdefer for (k.mods[0..loaded]) |*m| m.unload(); + for (images, 0..) |img, i| { + k.mods[i] = try cuda.Module.load(d, img); + loaded += 1; + } + k.group = try k.mods[0].function(sym.group); + for (&k.wide, sym.wide) |*f, name| f.* = try k.mods[0].function(name); + k.prefill_mm = try k.mods[1].function(sym.prefill_mm); + k.gemv = try k.mods[2].function(sym.gemv); + k.pattn = try k.mods[3].function(sym.pattn); + for (&k.trees, cuda.kernels.gdn_variants) |*f, v| f.* = try k.mods[4].function(v.symbol); + k.replay = try k.mods[4].function(cuda.kernels.gdn_symbols.replay_bf16); + k.pack_dense = try k.mods[6].function(cuda.qlinear.symbols.pack_words); + k.transpose16 = try k.mods[6].function(cuda.qlinear.symbols.pack_scales); + k.argmax = try k.mods[7].function(sym.argmax); + k.torch = try torch_ops.Functions.resolve(k.mods[7..13]); + k.copy_batch = try k.mods[13].function("tf_copy_batch"); + k.tap = try k.mods[13].function("tf_tap"); + k.rms_norm = try k.mods[13].function("tf_rms_norm"); + k.inv_freq = try k.mods[13].function("tf_inv_freq"); + k.rotary = try k.mods[13].function("tf_rotary"); + k.torch_rms = try k.mods[14].function("tf_dflash_rms5120_bf16_fma_kernel"); + const sms: usize = @intCast(try ctx.attribute(.multiprocessor_count)); + // gdn_prefill_cuda: a block takes 128 value rows, or 64 when there are fewer heads than SMs + k.prompt_rows = if (heads >= sms) 128 else 64; + k.prompt_chain = try k.mods[5].function(if (k.prompt_rows == 128) sym.chain128 else sym.chain64); + k.triton = try cuda.aot.Set.load(gpa, io, d, ctx.device, triton_dir); + errdefer k.triton.deinit(); + try k.group.allowDynamicShared(group_smem); + for (k.wide, wide) |f, t| try f.allowDynamicShared(t.smem); + try k.gemv.allowDynamicShared(group_smem); + try k.prefill_mm.allowDynamicShared(prefill_mm_smem); + try k.pattn.allowDynamicShared(pattn_smem); + k.gemv_blocks = @max(1, try k.gemv.occupancy(128, group_smem)) * sms; + const major = try ctx.attribute(.compute_capability_major); + const minor = try ctx.attribute(.compute_capability_minor); + k.gb10 = major == 12 and minor == 1; + k.discrete = try ctx.attribute(.integrated) == 0; + k.gemv_rows = 0; // a GB10 runs the 27B's projections faster in Python's clusters, 1 to 16 rows alike + if (std.c.getenv("TF_QWEN27_GEMV_ROWS")) |v| k.gemv_rows = std.fmt.parseInt(usize, std.mem.span(v), 10) catch k.gemv_rows; + k.chip = .{ major, minor, @intCast(sms) }; + return k; + } + + pub fn deinit(k: *Kernels) void { + k.triton.deinit(); + for (&k.mods) |*m| m.unload(); + } +}; + +/// qmm.split_k: K slices fixed by the weight's shape, never by the row count. +pub fn splitK(n: usize, k: usize) usize { + const tiles = (n + 63) / 64; + const groups = k / 64; + var sk: usize = 1; + while (sk < 8 and tiles * sk < 192 and groups % (sk * 2) == 0 and groups / (sk * 2) >= 8) sk *= 2; + return sk; +} + +fn int(x: usize) c_int { + return @intCast(x); +} + +fn u(x: usize) u32 { + return @intCast(x); +} + +/// The GDN shapes every launch takes: key heads, value heads, value rows a head. +pub const Heads = struct { hk: usize, hv: usize, dv: usize }; + +/// Launch helpers on one stream; each mirrors the Python wrapper it replaces. +pub const Ops = struct { + k: *const Kernels, + s: cuda.Stream, + + fn go(o: Ops, f: cuda.Function, grid: [3]usize, block: u32, shared: u32, args: *cuda.Args) !void { + try cuda.launch.launch(f, .{ .grid = .{ .x = u(grid[0]), .y = u(grid[1]), .z = u(grid[2]) }, .block = .{ .x = block }, .shared = shared }, o.s, args); + } + + /// qmm.matmul on sm_12x: x (rows, k) bf16 with group sums xs -> out (rows, n) bf16, qmm_group's bits. + pub fn dense(o: Ops, x: u64, xs: u64, q: QLinear, out: u64, rows: usize) !void { + const sk = splitK(q.n, q.k); + if (rows > 16) return o.wideTile(x, xs, q, out, rows, sk); + // Python's clusters, a CTA a K slice; lane_gemv (byte-equal) when TF_QWEN27_GEMV_ROWS asks for it + return if (sk > 1 and rows <= o.k.gemv_rows) o.gemv(x, xs, q, out, rows, sk) else o.cluster(x, xs, q, out, rows, sk); + } + + /// qmm.matmul at a K split the caller names (matmul_rows takes the stacked weight's for each part). + pub fn denseSplit(o: Ops, x: u64, xs: u64, q: QLinear, out: u64, rows: usize, sk: usize) !void { + if (rows > 16) return o.wideTile(x, xs, q, out, rows, sk); + return if (sk > 1 and rows <= o.k.gemv_rows) o.gemv(x, xs, q, out, rows, sk) else o.cluster(x, xs, q, out, rows, sk); + } + + /// tree_forward's taps: bf16(x + pending) of `rows` rows into columns [col, col + d) of rows `stride` wide. + pub fn tap(o: Ops, x: u64, pending: u64, out: u64, rows: usize, d: usize, stride: usize, col: usize) !void { + var a: cuda.Args = .{}; + for ([_]u64{ x, pending, out }) |v| a.add(v); + for ([_]usize{ d, stride, col }) |v| a.add(int(v)); + try o.go(o.k.tap, .{ rows, 4, 1 }, 256, 0, &a); + } + + /// lane_gemv: every K slice of a column tile in one CTA, summed in slice order, CTAs looping over the tiles. + fn gemv(o: Ops, x: u64, xs: u64, q: QLinear, out: u64, rows: usize, sk: usize) !void { + const tiles = (q.n + 63) / 64; + var a: cuda.Args = .{}; + a.add(x); + a.add(xs); + a.add(GemvPart{ .w = q.w, .scales = q.s, .biases = q.b, .out = out, .n = int(q.n), .npad = int(q.npad), .sk = int(sk), .tiles = int(tiles) }); + for ([_]usize{ rows, q.k, q.k }) |v| a.add(int(v)); + const cfg: cuda.Config = .{ .grid = .{ .x = u(@min(tiles, o.k.gemv_blocks)) }, .block = .{ .x = 128 }, .shared = group_smem, .pdl = o.k.gb10 }; + try cuda.launch.launch(o.k.gemv, cfg, o.s, &a); + } + + /// qmm_group's tile 2 with one K slice: a CTA a column tile. + fn cluster(o: Ops, x: u64, xs: u64, q: QLinear, out: u64, rows: usize, sk: usize) !void { + const tiles = (q.n + 63) / 64; + var parts: Parts = std.mem.zeroes(Parts); + parts.count = 1; + parts.p[0] = .{ .w = q.w, .scales = q.s, .biases = q.b, .out = out, .n = int(q.n), .npad = int(q.npad), .sk = int(sk), .tiles = int(tiles), .first = 0 }; + const rows_t = (rows + 15) / 16; + var a: cuda.Args = .{}; + a.add(x); + a.add(xs); + a.add(parts); + for ([_]usize{ rows, q.k, q.k, rows_t, sk }) |v| a.add(int(v)); + const cfg: cuda.Config = .{ + .grid = .{ .x = u(rows_t * tiles * sk) }, + .block = .{ .x = 128 }, + .shared = group_smem, + .cluster = if (sk > 1) .{ .x = u(sk) } else null, + .pdl = o.k.gb10, + }; + try cuda.launch.launch(o.k.group, cfg, o.s, &a); + } + + /// qmm_group's dispatch on a GB10 past 16 rows: tile 3, 4 or 5, a cluster of `sk` CTAs a column tile. + fn wideTile(o: Ops, x: u64, xs: u64, q: QLinear, out: u64, rows: usize, sk: usize) !void { + const i: usize = if (rows <= 32) 0 else if (rows <= 64) 1 else 2; + const t = wide[i]; + const tiles = (q.n + t.bn - 1) / t.bn; + const rows_t = (rows + t.bm - 1) / t.bm; + var parts: Parts = std.mem.zeroes(Parts); + parts.count = 1; + parts.p[0] = .{ .w = q.w, .scales = q.s, .biases = q.b, .out = out, .n = int(q.n), .npad = int(q.npad), .sk = int(sk), .tiles = int(tiles), .first = 0 }; + var a: cuda.Args = .{}; + a.add(x); + a.add(xs); + a.add(parts); + for ([_]usize{ rows, q.k, q.k, rows_t, sk }) |v| a.add(int(v)); + const cfg: cuda.Config = .{ + .grid = .{ .x = u(rows_t * tiles * sk) }, + .block = .{ .x = t.threads }, + .shared = t.smem, + .cluster = if (sk > 1) .{ .x = u(sk) } else null, + .pdl = o.k.gb10, + }; + try cuda.launch.launch(o.k.wide[i], cfg, o.s, &a); + } + + /// qmm.prefill_matmul at prompt_tile 9: weights rounded once to bf16, one fp32 chain over K; bf16 out. + pub fn prefillDense(o: Ops, x: u64, q: QLinear, out: u64, rows: usize) !void { + const rows_t = (rows + 127) / 128; + const band = (12 << 20) / (128 * q.k * 2); + const group = @max(1, @min(rows_t, band)); + var a: cuda.Args = .{}; + for ([_]u64{ x, q.w, q.s, q.b, out }) |v| a.add(v); + for ([_]usize{ rows, q.n, q.k, q.npad, q.k, group }) |v| a.add(int(v)); + try o.go(o.k.prefill_mm, .{ rows_t * ((q.n + 127) / 128), 1, 1 }, 128, prefill_mm_smem, &a); + } + + /// gdn.tree (dispatch_tree): y from one `state`, or each stream's own by `table` and `starts`; `slots` 0: chains. + pub fn gdnTree(o: Ops, q: u64, k: u64, v: u64, g: u64, beta: u64, state: u64, table: u64, starts: u64, plan: u64, y: u64, rows: usize, streams: usize, slots: usize, most: usize, h: Heads) !void { + const variant = cuda.kernels.treeVariant(@intCast(slots), @intCast(streams), o.k.chip[0], o.k.chip[1], o.k.chip[2]); + const index = for (cuda.kernels.gdn_variants, 0..) |x, n| { + if (std.mem.eql(u8, x.symbol, variant.symbol)) break n; + } else unreachable; + var a: cuda.Args = .{}; + for ([_]u64{ q, k, v, g, beta, state, table, starts, plan }) |x| a.add(x); + a.add(int(rows)); + a.add(y); + for ([_]usize{ h.hk, h.hv, h.dv }) |x| a.add(int(x)); + a.add(Pending{}); + a.add(@as(u64, 0)); + a.add(@as(u64, 0)); + a.add(h.dv % variant.r == 0 and v % (2 * @as(u64, @min(variant.r, 8))) == 0); + const shared = 16 * @as(usize, variant.warps) * variant.slots * variant.r * 32 + (if (variant.chain) 0 else 4 * 3 * most); + try o.go(o.k.trees[index], .{ (h.dv + variant.r * variant.warps - 1) / (variant.r * variant.warps), h.hv, streams }, 32 * variant.warps, @intCast(shared), &a); + } + + /// gdn.replay in place: each stream's accepted rows stepped into the states the table names. + pub fn gdnReplay(o: Ops, table: u64, layers: usize, streams: usize, rows: u64, row_stride: usize, counts: u64, count_stride: usize, h: Heads) !void { + var a: cuda.Args = .{}; + a.add(table); + a.add(int(layers)); + a.add(rows); + a.add(int(row_stride)); + a.add(counts); + a.add(int(count_stride)); + a.add(@as(u64, 0)); + for ([_]usize{ h.hk, h.hv, h.dv }) |x| a.add(int(x)); + try o.go(o.k.replay, .{ (h.dv + 31) / 32, h.hv, layers * streams }, 128, 0, &a); + } + + /// gdn.chain: a prompt chunk's rows from `state` (read only) to `last`, chunk-invariant bits. + pub fn gdnPrompt(o: Ops, q: u64, k: u64, v: u64, g: u64, beta: u64, state: u64, last: u64, y: u64, rows: usize, h: Heads) !void { + var a: cuda.Args = .{}; + for ([_]u64{ q, k, v, g, beta, state, last, y }) |x| a.add(x); + for ([_]usize{ rows, h.hk, h.hv }) |x| a.add(int(x)); + const r = o.k.prompt_rows; + try o.go(o.k.prompt_chain, .{ h.hv, 128 / r, 1 }, u(2 * r), 0, &a); + } + + /// prefill_attention (head dim 256, two query heads a block): q (rows, heads, 256) at positions p0.. + pub fn prefillAttention(o: Ops, q: u64, kc: u64, vc: u64, out: u64, p0: usize, rows: usize, heads: usize, kv_heads: usize, scale: f32) !void { + const g = heads / kv_heads; + const hpc = 2; + var a: cuda.Args = .{}; + for ([_]u64{ q, kc, vc, out }) |v| a.add(v); + for ([_]usize{ p0, rows, heads, kv_heads, g }) |v| a.add(int(v)); + a.add(scale); + const block_rows = 16 * (8 / hpc); + try o.go(o.k.pattn, .{ (rows + block_rows - 1) / block_rows, kv_heads * (g / hpc), 1 }, 256, pattn_smem, &a); + } + + /// torch.argmax(rows of bf16 logits) as int32: the first maximum, a NaN first. + pub fn argmax(o: Ops, logits: u64, vocab: usize, ld: usize, out: u64, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(logits); + a.add(out); + for ([_]usize{ rows, vocab, ld }) |v| a.add(@as(i64, @intCast(v))); + a.add(@as(i32, 0)); // dtype 0: bf16 + try o.go(o.k.argmax, .{ rows, 1, 1 }, 1024, 0, &a); + } + + /// The torch-op replacements on this stream (topk and casts for sampled draws). + pub fn torch(o: Ops) torch_ops.Torch { + return .{ .f = &o.k.torch, .s = o.s }; + } + + /// qwen_ops.cu's tf_copy_batch: `count` (dst, src, bytes) items from the device table `items`, one launch. + pub fn copies(o: Ops, items: u64, count: usize) !void { + if (count == 0) return; + var a: cuda.Args = .{}; + a.add(items); + try o.go(o.k.copy_batch, .{ count, 4, 1 }, 256, 0, &a); + } + + pub fn copy(o: Ops, dst: u64, src: u64, bytes: usize) !void { + if (bytes == 0) return; + try o.k.d.check(o.k.d.api.cuMemcpyDtoDAsync_v2(dst, src, bytes, o.s.handle), "cuMemcpyDtoDAsync"); + } + + pub fn fill32(o: Ops, dst: u64, value: u32, words: usize) !void { + try o.k.d.check(o.k.d.api.cuMemsetD32Async(dst, value, words, o.s.handle), "cuMemsetD32Async"); + } + + pub fn upload(o: Ops, dst: u64, bytes: []const u8) !void { + if (bytes.len == 0) return; + try o.k.d.check(o.k.d.api.cuMemcpyHtoDAsync_v2(dst, bytes.ptr, bytes.len, o.s.handle), "cuMemcpyHtoDAsync"); + } + + pub fn download(o: Ops, dst: []u8, src: u64) !void { + if (dst.len == 0) return; + try o.k.d.check(o.k.d.api.cuMemcpyDtoHAsync_v2(dst.ptr, src, dst.len, o.s.handle), "cuMemcpyDtoHAsync"); + } +}; + +test "split_k follows the 27B's shapes" { + try std.testing.expectEqual(@as(usize, 2), splitK(10240, 5120)); // qkv + try std.testing.expectEqual(@as(usize, 2), splitK(6144, 5120)); // z + try std.testing.expectEqual(@as(usize, 8), splitK(48, 5120)); // b, a + try std.testing.expectEqual(@as(usize, 1), splitK(17408, 5120)); // gate, up + try std.testing.expectEqual(@as(usize, 4), splitK(5120, 17408)); // down + try std.testing.expectEqual(@as(usize, 4), splitK(5120, 6144)); // out_proj, o_proj + try std.testing.expectEqual(@as(usize, 1), splitK(12288, 5120)); // q with its gate + try std.testing.expectEqual(@as(usize, 8), splitK(1024, 5120)); // k, v + try std.testing.expectEqual(@as(usize, 1), splitK(248320, 5120)); // head +} diff --git a/zig/src/families/qwen27/cuda/lanes.zig b/zig/src/families/qwen27/cuda/lanes.zig new file mode 100644 index 0000000000..8a5f86fad8 --- /dev/null +++ b/zig/src/families/qwen27/cuda/lanes.zig @@ -0,0 +1,549 @@ +//! The 27B's CUDA engine behind the lane core: every stream's window in one verify, DFlash2 drafts in one batch. + +const std = @import("std"); +const lanes = @import("lanes"); +const c = @import("shape.zig"); +const st = @import("state.zig"); +const Engine = @import("engine.zig").Engine; +const Part = @import("forward.zig").Part; +const Forward = @import("forward.zig").Forward; +const prompt_rows = @import("engine.zig").prompt_rows; +const dl = @import("draft_load.zig"); +const dr = @import("draft.zig"); +const drafts = @import("drafts.zig"); +const lone = @import("lone.zig"); +const trees = @import("tree.zig"); +const be = lanes.backend; + +/// The row counts calibrate times (calibration_rows without the tile steps a GB10 skips), to 16 a stream. +const calibration = [_]usize{ 1, 2, 4, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256 }; + +/// The last verified round, committed when the next call needs the streams' states (keep may cut it first). +const Pending = struct { + streams: [st.max_streams]*lanes.Stream = undefined, + parts: [st.max_streams]Part = undefined, + paths: [st.max_streams][]const u32 = undefined, + path_rows: [st.round_rows]u32 = undefined, // the round's kept rows, each stream's path in its own slice + tokens: [st.round_rows]u32 = undefined, + parents: [st.round_rows]i32 = undefined, + starts: [st.max_streams]usize = undefined, // each window's first row in the round + n: usize = 0, +}; + +pub const Cuda = struct { + gpa: std.mem.Allocator, + e: *Engine, + streams: u32, + seqs: std.AutoHashMapUnmanaged(*lanes.Stream, *st.Seq) = .empty, + logits: []u16 = &.{}, // a whole row on the host, for a draw with top_k off + cand_values: []f32 = &.{}, // the rows' top candidates on the host + cand_ids: []i64 = &.{}, + values: []f64 = &.{}, + pending: Pending = .{}, + drafter: ?*dr.DFlash2 = null, // DFlash2, when its checkpoint is pulled and drafts are on + drafting: std.AutoHashMapUnmanaged(*lanes.Stream, *drafts.Stream) = .empty, + costs: [calibration.len + 1]lanes.config.Cost = undefined, // the forward's ms by a round's rows (calibrate) + cost_count: usize = 0, + + pub fn init(gpa: std.mem.Allocator, e: *Engine, streams: u32) !Cuda { + return .{ + .gpa = gpa, + .e = e, + .streams = streams, + .logits = try gpa.alloc(u16, c.vocab), + .cand_values = try gpa.alloc(f32, st.round_rows * st.max_candidates), + .cand_ids = try gpa.alloc(i64, st.round_rows * st.max_candidates), + .values = try gpa.alloc(f64, st.max_candidates), + }; + } + + pub fn deinit(x: *Cuda) void { + var it = x.seqs.valueIterator(); + while (it.next()) |seq| { + seq.*.deinit(); + x.gpa.destroy(seq.*); + } + x.seqs.deinit(x.gpa); + var dit = x.drafting.valueIterator(); + while (dit.next()) |ds| { + ds.*.deinit(); + x.gpa.destroy(ds.*); + } + x.drafting.deinit(x.gpa); + x.gpa.free(x.logits); + x.gpa.free(x.cand_values); + x.gpa.free(x.cand_ids); + x.gpa.free(x.values); + } + + /// The facts the round loop reads: 16-row windows in one forward; with DFlash2, host trees with node chances. + pub fn facts(x: *const Cuda) lanes.Model { + var m: lanes.Model = .{ .exact_width = st.max_rows, .hidden_rows = true, .batch_rows = st.round_rows, .max_streams = @min(x.streams, st.max_streams), .streams_exact = true }; + if (x.drafter != null) { + m.mtp = true; + m.speculate = true; + m.speculate_early = false; + m.drafts = drafts.max_nodes; + m.draft_probabilities = true; + m.draft_streams = true; + } + const timed = x.costs[0..x.cost_count]; + var narrow: usize = 0; + while (narrow < timed.len and timed[narrow].width <= st.max_rows) narrow += 1; + m.window_costs = timed[0..narrow]; + m.shared_costs = timed; + return m; + } + + /// multi.calibrate: the forward's ms (median of three) by the rows `streams` windows bring, on a fresh state. + pub fn calibrate(x: *Cuda, io: std.Io, streams: usize) !void { + var seq = x.e.sequence(st.max_rows + 2) catch |err| return if (err == error.OutOfMemory) err else error.OutOfDeviceMemory; + defer seq.deinit(); + const zeros: [st.max_rows]u32 = @splat(0); + const most: usize = st.max_rows * @as(usize, @min(streams, st.max_streams)); + var rows: [calibration.len + 1]usize = undefined; + var n: usize = 0; + for (calibration) |r| if (r < most) { + rows[n] = r; + n += 1; + }; + rows[n] = most; + n += 1; + var f = x.e.forward(); + const clock = std.Io.Clock.awake; + for (rows[0..n], x.costs[0..n]) |r, *cost| { + const parts_n = (r + st.max_rows - 1) / st.max_rows; + var parts: [st.max_streams]Part = undefined; + for (parts[0..parts_n], 0..) |*part, i| part.* = .{ .seq = &seq, .tokens = zeros[0 .. r / parts_n + @intFromBool(i < r % parts_n)] }; + var times: [3]f64 = undefined; + for (0..4) |rep| { + try f.ops.s.synchronize(); + const t0 = clock.now(io).toNanoseconds(); + try f.round(parts[0..parts_n]); + try f.ops.s.synchronize(); + if (rep > 0) times[rep - 1] = @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e6; + } + std.mem.sort(f64, ×, {}, std.sort.asc(f64)); + cost.* = .{ .width = @intCast(r), .ms = times[1] }; + } + x.cost_count = n; + } + + pub fn backend(x: *Cuda) be.Backend { + return .{ .ptr = x, .vtable = &.{ .prefill = prefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .probabilities = probabilities, .tree = tree, .release = release, .prefill_many = prefillMany } }; + } + + /// The stream's drafting (its DFlash2 context and copy index), made on first use. + pub fn draftingOf(x: *Cuda, s: *lanes.Stream) !*drafts.Stream { + if (x.drafting.get(s)) |ds| return ds; + const ds = try x.gpa.create(drafts.Stream); + errdefer x.gpa.destroy(ds); + const ctx = dr.Context.init(x.e.ctx.d) catch |err| return if (err == error.OutOfMemory) err else error.OutOfDeviceMemory; + ds.* = drafts.Stream.init(x.gpa, ctx); + errdefer ds.deinit(); + try x.drafting.put(x.gpa, s, ds); + return ds; + } + + fn cast(p: *anyopaque) *Cuda { + return @ptrCast(@alignCast(p)); + } + + fn seqOf(x: *Cuda, s: *lanes.Stream) !*st.Seq { + return x.seqs.get(s) orelse error.UnknownQwenStream; + } + + /// Commits the last verified round: every stream its kept rows (its whole window unless keep cut it). + fn settle(x: *Cuda) !void { + const p = &x.pending; + if (p.n == 0) return; + const n = p.n; + p.n = 0; + var f = x.e.forward(); + try f.commit(p.parts[0..n], p.paths[0..n]); + } + + /// The stream's state, the last round committed first. + fn settled(x: *Cuda, s: *lanes.Stream) !*st.Seq { + try x.settle(); + return x.seqOf(s); + } + + /// The round's logits rows drawn: greedy by one argmax, sampled from top (top_k + 8) GPU candidates or whole rows. + pub fn drawRows(x: *Cuda, rules: []const ?lanes.Sampling, positions: []const u64, out: []u32) !void { + const rows = positions.len; + var f = x.e.forward(); + const s = f.s; + try f.picks(rows, out[0..rows]); + var want: usize = 0; + for (rules) |r| if (r) |rule| if (rule.temperature > 0 and rule.top_k != 0) { + want = @max(want, @min(c.vocab, @as(usize, rule.top_k) + 8)); + }; + if (want > st.max_candidates) want = 0; // past the GPU's candidates: whole rows below + if (want > 0) { + const t = f.ops.torch(); + try t.toF32(s.logits, s.logits32, rows * c.vocab); + try t.topk(s.logits32, c.vocab, rows, want, s.cand_values, s.cand_ids, s.topk_scratch); + try f.ops.download(std.mem.sliceAsBytes(x.cand_values[0 .. rows * want]), s.cand_values); + try f.ops.download(std.mem.sliceAsBytes(x.cand_ids[0 .. rows * want]), s.cand_ids); + try f.ops.s.synchronize(); + } + for (rules, positions, out[0..rows], 0..) |rule_, pos, *o, r| { + const rule = rule_ orelse continue; + if (rule.temperature <= 0) continue; + if (rule.top_k != 0 and want > 0) { + const vals = x.values[0..want]; + for (vals, x.cand_values[r * want ..][0..want]) |*v, w| v.* = w; + const ids = x.cand_ids[r * want ..][0..want]; + o.* = @intCast(try lanes.sampling.choose(x.gpa, vals, @ptrCast(ids), pos, rule)); + continue; + } + try f.ops.download(std.mem.sliceAsBytes(x.logits), s.logits + r * c.vocab * 2); + try f.ops.s.synchronize(); + o.* = try draw(x.gpa, x.logits, rule, pos); + } + } + + /// A new stream's state, sized for its prompt and reply. + pub fn open(x: *Cuda, s: *lanes.Stream) !*st.Seq { + try x.settle(); + const ids = s.prompt(); + if (ids.len == 0 or x.seqs.contains(s)) return error.InvalidQwenPrompt; + const capacity = @min(x.e.context, ids.len + s.max_new + st.max_rows); + if (ids.len >= capacity) return error.PromptTooLong; + const seq = try x.gpa.create(st.Seq); + errdefer x.gpa.destroy(seq); + seq.* = x.e.sequence(capacity) catch |err| return if (err == error.OutOfMemory) err else error.OutOfDeviceMemory; + errdefer seq.deinit(); + try x.seqs.put(x.gpa, s, seq); + return seq; + } + + fn prefill(p: *anyopaque, s: *lanes.Stream) !void { + const x = cast(p); + const seq = try x.open(s); + errdefer x.dropSeq(s); + try x.prefillOpened(s, seq); + } + + /// prefill_state into an opened stream: the prompt in chunks, a drafting stream's last window of taps absorbed. + fn prefillOpened(x: *Cuda, s: *lanes.Stream, seq: *st.Seq) !void { + if (x.drafter) |d| if (s.drafts) { + const ds = try x.draftingOf(s); + return lone.prefill(x.e, seq, &ds.ctx, d, s.prompt()); + }; + try x.e.prefill(seq, s.prompt()); + } + + /// prefill_batch: prompts in shared passes of at most a chunk's rows (a longer one alone, in its chunks). + fn prefillMany(p: *anyopaque, streams: []const *lanes.Stream, errs: []?anyerror) !void { + const x = cast(p); + var pieces: [st.max_streams]Forward.Piece = undefined; + var which: [st.max_streams]usize = undefined; + var n: usize = 0; + var rows: usize = 0; + for (streams, errs, 0..) |s, *err, i| { + const seq = x.open(s) catch |e| { + err.* = e; + continue; + }; + const ids = s.prompt(); + if (ids.len > prompt_rows) { + x.prefillOpened(s, seq) catch |e| { + x.dropSeq(s); + err.* = e; + }; + continue; + } + if (n == st.max_streams or rows + ids.len > prompt_rows) { + x.pass(streams, errs, pieces[0..n], which[0..n]); + n = 0; + rows = 0; + } + pieces[n] = .{ .ids = ids, .seq = seq, .last = true }; + which[n] = i; + n += 1; + rows += ids.len; + } + if (n > 0) x.pass(streams, errs, pieces[0..n], which[0..n]); + } + + /// One shared prompt pass; on a failure every stream in it fails. + fn pass(x: *Cuda, streams: []const *lanes.Stream, errs: []?anyerror, pieces: []const Forward.Piece, which: []const usize) void { + x.passPieces(streams, pieces, which) catch |e| for (which) |i| { + x.dropSeq(streams[i]); + errs[i] = e; + }; + } + + fn passPieces(x: *Cuda, streams: []const *lanes.Stream, pieces: []const Forward.Piece, which: []const usize) !void { + var f = x.e.forward(); + const d = x.drafter orelse return f.chunks(pieces); + f.taps = x.e.scratch.taps; + try f.chunks(pieces); + // each drafting stream's last window of taps, consecutive whole prompts absorbed together + const row = drafts.taps_width * 2; + var group: [st.max_streams]dr.Absorb = undefined; + var g: usize = 0; + var g_rows: usize = 0; + var g_from: usize = 0; // the group's first tap row + var at: usize = 0; // this piece's first row in the pass + for (pieces, which) |pc, i| { + defer at += pc.ids.len; + const s = streams[i]; + if (!s.drafts) continue; + const ds = try x.draftingOf(s); + ds.ctx.len = 0; + ds.ctx.end = 0; + const tap_from = pc.ids.len -| dl.window; + ds.ctx.skip(tap_from); + const taken = pc.ids.len - tap_from; + if (g > 0 and (tap_from > 0 or g_from + g_rows != at or g_rows + taken > dl.window + 1)) { + try d.absorbMany(group[0..g], x.e.scratch.taps + g_from * row); + g = 0; + } + if (g == 0) { + g_from = at + tap_from; + g_rows = 0; + } + group[g] = .{ .ctx = &ds.ctx, .rows = taken }; + g += 1; + g_rows += taken; + } + if (g > 0) try d.absorbMany(group[0..g], x.e.scratch.taps + g_from * row); + } + + fn dropSeq(x: *Cuda, s: *lanes.Stream) void { + if (x.seqs.fetchRemove(s)) |entry| { + entry.value.deinit(); + x.gpa.destroy(entry.value); + } + } + + fn first(p: *anyopaque, s: *lanes.Stream, position: u64) !u64 { + const x = cast(p); + const seq = try x.settled(s); + if (position != seq.pos) return error.InvalidQwenPosition; + var f = x.e.forward(); + try f.head(seq); + var out: [1]u32 = undefined; + try x.drawRows(&.{s.sampling}, &.{position}, &out); + return out[0]; + } + + fn queue(p: *anyopaque, s: *lanes.Stream, feed: be.Feed, position: u64) !u64 { + const x = cast(p); + const seq = try x.settled(s); + if (position != seq.pos + 1) return error.InvalidQwenPosition; + const token: u32 = switch (feed) { + .value => |v| v, + .handle => |h| @intCast(h), + }; + var f = x.e.forward(); + const part = [_]Part{.{ .seq = seq, .tokens = &.{token} }}; + try f.round(&part); + var out: [1]u32 = undefined; + try x.drawRows(&.{s.sampling}, &.{position}, &out); + try f.commit(&part, &.{&.{0}}); + return out[0]; + } + + fn read(_: *anyopaque, handle: u64) !u32 { + if (handle >= c.vocab) return error.InvalidQwenToken; + return @intCast(handle); + } + + /// One forward over every window (one stream: tree_forward's, several: multi_tree_forward's), each row drawn. + fn verify(p: *anyopaque, windows: []const be.Window, out: []be.Verified) !void { + const x = cast(p); + if (windows.len != out.len or windows.len == 0 or windows.len > st.max_streams) return error.InvalidQwenWindows; + try x.settle(); + const pend = &x.pending; + var total: usize = 0; + for (windows, out, 0..) |w, o, k| { + const rows = w.rows(); + if (w.held != 0 or w.positions.len != rows or rows > st.max_rows or total + rows > st.round_rows) return error.UnsupportedQwenWindow; + if (o.sampled.len != rows or o.drafts.len != w.tokens.len) return error.InvalidQwenOutputs; + const seq = try x.seqOf(w.stream); + pend.tokens[total] = w.pending; + @memcpy(pend.tokens[total + 1 ..][0..w.tokens.len], w.tokens); + const parents: ?[]const i32 = if (w.parents) |given| blk: { + if (given.len != rows) return error.InvalidQwenWindows; + @memcpy(pend.parents[total..][0..rows], given); + break :blk pend.parents[total..][0..rows]; + } else null; + // each row's draw is keyed at its depth past the committed position + var depth: [st.max_rows]usize = undefined; + if (parents) |ps| { + try trees.depths(ps, depth[0..rows]); + } else for (depth[0..rows], 0..) |*d, r| { + d.* = r; + } + for (w.positions, depth[0..rows]) |pos, d| if (pos != seq.pos + d + 1) return error.InvalidQwenPosition; + pend.parts[k] = .{ .seq = seq, .tokens = pend.tokens[total..][0..rows], .parents = parents }; + pend.starts[k] = total; + pend.streams[k] = w.stream; + // a window kept whole: its rows in order (keep replaces them with its path) + for (pend.path_rows[total..][0..rows], 0..) |*row, r| row.* = @intCast(r); + pend.paths[k] = pend.path_rows[total..][0..rows]; + total += rows; + } + var f = x.e.forward(); + if (x.drafter != null) f.taps = x.e.scratch.taps; + try f.round(pend.parts[0..windows.len]); + pend.n = windows.len; + var rules: [st.round_rows]?lanes.Sampling = undefined; + var positions: [st.round_rows]u64 = undefined; + var drawn: [st.round_rows]u32 = undefined; + var row: usize = 0; + for (windows) |w| for (w.positions) |pos| { + rules[row] = w.stream.sampling; + positions[row] = pos; + row += 1; + }; + try x.drawRows(rules[0..total], positions[0..total], &drawn); + row = 0; + for (windows, out) |w, o| { + @memcpy(o.sampled, drawn[row..][0..o.sampled.len]); + row += o.sampled.len; + @memcpy(o.drafts, w.tokens); + } + } + + /// A window keeps its accepted path (a chain's prefix, or a tree's root-to-node rows); verify keeps all of it. + fn keep(p: *anyopaque, windows: []const be.Window, paths: []const []const u32) !void { + const x = cast(p); + const pend = &x.pending; + for (windows, paths) |w, path| { + const k = for (pend.streams[0..pend.n], 0..) |s, k| { + if (s == w.stream) break k; + } else return error.UnknownQwenStream; + const rows = pend.parts[k].tokens.len; + if (path.len == 0 or path.len > rows) return error.InvalidQwenCommit; + const slot: [*]u32 = @constCast(pend.paths[k].ptr); + for (path, 0..) |r, i| { + if (r >= rows) return error.InvalidQwenCommit; + slot[i] = r; + } + pend.paths[k] = slot[0..path.len]; + } + } + + /// The kept rows' taps into each stream's drafter context, then each stream's next drafts. + fn draft(p: *anyopaque, requests: []const be.DraftRequest) !void { + const x = cast(p); + const d = x.drafter orelse { + for (requests) |r| if (r.depth != 0) return error.QwenCheckpointHasNoDraftHead; + return; + }; + const pend = &x.pending; + var kept: [st.max_streams]drafts.Kept = undefined; + var rows: [st.round_rows]u32 = undefined; + var asks: [st.max_streams]drafts.Ask = undefined; + var firsts: [st.max_streams]std.ArrayList(u32) = @splat(.empty); + defer for (&firsts) |*l| l.deinit(x.gpa); + var nk: usize = 0; + var nr: usize = 0; + var na: usize = 0; + for (requests) |r| { + if (na == st.max_streams) return error.InvalidQwenWindows; + const ds = x.drafting.get(r.stream) orelse continue; + var context = r.stream.context.items; + if (r.rows) |path| { + const k = for (pend.streams[0..pend.n], 0..) |s, k| { + if (s == r.stream) break k; + } else return error.UnknownQwenStream; + for (path, rows[nr..][0..path.len]) |row, *g| g.* = @intCast(pend.starts[k] + row); + kept[nk] = .{ .x = ds, .rows = rows[nr..][0..path.len] }; + nk += 1; + nr += path.len; + } else if (r.first) |feed| { + // the prompt's taps went in with its prefill; the first token ends the context the copies read + const token: u32 = switch (feed) { + .value => |v| v, + .handle => |h| try read(p, h), + }; + try firsts[na].appendSlice(x.gpa, context); + try firsts[na].append(x.gpa, token); + context = firsts[na].items; + } + asks[na] = .{ .x = ds, .context = context, .sampling = r.stream.sampling }; + na += 1; + } + const f = x.e.forward(); + try drafts.absorb(d, f.ops, x.e.scratch.taps, x.e.scratch.copy_items, kept[0..nk]); + try drafts.propose(d, asks[0..na]); + } + + /// The drafts a stream holds as host tokens and parents (a copy's as a chain). + fn tree(p: *anyopaque, s: *lanes.Stream, gpa: std.mem.Allocator) !?lanes.stream.Held { + const x = cast(p); + const ds = x.drafting.get(s) orelse return null; + const tokens = try gpa.dupe(u32, ds.tokens.items); + errdefer gpa.free(tokens); + const parents: ?[]i32 = if (ds.kind == .tree) try gpa.dupe(i32, ds.parents.items) else null; + return .{ .count = @intCast(tokens.len), .tokens = tokens, .parents = parents }; + } + + /// Each held draft's chance of landing: a tree node's exp(-path score) (allocate's), a copied token's 1. + fn probabilities(p: *anyopaque, s: *lanes.Stream, out: []f64) !bool { + const x = cast(p); + const ds = x.drafting.get(s) orelse return false; + if (out.len > ds.scores.items.len) return false; + for (out, ds.scores.items[0..out.len]) |*o, score| o.* = @exp(-score); + return true; + } + + fn release(p: *anyopaque, s: *lanes.Stream) void { + const x = cast(p); + x.settle() catch |err| std.log.err("committing the last round before a release: {s}", .{@errorName(err)}); + if (x.seqs.fetchRemove(s)) |entry| { + entry.value.deinit(); + x.gpa.destroy(entry.value); + } + if (x.drafting.fetchRemove(s)) |entry| { + entry.value.deinit(); + x.gpa.destroy(entry.value); + } + } +}; + +fn value(word: u16) f64 { + return @as(f32, @bitCast(@as(u32, word) << 16)); +} + +/// The Metal backend's draw: the top-k candidates by value then id, then the shared fp64 keyed sampler. +pub fn draw(gpa: std.mem.Allocator, logits: []const u16, settings: ?lanes.Sampling, position: u64) !u32 { + var best: usize = 0; + for (logits, 0..) |word, id| { + const x = value(word); + if (!std.math.isFinite(x)) return error.NonfiniteQwenLogits; + if (x > value(logits[best])) best = id; + } + const sampling = settings orelse return @intCast(best); + if (sampling.temperature <= 0) return @intCast(best); + const k = if (sampling.top_k == 0) logits.len else @min(logits.len, sampling.top_k); + const values = try gpa.alloc(f64, k); + defer gpa.free(values); + const ids = try gpa.alloc(u64, k); + defer gpa.free(ids); + var filled: usize = 0; + for (logits, 0..) |word, id| { + const x = value(word); + if (k == logits.len) { + values[id] = x; + ids[id] = id; + continue; + } + if (filled == k and x <= values[k - 1]) continue; + var at = @min(filled, k - 1); + while (at > 0 and x > values[at - 1]) : (at -= 1) { + values[at] = values[at - 1]; + ids[at] = ids[at - 1]; + } + values[at] = x; + ids[at] = id; + filled = @min(filled + 1, k); + } + return @intCast(try lanes.sampling.choose(gpa, values, ids, position, sampling)); +} diff --git a/zig/src/families/qwen27/cuda/lone.zig b/zig/src/families/qwen27/cuda/lone.zig new file mode 100644 index 0000000000..0397ea706f --- /dev/null +++ b/zig/src/families/qwen27/cuda/lone.zig @@ -0,0 +1,181 @@ +//! decode.draft_decode for one stream: copies from the context, else a DFlash2 tree; verify, walk, commit, absorb. + +const std = @import("std"); +const lanes = @import("lanes"); +const c = @import("shape.zig"); +const st = @import("state.zig"); +const tree = @import("tree.zig"); +const kern = @import("kernels.zig"); +const dr = @import("draft.zig"); +const dl = @import("draft_load.zig"); +const Engine = @import("engine.zig").Engine; +const Forward = @import("forward.zig").Forward; +const Part = @import("forward.zig").Part; +const Lanes = @import("lanes.zig").Cuda; + +const bf = 2; +const taps_width = dl.taps.len * dl.hidden; + +/// decode.CopyIndex: earlier 8-token matches of the context's suffix, the longest continuation proposed. +pub const CopyIndex = struct { + pub const n = 8; + const Key = [n]u32; + gpa: std.mem.Allocator, + positions: std.AutoHashMapUnmanaged(Key, std.ArrayList(usize)) = .empty, + indexed: usize = 0, + + pub fn deinit(x: *CopyIndex) void { + var it = x.positions.valueIterator(); + while (it.next()) |l| l.deinit(x.gpa); + x.positions.deinit(x.gpa); + } + + fn update(x: *CopyIndex, context: []const u32) !void { + if (context.len < n) return; + const last = context.len - n; // the trailing query itself stays out of the index + var start = x.indexed; + while (start < last) : (start += 1) { + const gop = try x.positions.getOrPut(x.gpa, context[start..][0..n].*); + if (!gop.found_existing) gop.value_ptr.* = .empty; + try gop.value_ptr.append(x.gpa, start); + } + x.indexed = @max(x.indexed, last); + } + + /// The longest continuation after an earlier occurrence of the last 8 tokens (latest first), at least 8 long. + pub fn propose(x: *CopyIndex, context: []const u32, max_nodes: usize) ![]const u32 { + if (context.len < 2 * n) return &.{}; + try x.update(context); + const starts = x.positions.get(context[context.len - n ..][0..n].*) orelse return &.{}; + var best: []const u32 = &.{}; + var i = starts.items.len; + while (i > 0) { + i -= 1; + const from = starts.items[i] + n; + const cont = context[from..@min(context.len, from + max_nodes)]; + if (cont.len > best.len) { + best = cont; + if (best.len == max_nodes) break; + } + } + return if (best.len >= n) best else &.{}; + } +}; + +/// decode.next_copy_rows: a copy's next window, twice as wide after a whole copy, half after a broken one. +pub fn nextCopyRows(rows: usize, whole: bool, tree_rows: usize, max_rows: usize) usize { + const first = @min(max_rows, @max(tree_rows, 16)); + return if (whole) @min(max_rows, @max(rows, first) * 2) else @max(first, @min(rows, max_rows) / 2); +} + +pub const Stats = struct { rounds: usize = 0, drafted: usize = 0, accepted: usize = 0 }; + +/// prefill_state with a drafter: the prompt in even chunks, its last `window` rows' taps into the context. +pub fn prefill(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, prompt: []const u32) !void { + try seq.reset(e.ops(), e.w.g); + ctx.len = 0; + ctx.end = 0; + const tap_from = prompt.len -| dl.window; + ctx.skip(tap_from); + var f = e.forward(); + f.taps = e.scratch.taps; + const rows = @import("engine.zig").prompt_rows; + const chunks = (prompt.len + rows - 1) / rows; + for (0..chunks) |j| { + const b = @import("engine.zig").chunkBounds(0, prompt.len, rows, j); + try f.chunk(prompt[b[0]..b[1]], seq, j == chunks - 1); + if (b[1] <= tap_from) continue; + const skip = tap_from -| b[0]; + try d.absorb(ctx, e.scratch.taps + skip * taps_width * bf, b[1] - b[0] - skip); + } +} + +/// draft_decode, greedy: rounds until `count` tokens or an end token; the first token is `pending`. +pub fn decode(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, prompt: []const u32, pending: u32, count: usize, max_rows: usize, out: *std.ArrayList(u32), stats: *Stats) !void { + const gpa = e.gpa; + var context: std.ArrayList(u32) = .empty; + defer context.deinit(gpa); + try context.appendSlice(gpa, prompt); + try out.append(gpa, pending); + try context.append(gpa, pending); + var copies: CopyIndex = .{ .gpa = gpa }; + defer copies.deinit(); + const tree_rows = max_rows; + var copy_rows = nextCopyRows(tree_rows, false, tree_rows, max_rows); + var tokens: [st.max_rows]u32 = undefined; + var parents: [st.max_rows]i32 = undefined; + var sampled: [st.max_rows]u32 = undefined; + var path: [st.max_rows]u32 = undefined; + var f = e.forward(); + f.taps = e.scratch.taps; + while (out.items.len < count and !e.w.isEos(out.items[out.items.len - 1])) { + const last = out.items[out.items.len - 1]; + tokens[0] = last; + parents[0] = -1; + var rows: usize = 1; + const copied = try copies.propose(context.items, copy_rows - 1); + if (copied.len > 0) { + for (copied, 1..) |t, r| { + tokens[r] = t; + parents[r] = @as(i32, @intCast(r)) - 1; + } + rows += copied.len; + } else if (ctx.len > 0) { + const p = try d.propose(ctx, last, context.items.len, tree_rows - 1, null); + for (p.tokens, p.parents, 1..) |t, pr, r| { + tokens[r] = t; + parents[r] = if (pr < 0) 0 else pr + 1; + } + rows += p.tokens.len; + } + const part = [_]Part{.{ .seq = seq, .tokens = tokens[0..rows], .parents = parents[0..rows] }}; + try f.round(&part); + try f.picks(rows, &sampled); + // the path: from the root, each next token the child whose token the target drew + var n: usize = 1; + path[0] = 0; + var terminal = sampled[0]; + while (out.items.len + n < count and !e.w.isEos(terminal)) { + const child = for (1..rows) |r| { + if (parents[r] == @as(i32, @intCast(path[n - 1])) and tokens[r] == terminal) break r; + } else break; + path[n] = @intCast(child); + n += 1; + terminal = sampled[child]; + } + try f.commit(&part, &.{path[0..n]}); + // the drafter reads the kept rows' taps, gathered in path order + var items: [st.max_rows]kern.Copy = undefined; + const gathered = e.scratch.taps + st.max_rows * taps_width * bf; + for (path[0..n], 0..) |row, j| items[j] = .{ .dst = gathered + j * taps_width * bf, .src = e.scratch.taps + row * taps_width * bf, .bytes = taps_width * bf }; + try f.ops.upload(e.scratch.copy_items, std.mem.sliceAsBytes(items[0..n])); + try f.ops.copies(e.scratch.copy_items, n); + try d.absorb(ctx, gathered, n); + for (path[1..n]) |row| { + try out.append(gpa, tokens[row]); + try context.append(gpa, tokens[row]); + } + try out.append(gpa, terminal); + try context.append(gpa, terminal); + if (copied.len > 0) copy_rows = nextCopyRows(copy_rows, n == rows, tree_rows, max_rows); + stats.rounds += 1; + stats.drafted += rows - 1; + stats.accepted += n - 1; + } +} + +test "copy windows grow after whole copies and shrink after broken ones" { + try std.testing.expectEqual(@as(usize, 12), nextCopyRows(12, false, 12, 12)); + try std.testing.expectEqual(@as(usize, 12), nextCopyRows(12, true, 12, 12)); + try std.testing.expectEqual(@as(usize, 16), nextCopyRows(16, false, 12, 64)); + try std.testing.expectEqual(@as(usize, 32), nextCopyRows(16, true, 12, 64)); +} + +test "copies propose the latest earlier continuation of the last 8 tokens" { + const gpa = std.testing.allocator; + var x: CopyIndex = .{ .gpa = gpa }; + defer x.deinit(); + const ctx = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 1, 2, 3, 4, 5, 6, 7, 8 }; + try std.testing.expectEqualSlices(u32, &.{ 9, 10, 11, 12, 13, 14, 15, 16 }, try x.propose(&ctx, 8)); + try std.testing.expectEqual(@as(usize, 0), (try x.propose(ctx[0..15], 8)).len); +} diff --git a/zig/src/families/qwen27/cuda/native.zig b/zig/src/families/qwen27/cuda/native.zig new file mode 100644 index 0000000000..6e3f362fdf --- /dev/null +++ b/zig/src/families/qwen27/cuda/native.zig @@ -0,0 +1,111 @@ +//! Qwen3.5-family dense models on CUDA behind the native family interface (native/cuda.zig's registry). + +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const c = @import("shape.zig"); +const st = @import("state.zig"); +const engine = @import("engine.zig"); +const Lanes = @import("lanes.zig").Cuda; +const dr = @import("draft.zig"); + +pub const model_type = "qwen3_5"; +pub const formats: []const []const u8 = &.{"mlx-q4g64"}; +pub const default_context: i64 = 32768; +pub const max_segments: u32 = 1; +pub const prompt_rows: u32 = engine.prompt_rows; + +pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, drafter: ?[]const u8 = null }; + +/// A lone drafted stream's own driver (none here: one stream decodes in the lane core too, as under --parallel). +pub const LoneRun = *const fn (ctx: *anyopaque, s: *lanes.Stream, hooks: *anyopaque, committed: *const fn (*anyopaque) void, yield: *const fn (*anyopaque) bool) anyerror!bool; + +/// What the native server drives: the lane backend, the facts its round loop reads, and how to free it. +pub const Loaded = struct { + backend: lanes.backend.Backend, + facts: lanes.Model, + rows: u32, + /// Device bytes each admitted stream allocates for its own state and caches. + stream_bytes: usize, + /// Streams that allocate nothing (none here: every stream's state is its own). + free_streams: u32 = 0, + /// What a --slide trainer keeps out of the streams' room (none: the 27B does not learn on CUDA yet). + learn_bytes: usize = 0, + ctx: *anyopaque, + deinit: *const fn (*anyopaque) void, + lone: ?LoneRun = null, +}; + +const Owned = struct { gpa: std.mem.Allocator, e: *engine.Engine, lanes: Lanes, draft: ?*dr.DFlash2 = null }; + +/// The drafter the Python engine pairs with the 27B once pulled (z-lab/Qwen3.8-27B-DFlash2). +const drafter_repo = "models--z-lab--Qwen3.8-27B-DFlash2"; + +fn getenv(name: [:0]const u8) ?[]const u8 { + return std.mem.span(std.c.getenv(name) orelse return null); +} + +/// --drafter, else the pulled drafter's snapshot in the Hugging Face cache; null when neither holds one. +fn drafterDir(a: std.mem.Allocator, io: std.Io, given: ?[]const u8) !?[]const u8 { + if (given) |d| return try a.dupe(u8, d); + const hub = if (getenv("HF_HUB_CACHE")) |h| try a.dupe(u8, h) else if (getenv("HF_HOME")) |h| try std.fs.path.join(a, &.{ h, "hub" }) else blk: { + const home = getenv("HOME") orelse return null; + break :blk try std.fs.path.join(a, &.{ home, ".cache", "huggingface", "hub" }); + }; + defer a.free(hub); + const snaps = try std.fs.path.join(a, &.{ hub, drafter_repo, "snapshots" }); + defer a.free(snaps); + var dir = std.Io.Dir.cwd().openDir(io, snaps, .{ .iterate = true }) catch return null; + defer dir.close(io); + var it = dir.iterate(); + while (try it.next(io)) |entry| if (entry.kind == .directory) return try std.fs.path.join(a, &.{ snaps, entry.name }); + return null; +} + +/// The streams the lane core may admit at most; the server's memory admission picks how many fit. +const most_streams = 32; + +pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { + // the 27B's glue runs the Python engine's Triton kernels, captured on this chip (no own glue kernels yet) + const e = try engine.Engine.init(gpa, io, ctx, dir, kernels orelse return error.QwenNeedsCapturedKernels, .{ .context = o.context }); + errdefer e.deinit(); + const own = try gpa.create(Owned); + errdefer gpa.destroy(own); + own.* = .{ .gpa = gpa, .e = e, .lanes = try Lanes.init(gpa, e, most_streams) }; + errdefer own.lanes.deinit(); + if (o.drafts) if (try drafterDir(gpa, io, o.drafter)) |draft_dir| { + defer gpa.free(draft_dir); + const f = e.forward(); + own.draft = try dr.DFlash2.init(gpa, io, f.ops, f.t, &e.w, draft_dir, dir); + own.lanes.drafter = own.draft; + std.log.info("DFlash2 drafts every stream: {s}", .{draft_dir}); + // the forward's ms by rows: a shared round's tree widths follow the curve + try own.lanes.calibrate(io, most_streams); + }; + return .{ + .backend = own.lanes.backend(), + .facts = own.lanes.facts(), + .rows = st.max_rows, + .stream_bytes = st.Seq.bytes(e.w.g, o.context) + if (own.draft != null) dr.Context.bytes() else 0, + .ctx = own, + .deinit = release, + }; +} + +/// A request this engine refuses, in words; null: none of its own. +pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { + return switch (err) { + error.PromptTooLong => "the prompt and its reply exceed this server's context window: shorten it or lower max_tokens", + error.OutOfDeviceMemory => "the GPU had no memory left for this request's caches: retry once another request ends", + error.QwenCheckpointHasNoDraftHead => "this checkpoint has no draft head on CUDA yet: serve with --no-drafts", + else => null, + }; +} + +fn release(p: *anyopaque) void { + const own: *Owned = @ptrCast(@alignCast(p)); + own.lanes.deinit(); + if (own.draft) |d| d.deinit(); + own.e.deinit(); + own.gpa.destroy(own); +} diff --git a/zig/src/families/qwen27/cuda/round.zig b/zig/src/families/qwen27/cuda/round.zig new file mode 100644 index 0000000000..2b2d4e2697 --- /dev/null +++ b/zig/src/families/qwen27/cuda/round.zig @@ -0,0 +1,230 @@ +//! A verify round's inputs laid out as tree_forward or multi_tree_forward lays them (Triton variants follow alignment). + +const std = @import("std"); +const c = @import("shape.zig"); +const kern = @import("kernels.zig"); +const tri = @import("triton.zig"); +const st = @import("state.zig"); +const tree = @import("tree.zig"); + +const bf = 2; + +/// One stream's window: its tokens from its committed position, and each row's parent (null: a chain). +pub const Part = struct { seq: *st.Seq, tokens: []const u32, parents: ?[]const i32 = null }; + +/// Where a round's inputs live on the device, and what the layer loop launches with. +pub const Round = struct { + rows: usize, + streams: usize, + multi: bool, + ids: u64, + pos: u64, + windows: u64, + sids: u64, // multi: each row's stream; else the windows again (gdn_pre passes WIN as SID) + plan: u64, // GDN schedule entries (rows, 3) + starts: u64, // stream row starts (streams + 1) + slots: usize, // the GDN schedule's live states (0: every window a chain) + most: usize, // the most rows a stream's window holds + tables: u64, // multi: (DeltaNet layers, streams) state pointers, a layer's row at its DeltaNet index + attn: tri.Tri.Plan, + offs: u64, // (attention layers, streams, 2) int64 cache offsets; single: indexed by layer + starts_host: [st.max_streams + 1]usize, + + /// The conv rows gdn_pre reads for layer `i` (its DeltaNet index `j`): the stream's own, or the stacked copy. + pub fn conv(r: *const Round, parts: []const Part, s: *const st.Scratch, g: c.Geometry, i: usize, j: usize) u64 { + if (!r.multi) return parts[0].seq.conv[i]; + return s.conv_cat + j * st.max_streams * (c.conv_taps - 1) * g.convDim() * bf; + } + + /// Layer `i`'s attention cache offsets: tree_forward's (one stream, by layer) or the packed (layer, streams) rows. + pub fn offsets(r: *const Round, i: usize, a: usize) u64 { + return if (r.multi) r.offs + a * r.streams * 16 else r.offs + i * 16; + } + + /// The DeltaNet state table of DeltaNet layer `j` (multi only). + pub fn table(r: *const Round, j: usize) u64 { + return r.tables + j * r.streams * 8; + } +}; + +/// A part's parents: its own tree's, or a chain's. +pub fn parentsOf(p: Part, buf: []i32) []const i32 { + if (p.parents) |x| return x; + for (buf[0..p.tokens.len], 0..) |*x, r| x.* = @as(i32, @intCast(r)) - 1; + return buf[0..p.tokens.len]; +} + +/// attention.plan_host: rows, (first, rows, keys, slots) per stream, items, then window parents (global rows). +fn attnPlan(gpa: std.mem.Allocator, out: *std.ArrayList(i32), parts: []const Part, group: usize) !usize { + for (parts, 0..) |p, s| for (p.tokens) |_| try out.append(gpa, @intCast(s)); + var start: usize = 0; + for (parts) |p| { + const w = p.tokens.len; + try out.appendSlice(gpa, &.{ @intCast(start), @intCast(w), @intCast(p.seq.pos), @intCast(tri.slots(p.seq.pos, w)) }); + start += w; + } + var n_items: usize = 0; + for (parts, 0..) |p, s| { + const w = p.tokens.len; + const folded = tri.groups(p.seq.pos, w); + const loose = p.seq.pos / tri.chunk - folded * tri.group_chunks; + for (0..folded + loose) |j| { + const code: i32 = if (j < folded) @intCast(j) else -1 - @as(i32, @intCast(j - folded)); + var first: usize = 0; + while (first < w * group) : (first += 16) { + try out.appendSlice(gpa, &.{ @intCast(s), @intCast(first), code }); + n_items += 1; + } + } + } + start = 0; + var buf: [tree.max_nodes]i32 = undefined; + for (parts) |p| { + for (parentsOf(p, &buf)) |x| try out.append(gpa, if (x < 0) -1 else @intCast(start + @as(usize, @intCast(x)))); + start += p.tokens.len; + } + return n_items; +} + +/// Each stream's key and value caches as bf16 element offsets from the scratch's origin. +fn offsetOf(s: *const st.Scratch, ptr: u64) i64 { + return @divExact(@as(i64, @bitCast(ptr -% s.origin)), bf); +} + +/// Every stream's host plans: positions (pos + depth), the GDN schedule (nodes offset by its start), conv windows. +const Host = struct { pos: std.ArrayList(i32) = .empty, entries: std.ArrayList(i32) = .empty, windows: std.ArrayList(i32) = .empty, slots: usize = 0, most: usize = 0 }; + +fn plans(gpa: std.mem.Allocator, parts: []const Part, starts: []const usize, multi: bool, h: *Host) !void { + const keep = c.conv_taps - 1; + var buf: [tree.max_nodes]i32 = undefined; + var dep: [tree.max_nodes]usize = undefined; + var win: [tree.max_nodes * c.conv_taps]i32 = undefined; + for (parts, 0..) |p, k| { + const parents = parentsOf(p, &buf); + const w = parents.len; + try tree.depths(parents, dep[0..w]); + for (dep[0..w]) |d| try h.pos.append(gpa, @intCast(p.seq.pos + d)); + const s = try tree.schedule(gpa, parents); + defer gpa.free(s.entries); + for (s.entries, 0..) |x, j| try h.entries.append(gpa, if (j % 3 == 0) x + @as(i32, @intCast(starts[k])) else x); + h.slots = @max(h.slots, s.slots); + h.most = @max(h.most, w); + // one stream's windows index [its state; its rows]; several streams' index [their states; all rows] + tree.convWindows(parents, keep, if (multi) starts[k] else 0, win[0 .. w * (keep + 1)]); + try h.windows.appendSlice(gpa, win[0 .. w * (keep + 1)]); + } +} + +/// Uploads the round's inputs and runs attention's _paths; the caller's layer loop reads the returned Round. +pub fn stage(gpa: std.mem.Allocator, ops: kern.Ops, t: tri.Tri, s: *st.Scratch, g: c.Geometry, parts: []const Part) !Round { + if (parts.len == 0 or parts.len > st.max_streams) return error.InvalidQwenWindows; + var W: usize = 0; + var r: Round = undefined; + r.starts_host[0] = 0; + for (parts, 0..) |p, k| { + if (p.tokens.len == 0 or p.tokens.len > tree.max_nodes) return error.InvalidQwenWindows; + if (p.parents) |x| if (x.len != p.tokens.len) return error.InvalidQwenWindows; + if (p.seq.pos + p.tokens.len > p.seq.capacity) return error.PromptTooLong; + W += p.tokens.len; + r.starts_host[k + 1] = W; + } + if (W > st.round_rows) return error.WindowTooWide; + r.rows = W; + r.streams = parts.len; + r.multi = parts.len > 1; + const S = parts.len; + const group = g.query_heads / g.kv_heads; + var h: Host = .{}; + defer { + h.pos.deinit(gpa); + h.entries.deinit(gpa); + h.windows.deinit(gpa); + } + try plans(gpa, parts, r.starts_host[0 .. S + 1], r.multi, &h); + r.slots = h.slots; + r.most = h.most; + var host: std.ArrayList(i32) = .empty; + defer host.deinit(gpa); + var offs: std.ArrayList(i64) = .empty; + defer offs.deinit(gpa); + if (!r.multi) { + // tree_forward: tokens, positions, plan (entries then starts), windows and attention's plan apart + const p = parts[0]; + for (p.tokens) |tok| try host.append(gpa, @intCast(tok)); + try ops.upload(s.ids, std.mem.sliceAsBytes(host.items)); + try ops.upload(s.pos, std.mem.sliceAsBytes(h.pos.items)); + try ops.upload(s.windows, std.mem.sliceAsBytes(h.windows.items)); + try ops.s.synchronize(); + host.clearRetainingCapacity(); + try host.appendSlice(gpa, h.entries.items); + try host.appendSlice(gpa, &.{ 0, @intCast(W) }); + try ops.upload(s.plan, std.mem.sliceAsBytes(host.items)); + try ops.s.synchronize(); + host.clearRetainingCapacity(); + const n_items = try attnPlan(gpa, &host, parts, group); + try ops.upload(s.attn_plan, std.mem.sliceAsBytes(host.items)); + try ops.s.synchronize(); + for (0..g.layers) |i| try offs.appendSlice(gpa, if (c.linear(i)) &.{ 0, 0 } else &.{ offsetOf(s, p.seq.keys[i]), offsetOf(s, p.seq.values[i]) }); + try ops.upload(s.offs, std.mem.sliceAsBytes(offs.items)); + try ops.s.synchronize(); + r.ids = s.ids; + r.pos = s.pos; + r.windows = s.windows; + r.sids = s.windows; + r.plan = s.plan; + r.starts = s.plan + 3 * W * 4; + r.tables = 0; + r.offs = s.offs; + r.attn = .{ .rows = s.attn_plan, .streams = s.attn_plan + W * 4, .items = s.attn_plan + (W + 4) * 4, .n_items = n_items, .paths = s.paths, .depths = s.depths, .width = W }; + try t.paths(s.attn_plan + (W + 4 + 3 * n_items) * 4, s.paths, s.depths, W); + return r; + } + // multi_tree_forward: positions, stream ids, plan entries, starts, ids, windows, attention's plan in one copy + try host.appendSlice(gpa, h.pos.items); + for (parts, 0..) |p, k| for (p.tokens) |_| try host.append(gpa, @intCast(k)); + try host.appendSlice(gpa, h.entries.items); + for (r.starts_host[0 .. S + 1]) |x| try host.append(gpa, @intCast(x)); + for (parts) |p| for (p.tokens) |tok| try host.append(gpa, @intCast(tok)); + try host.appendSlice(gpa, h.windows.items); + const at_attn = host.items.len; + const n_items = try attnPlan(gpa, &host, parts, group); + try ops.upload(s.round, std.mem.sliceAsBytes(host.items)); + try ops.s.synchronize(); + const base = s.round; + r.pos = base; + r.sids = base + W * 4; + r.plan = base + 2 * W * 4; + r.starts = base + 5 * W * 4; + r.ids = base + (5 * W + S + 1) * 4; + r.windows = base + (6 * W + S + 1) * 4; + const ab = base + at_attn * 4; + r.attn = .{ .rows = ab, .streams = ab + W * 4, .items = ab + (W + 4 * S) * 4, .n_items = n_items, .paths = s.paths, .depths = s.depths, .width = W }; + // the state pointer table and cache offsets, one copy each; every stream's conv rows stacked by layer + var ptrs: std.ArrayList(u64) = .empty; + defer ptrs.deinit(gpa); + var stack: std.ArrayList(kern.Copy) = .empty; + defer stack.deinit(gpa); + const keep = c.conv_taps - 1; + var j: usize = 0; + for (0..g.layers) |i| { + if (!c.linear(i)) { + for (parts) |p| try offs.appendSlice(gpa, &.{ offsetOf(s, p.seq.keys[i]), offsetOf(s, p.seq.values[i]) }); + continue; + } + const cat = s.conv_cat + j * st.max_streams * keep * g.convDim() * bf; + for (parts, 0..) |p, k| { + try ptrs.append(gpa, p.seq.rec[i]); + try stack.append(gpa, .{ .dst = cat + k * keep * g.convDim() * bf, .src = p.seq.conv[i], .bytes = keep * g.convDim() * bf }); + } + j += 1; + } + try ops.upload(s.tables, std.mem.sliceAsBytes(ptrs.items)); + try ops.upload(s.offs, std.mem.sliceAsBytes(offs.items)); + try ops.upload(s.copy_items, std.mem.sliceAsBytes(stack.items)); + try ops.copies(s.copy_items, stack.items.len); + try ops.s.synchronize(); + r.tables = s.tables; + r.offs = s.offs; + try t.paths(ab + (W + 4 * S + 3 * n_items) * 4, s.paths, s.depths, W); + return r; +} diff --git a/zig/src/families/qwen27/cuda/shape.zig b/zig/src/families/qwen27/cuda/shape.zig new file mode 100644 index 0000000000..b018dc22a1 --- /dev/null +++ b/zig/src/families/qwen27/cuda/shape.zig @@ -0,0 +1,102 @@ +//! The shapes the CUDA engine is built for: the family's parsed config (config.zig), held to the 27B's. +const std = @import("std"); +const config = @import("../config.zig"); + +pub const vocab = 248320; +pub const linear_dim = 128; // a DeltaNet key or value head's width +pub const conv_taps = 4; +pub const head_dim = 256; +pub const rotary_dim = 64; +pub const eps: f32 = 1e-6; +pub const theta: f32 = 10000000; + +/// Whether layer `index` is a DeltaNet layer: every fourth is attention. +pub fn linear(index: usize) bool { + return index % 4 != 3; +} + +/// The widths a forward sizes its buffers by. +pub const Geometry = struct { + hidden: usize, + intermediate: usize, + layers: usize, + linear_k_heads: usize, // DeltaNet key (and query) heads + linear_v_heads: usize, // DeltaNet value heads, each key head serving a run of them + query_heads: usize, + kv_heads: usize, + + /// The DeltaNet input projection's row: queries, keys, then values. + pub fn convDim(g: Geometry) usize { + return (2 * g.linear_k_heads + g.linear_v_heads) * linear_dim; + } + pub fn kInner(g: Geometry) usize { + return g.linear_k_heads * linear_dim; + } + pub fn vInner(g: Geometry) usize { + return g.linear_v_heads * linear_dim; + } + pub fn qInner(g: Geometry) usize { + return g.query_heads * head_dim; + } + pub fn kvInner(g: Geometry) usize { + return g.kv_heads * head_dim; + } + /// The widest row an activation buffer holds: the recurrence's values or the attention's heads. + pub fn inner(g: Geometry) usize { + return @max(g.vInner(), g.qInner()); + } + /// One layer's recurrent state (fp32) and its conv window (bf16). + pub fn deltaBytes(g: Geometry) usize { + return g.linear_v_heads * linear_dim * linear_dim * 4; + } + pub fn convBytes(g: Geometry) usize { + return (conv_taps - 1) * g.convDim() * 2; + } +}; + +/// Qwen3.8-27B, the one checkpoint shape the CUDA engine serves. +pub const the_27b: Geometry = .{ .hidden = 5120, .intermediate = 17408, .layers = 64, .linear_k_heads = 16, .linear_v_heads = 48, .query_heads = 24, .kv_heads = 4 }; + +/// A checkpoint's config.json (and generation_config.json's end tokens), refused unless it is the 27B's. +pub const Config = struct { + g: Geometry, + eos: [config.max_eos]u32, + eos_count: usize, + + pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config { + const text = try file(gpa, io, dir, "config.json") orelse return error.MissingConfig; + defer gpa.free(text); + const generation = try file(gpa, io, dir, "generation_config.json"); + defer if (generation) |x| gpa.free(x); + return check(try config.parse(gpa, text, generation)); + } + + fn file(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, name: []const u8) !?[]u8 { + const path = try std.fs.path.join(gpa, &.{ dir, name }); + defer gpa.free(path); + return std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)) catch |err| switch (err) { + error.FileNotFound => null, + else => err, + }; + } +}; + +/// The parsed config as the CUDA engine's Config, when every shape the kernels assume is the 27B's. +pub fn check(c: config.Config) !Config { + const g: Geometry = .{ .hidden = c.hidden, .intermediate = c.intermediate, .layers = c.layers, .linear_k_heads = c.k_heads, .linear_v_heads = c.v_heads, .query_heads = c.heads, .kv_heads = c.kv_heads }; + if (!std.meta.eql(g, the_27b) or c.vocab != vocab or c.head_dim != head_dim or c.dk != linear_dim or c.dv != linear_dim) return error.UnsupportedQwenGeometry; + if (c.conv_kernel != conv_taps or c.rope_dims != rotary_dim or c.eps != eps or c.rope_theta != theta) return error.UnsupportedQwenGeometry; + for (c.kinds[0..c.layers], 0..) |kind, i| if ((kind == .linear) != linear(i)) return error.UnsupportedQwenGeometry; + return .{ .g = g, .eos = c.eos, .eos_count = c.eos_count }; +} + +test "the 27B's shapes pass and another hidden size is refused" { + var c: config.Config = .{ .hidden = 5120, .intermediate = 17408, .layers = 64, .vocab = vocab, .heads = 24, .kv_heads = 4, .head_dim = head_dim, .k_heads = 16, .v_heads = 48, .dk = linear_dim, .dv = linear_dim, .conv_kernel = conv_taps, .eps = eps, .rope_dims = rotary_dim, .rope_theta = theta }; + for (c.kinds[0..64], 0..) |*k, i| k.* = if (linear(i)) .linear else .attention; + c.eos[0] = 248044; + c.eos_count = 1; + const ok = try check(c); + try std.testing.expectEqual(@as(usize, 1), ok.eos_count); + c.hidden = 2048; + try std.testing.expectError(error.UnsupportedQwenGeometry, check(c)); +} diff --git a/zig/src/families/qwen27/cuda/state.zig b/zig/src/families/qwen27/cuda/state.zig new file mode 100644 index 0000000000..4cbe06c07e --- /dev/null +++ b/zig/src/families/qwen27/cuda/state.zig @@ -0,0 +1,304 @@ +//! A stream's committed state (DeltaNet recurrences, conv windows, attention caches) and the forward's scratch. + +const std = @import("std"); +const cuda = @import("cuda"); +const c = @import("shape.zig"); +const kern = @import("kernels.zig"); +const tri = @import("triton.zig"); +const torch_ops = kern.torch_ops; + +/// The most rows a stream's verify window takes (the multi-stream GDN tree kernel's limit). +pub const max_rows = 16; +/// The most streams a shared round takes. +pub const max_streams = 16; +/// The most rows a verify round takes: every stream's whole window. +pub const round_rows = max_rows * max_streams; +/// The most items a batched copy takes: every stream's layers, three rows or a key and a value each. +pub const copy_items = max_streams * 64 * 3 + round_rows * 64 * 2; +/// The most candidates a sampled row reads from the GPU: top_k up to 1,024, and exact_sampling.MARGIN past it. +pub const max_candidates = 1024 + 8; + +/// A bump allocator over one device buffer, every slice 256-byte aligned. +pub const Arena = struct { + buf: ?cuda.DeviceBuffer, // null: a measuring pass, every take counted and none backed + used: usize = 0, + + pub fn init(d: *const cuda.Driver, len: usize) !Arena { + return .{ .buf = try cuda.DeviceBuffer.alloc(d, len) }; + } + + pub fn deinit(a: *Arena) void { + if (a.buf) |*b| b.free(); + } + + pub fn take(a: *Arena, len: usize) !u64 { + const at = std.mem.alignForward(usize, a.used, 256); + a.used = at + len; + const b = a.buf orelse return 0; + if (a.used > b.len) return error.ArenaFull; + return b.ptr + at; + } +}; + +/// One stream's committed state: DeltaNet recurrences and conv windows, attention keys and values for `capacity`. +pub const Seq = struct { + arena: Arena, + rec: []u64, // by layer: (hv, dv, dk) fp32, 0 for attention layers + conv: []u64, // by layer: (3, conv dim) bf16 + keys: []u64, // by layer: (capacity, kv heads, head dim) bf16 + values: []u64, + head_in: u64, // the last prompt row normed, (hidden) bf16, and its group sums: the first draw's input + head_xs: u64, + capacity: usize, + pos: usize = 0, + gpa: std.mem.Allocator, + + /// Device bytes a stream of `capacity` positions takes. + pub fn bytes(g: c.Geometry, capacity: usize) usize { + var n: usize = std.mem.alignForward(usize, g.hidden * 2, 256) + std.mem.alignForward(usize, g.hidden / 64 * 4, 256); + const a = std.mem.alignForward; + for (0..g.layers) |i| n += if (c.linear(i)) a(usize, g.deltaBytes(), 256) + a(usize, g.convBytes(), 256) else 2 * a(usize, capacity * g.kvInner() * 2, 256); + return n; + } + + /// A fresh stream: zero recurrences and conv windows, caches for `capacity` positions. + pub fn init(gpa: std.mem.Allocator, ops: kern.Ops, g: c.Geometry, capacity: usize) !Seq { + var s: Seq = .{ .gpa = gpa, .arena = try Arena.init(ops.k.d, bytes(g, capacity)), .rec = &.{}, .conv = &.{}, .keys = &.{}, .values = &.{}, .head_in = 0, .head_xs = 0, .capacity = capacity }; + errdefer s.arena.deinit(); + s.rec = try gpa.alloc(u64, g.layers); + errdefer gpa.free(s.rec); + s.conv = try gpa.alloc(u64, g.layers); + errdefer gpa.free(s.conv); + s.keys = try gpa.alloc(u64, g.layers); + errdefer gpa.free(s.keys); + s.values = try gpa.alloc(u64, g.layers); + errdefer gpa.free(s.values); + const bf = 2; + s.head_in = try s.arena.take(g.hidden * 2); + s.head_xs = try s.arena.take(g.hidden / 64 * 4); + for (0..g.layers) |i| { + s.rec[i] = 0; + s.conv[i] = 0; + s.keys[i] = 0; + s.values[i] = 0; + const A = &s.arena; + if (c.linear(i)) { + s.rec[i] = try A.take(g.deltaBytes()); + s.conv[i] = try A.take(g.convBytes()); + } else { + s.keys[i] = try A.take(capacity * g.kvInner() * bf); + s.values[i] = try A.take(capacity * g.kvInner() * bf); + } + } + try s.reset(ops, g); + return s; + } + + pub fn deinit(s: *Seq) void { + s.arena.deinit(); + s.gpa.free(s.rec); + s.gpa.free(s.conv); + s.gpa.free(s.keys); + s.gpa.free(s.values); + s.* = undefined; + } + + /// Back to an empty prompt: zero recurrences and conv windows (State.__init__'s zeros). + pub fn reset(s: *Seq, ops: kern.Ops, g: c.Geometry) !void { + for (0..g.layers) |i| if (c.linear(i)) { + try ops.fill32(s.rec[i], 0, g.deltaBytes() / 4); + try ops.fill32(s.conv[i], 0, g.convBytes() / 4); + }; + s.pos = 0; + } +}; + +/// One DeltaNet layer's window record, kept until commit: what the replay steps and the conv window takes. +pub const GdnRecord = struct { q: u64, k: u64, v: u64, g: u64, beta: u64, qkv: u64 }; +/// One attention layer's window record: the rotated keys and the values the window's rows would add. +pub const AttnRecord = struct { k: u64, v: u64 }; + +/// The forward's device buffers, sized for `rows` rows a call (a decode window, or a prompt chunk). +pub const Scratch = struct { + arena: Arena, + rows: usize, + // the residual stream and the normed rows with their group sums + x: u64, + h: u64, + y: u64, + xs: u64, + r: u64, + pending: u64, + // DeltaNet + qkv: u64, + z: u64, + b: u64, + a: u64, + yr: u64, + gq: u64, // a prompt chunk's DeltaNet inputs (a window's live in its records) + gk: u64, + gv: u64, + gg: u64, + gbeta: u64, + gated: u64, + gated_xs: u64, + // attention + qg: u64, + key: u64, + value: u64, + q_rot: u64, + attn: u64, + // MLP + gate: u64, + up: u64, + act: u64, + act_xs: u64, + // the head's input, logits and picks + last_h: u64, + last_xs: u64, + logits: u64, + picks: u64, + logits32: u64, // the round's logits as fp32, the top-k input + cand_values: u64, // (rows, max_candidates) fp32 and int64: each row's top candidates + cand_ids: u64, + topk_scratch: u64, + // inputs a call uploads: ids, positions, conv windows, the GDN plan, the attention plan + ids: u64, + pos: u64, + sids: u64, // a batched prompt's rows' streams + prompt_keys: u64, // a batched prompt's rotated keys and values, before each stream's cache takes its rows + prompt_values: u64, + windows: u64, + plan: u64, + attn_plan: u64, + paths: u64, + depths: u64, + offs: u64, + part_o: u64, + part_m: u64, + part_l: u64, + part_chunks: usize, + origin: u64, // the bf16 origin cache offsets count from + conv_tmp: u64, + conv_old: u64, // a round's streams' conv rows that survive its commit, by stream and DeltaNet layer + copy_items: u64, // two batched-copy tables (kern.Copy), one for each phase of a commit + taps: u64, // a call's rows of the drafter's taps: (rows, 5 x hidden) bf16 + replay_table: u64, + replay_rows: u64, + round: u64, // a shared round's packed int32 inputs (multi_tree_forward's one host copy) + tables: u64, // (DeltaNet layers, streams) int64: each stream's state of each layer + conv_cat: u64, // by DeltaNet layer: every stream's conv rows, stacked + records: []GdnRecord, // by layer: the round's DeltaNet inputs, kept until commit + attn_records: []AttnRecord, // by layer: the round's rotated keys and values + gpa: std.mem.Allocator, + + /// Scratch for prompt chunks of `prompt_rows` and windows of `max_rows`, over caches of `capacity` positions. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, g: c.Geometry, prompt_rows: usize, capacity: usize) !Scratch { + var s: Scratch = undefined; + s.gpa = gpa; + s.records = try gpa.alloc(GdnRecord, g.layers); + errdefer gpa.free(s.records); + s.attn_records = try gpa.alloc(AttnRecord, g.layers); + errdefer gpa.free(s.attn_records); + s.arena = .{ .buf = null }; + try s.layout(g, prompt_rows, capacity); + s.arena = try Arena.init(d, s.arena.used); + errdefer s.arena.deinit(); + try s.layout(g, prompt_rows, capacity); + return s; + } + + fn layout(s: *Scratch, g: c.Geometry, prompt_rows: usize, capacity: usize) !void { + const R = @max(prompt_rows, round_rows); + const W = round_rows; + const bf = 2; + const chunks = (capacity + W + tri.chunk - 1) / tri.chunk; + // attention.plan_host: a query tile's items per committed chunk and folded group + const codes = capacity / tri.chunk + capacity / (tri.chunk * tri.group_chunks); + const items = codes * ((W * (g.query_heads / g.kv_heads) + 15) / 16); + s.rows = R; + s.part_chunks = chunks; + s.arena.used = 0; + const A = &s.arena; + s.origin = try A.take(128); + s.x = try A.take(R * g.hidden * bf); + s.h = try A.take(R * g.hidden * bf); + s.y = try A.take(R * g.hidden * bf); + s.r = try A.take(R * g.hidden * bf); + s.pending = try A.take(R * g.hidden * bf); + s.xs = try A.take(R * g.hidden / 64 * 4); + s.qkv = try A.take(R * g.convDim() * bf); + s.z = try A.take(R * g.vInner() * bf); + s.b = try A.take(R * g.linear_v_heads * bf); + s.a = try A.take(R * g.linear_v_heads * bf); + s.yr = try A.take(R * g.vInner() * bf); + s.gq = try A.take(R * g.kInner() * bf); + s.gk = try A.take(R * g.kInner() * bf); + s.gv = try A.take(R * g.vInner() * bf); + s.gg = try A.take(R * g.linear_v_heads * 4); + s.gbeta = try A.take(R * g.linear_v_heads * 4); + s.gated = try A.take(R * g.inner() * bf); + s.gated_xs = try A.take(R * g.inner() / 64 * 4); + s.qg = try A.take(R * 2 * g.qInner() * bf); + s.key = try A.take(R * g.kvInner() * bf); + s.value = try A.take(R * g.kvInner() * bf); + s.q_rot = try A.take(R * g.qInner() * bf); + s.attn = try A.take(R * g.qInner() * bf); + s.gate = try A.take(R * g.intermediate * bf); + s.up = try A.take(R * g.intermediate * bf); + s.act = try A.take(R * g.intermediate * bf); + s.act_xs = try A.take(R * g.intermediate / 64 * 4); + s.last_h = try A.take(W * g.hidden * bf); + s.last_xs = try A.take(W * g.hidden / 64 * 4); + s.logits = try A.take(W * c.vocab * bf); + s.picks = try A.take(W * 4); + s.logits32 = try A.take(W * c.vocab * 4); + s.cand_values = try A.take(W * max_candidates * 4); + s.cand_ids = try A.take(W * max_candidates * 8); + s.topk_scratch = try A.take(torch_ops.topkScratchBytes(W, c.vocab)); + s.ids = try A.take(R * 4); + s.pos = try A.take(R * 4); + s.sids = try A.take(R * 4); + s.prompt_keys = try A.take(R * g.kvInner() * bf); + s.prompt_values = try A.take(R * g.kvInner() * bf); + s.windows = try A.take(R * c.conv_taps * 4); + s.plan = try A.take(R * 3 * 4); + s.attn_plan = try A.take((W + 4 + 3 * items + W) * 4); + s.paths = try A.take(W * tri.max_nodes * 4); + s.depths = try A.take(W * 4); + s.offs = try A.take(g.layers * max_streams * 2 * 8); + s.part_o = try A.take(chunks * W * g.query_heads * c.head_dim * 4); + s.part_m = try A.take(chunks * W * g.query_heads * 4); + s.part_l = try A.take(chunks * W * g.query_heads * 4); + s.conv_tmp = try A.take((c.conv_taps - 1 + R) * g.convDim() * bf); + s.conv_old = try A.take(max_streams * g.layers * (c.conv_taps - 1) * g.convDim() * bf); + s.copy_items = try A.take(2 * copy_items * @sizeOf(kern.Copy)); + s.taps = try A.take(R * 5 * g.hidden * bf); + s.replay_table = try A.take(g.layers * (4 + max_streams) * 8); + s.replay_rows = try A.take(max_streams * (W + 1) * 4); + s.round = try A.take((6 * W + max_streams + 1 + W * c.conv_taps + W + 4 * max_streams + 3 * items * max_streams + W) * 4); + s.tables = try A.take(g.layers * max_streams * 8); + s.conv_cat = try A.take(g.layers * max_streams * (c.conv_taps - 1) * g.convDim() * bf); + for (0..g.layers) |i| { + if (c.linear(i)) { + s.records[i] = .{ + .q = try A.take(W * g.kInner() * bf), + .k = try A.take(W * g.kInner() * bf), + .v = try A.take(W * g.vInner() * bf), + .g = try A.take(W * g.linear_v_heads * 4), + .beta = try A.take(W * g.linear_v_heads * 4), + .qkv = try A.take(W * g.convDim() * bf), + }; + } else { + s.attn_records[i] = .{ .k = try A.take(W * g.kvInner() * bf), .v = try A.take(W * g.kvInner() * bf) }; + } + } + } + + pub fn deinit(s: *Scratch) void { + s.arena.deinit(); + s.gpa.free(s.records); + s.gpa.free(s.attn_records); + s.* = undefined; + } +}; diff --git a/zig/src/families/qwen27/cuda/tree.zig b/zig/src/families/qwen27/cuda/tree.zig new file mode 100644 index 0000000000..f8cdf7187d --- /dev/null +++ b/zig/src/families/qwen27/cuda/tree.zig @@ -0,0 +1,181 @@ +//! A verify tree's host plans: gdn.schedule's slots and visiting order, and each node's conv window and depth. + +const std = @import("std"); + +/// The most nodes a stream's tree takes (forward._paths), and the most live states a schedule may hold. +pub const max_nodes = 128; +pub const max_slots = 32; + +/// gdn.schedule's result: (node, source, dest) entries in visiting order and the slots they use. +pub const Schedule = struct { entries: []i32, slots: usize }; + +/// forward._paths: each row's depth from the root (parents topologically sorted, -1 at row 0 only). +pub fn depths(parents: []const i32, out: []usize) !void { + if (parents.len == 0 or parents.len > max_nodes or parents[0] != -1) return error.InvalidQwenTree; + for (parents, 0..) |p, row| { + if (row == 0) { + out[0] = 0; + continue; + } + if (p < 0 or p >= row) return error.InvalidQwenTree; + out[row] = out[@intCast(p)] + 1; + } +} + +/// Whether every row's parent is the row before it: a chain. +pub fn chain(parents: []const i32) bool { + for (parents, 0..) |p, row| if (p != @as(i32, @intCast(row)) - 1) return false; + return true; +} + +/// gdn._order_slots: entries for one visiting order, and the slots it needs. +fn orderSlots(gpa: std.mem.Allocator, parents: []const i32, order: []const usize) !Schedule { + const n = parents.len; + const pos = try gpa.alloc(usize, n); + defer gpa.free(pos); + for (order, 0..) |node, i| pos[node] = i; + // each node's last child in this order, and whether all its children follow it directly + const last = try gpa.alloc(?usize, n); + defer gpa.free(last); + @memset(last, null); + const direct = try gpa.alloc(bool, n); + defer gpa.free(direct); + @memset(direct, true); + for (parents, 0..) |p, node| { + if (p < 0) continue; + const pu: usize = @intCast(p); + if (last[pu] == null or pos[node] > pos[last[pu].?]) last[pu] = node; + if (pos[node] != pos[pu] + 1) direct[pu] = false; + } + const slot_of = try gpa.alloc(?i32, n); + defer gpa.free(slot_of); + @memset(slot_of, null); + var free: std.ArrayList(i32) = .empty; + defer free.deinit(gpa); + var entries = try gpa.alloc(i32, 3 * n); + errdefer gpa.free(entries); + var used: i32 = 0; + for (order, 0..) |node, i| { + const parent = parents[node]; + var source: i32 = -1; + if (parent >= 0) { + const pu: usize = @intCast(parent); + source = if (i > 0 and order[i - 1] == pu) -2 else slot_of[pu] orelse return error.InvalidQwenTree; + // its last child reads it now: the slot may be reused + if (slot_of[pu] != null and pos[last[pu].?] == i) { + try free.append(gpa, slot_of[pu].?); + slot_of[pu] = null; + } + } + var dest: i32 = -1; + if (last[node] != null and !direct[node]) { + if (free.items.len > 0) { + std.mem.sort(i32, free.items, {}, std.sort.asc(i32)); + dest = free.orderedRemove(0); + } else { + dest = used; + used += 1; + } + slot_of[node] = dest; + } + entries[3 * i ..][0..3].* = .{ @intCast(node), source, dest }; + } + return .{ .entries = entries, .slots = @intCast(used) }; +} + +/// gdn.schedule: depth-first or level order, whichever needs fewer slots (depth-first on a tie). +pub fn schedule(gpa: std.mem.Allocator, parents: []const i32) !Schedule { + const n = parents.len; + const d = try gpa.alloc(usize, n); + defer gpa.free(d); + try depths(parents, d); + // depth-first: children in row order, as the Python stack pushes them reversed + const dfs = try gpa.alloc(usize, n); + defer gpa.free(dfs); + var stack: std.ArrayList(usize) = .empty; + defer stack.deinit(gpa); + try stack.append(gpa, 0); + var at: usize = 0; + while (stack.pop()) |node| { + dfs[at] = node; + at += 1; + var child = n; + while (child > node + 1) { + child -= 1; + if (parents[child] == @as(i32, @intCast(node))) try stack.append(gpa, child); + } + } + const level = try gpa.alloc(usize, n); + defer gpa.free(level); + for (level, 0..) |*l, i| l.* = i; + std.mem.sort(usize, level, d, struct { + fn less(ds: []const usize, a: usize, b: usize) bool { + return ds[a] < ds[b] or (ds[a] == ds[b] and a < b); + } + }.less); + const first = try orderSlots(gpa, parents, dfs); + const second = orderSlots(gpa, parents, level) catch |err| { + gpa.free(first.entries); + return err; + }; + const best, const other = if (second.slots < first.slots) .{ second, first } else .{ first, second }; + gpa.free(other.entries); + if (best.slots > max_slots) { + gpa.free(best.entries); + return error.QwenTreeTooWide; + } + return best; +} + +/// forward._conv_windows: each node's last `keep` inputs along its path, then its own row (`keep + base + row`). +pub fn convWindows(parents: []const i32, keep: usize, base: usize, out: []i32) void { + const w = keep + 1; + for (parents, 0..) |p, row| { + const dst = out[row * w ..][0..w]; + if (p < 0) { + for (0..keep) |j| dst[j] = @intCast(j); + } else { + const src = out[@as(usize, @intCast(p)) * w ..][0..w]; + @memcpy(dst[0..keep], src[1..w]); + } + dst[keep] = @intCast(keep + base + row); + } +} + +test "a chain's schedule keeps no slot and reads each predecessor" { + const gpa = std.testing.allocator; + const s = try schedule(gpa, &.{ -1, 0, 1, 2 }); + defer gpa.free(s.entries); + try std.testing.expectEqual(@as(usize, 0), s.slots); + try std.testing.expectEqualSlices(i32, &.{ 0, -1, -1, 1, -2, -1, 2, -2, -1, 3, -2, -1 }, s.entries); +} + +test "a fork saves the shared parent in a slot until its last child" { + const gpa = std.testing.allocator; + // root 0 with children 1 and 2, 1 with child 3: depth-first 0 1 3 2 needs the root kept for 2 + const s = try schedule(gpa, &.{ -1, 0, 0, 1 }); + defer gpa.free(s.entries); + try std.testing.expectEqual(@as(usize, 1), s.slots); + try std.testing.expectEqualSlices(i32, &.{ 0, -1, 0, 1, -2, -1, 3, -2, -1, 2, 0, -1 }, s.entries); +} + +test "schedules match gdn.schedule on random trees" { + const gpa = std.testing.allocator; + const cases = .{ + .{ &[_]i32{ -1, 0, 1, 2, 0, 3 }, &[_]i32{ 0, -1, 0, 1, -2, -1, 2, -2, -1, 3, -2, -1, 5, -2, -1, 4, 0, -1 }, 1 }, + .{ &[_]i32{ -1, 0, 0, 0, 0, 2, 3, 6, 3 }, &[_]i32{ 0, -1, 0, 1, -2, -1, 2, 0, -1, 5, -2, -1, 3, 0, 1, 6, -2, -1, 7, -2, -1, 8, 1, -1, 4, 0, -1 }, 2 }, + .{ &[_]i32{ -1, 0, 0, 2, 1, 0, 5, 1, 6, 4, 2, 6 }, &[_]i32{ 0, -1, 0, 1, -2, 1, 4, -2, -1, 9, -2, -1, 7, 1, -1, 2, 0, 1, 3, -2, -1, 10, 1, -1, 5, 0, -1, 6, -2, 0, 8, -2, -1, 11, 0, -1 }, 2 }, + }; + inline for (cases) |case| { + const s = try schedule(gpa, case[0]); + defer gpa.free(s.entries); + try std.testing.expectEqual(@as(usize, case[2]), s.slots); + try std.testing.expectEqualSlices(i32, case[1], s.entries); + } +} + +test "conv windows follow each node's path" { + var out: [4 * 4]i32 = undefined; + convWindows(&.{ -1, 0, 0, 1 }, 3, 0, &out); + try std.testing.expectEqualSlices(i32, &.{ 0, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 5, 2, 3, 4, 6 }, &out); +} diff --git a/zig/src/families/qwen27/cuda/triton.zig b/zig/src/families/qwen27/cuda/triton.zig new file mode 100644 index 0000000000..5206ff382d --- /dev/null +++ b/zig/src/families/qwen27/cuda/triton.zig @@ -0,0 +1,141 @@ +//! The 27B's Triton kernels from the captured cubins: each launch has the Python wrapper's grid and constexprs. + +const std = @import("std"); +const cuda = @import("cuda"); +const aot = cuda.aot; + +const p = aot.ptr; + +fn int(name: []const u8, v: usize) aot.Arg { + return aot.int(name, @intCast(v)); +} + +fn ci(name: []const u8, v: usize) aot.Const { + return aot.ci(name, @intCast(v)); +} + +fn u(x: usize) u32 { + return @intCast(x); +} + +fn cdiv(a: usize, b: usize) u32 { + return u((a + b - 1) / b); +} + +fn pow2(n: usize) usize { + return std.math.ceilPowerOfTwo(usize, n) catch unreachable; +} + +/// attention.py's layout constants: 512-key chunks, folded four to a group, up to 128 window rows. +pub const chunk = 512; +pub const group_chunks = 4; +pub const max_nodes = 128; +const merge_columns = 64; + +/// The DeltaNet shapes glue.gdn_pre takes: projection width, key and value heads, head dim, kept conv rows. +pub const Gdn = struct { c: usize, kh: usize, vh: usize, dk: usize, keep: usize }; + +/// The attention shapes: query and key heads, head dim, rotary half. +pub const Attn = struct { heads: usize, kv_heads: usize, dim: usize, half: usize }; + +pub const Tri = struct { + set: *const aot.Set, + s: cuda.Stream, + + fn run(t: Tri, name: []const u8, grid: [3]u32, args: []const aot.Arg, consts: []const aot.Const) !void { + try t.set.run(t.s, name, grid, args, consts); + } + + /// glue.embed: a 4-bit table row dequantized, one program a row and 64-group. + pub fn embed(t: Tri, ids: u64, w: u64, s: u64, b: u64, out: u64, rows: usize, d: usize) !void { + try t.run("_embed", .{ u(rows), u(d / 64), 1 }, &.{ p("IDS", "*i32", ids), p("Wt", "*i32", w), p("S", "*bf16", s), p("B", "*bf16", b), p("OUT", "*bf16", out) }, &.{ci("D", d)}); + } + + /// glue.add_rmsnorm: h = x + r (or x itself without r), y = rmsnorm(h) * w, xs = y's 64-group sums. + pub fn addRmsnorm(t: Tri, x: u64, r: ?u64, w: u64, h: u64, y: u64, xs: u64, rows: usize, d: usize, eps: f32) !void { + try t.run("_add_rmsnorm", .{ u(rows), 1, 1 }, &.{ p("X", "*bf16", x), p("R", "*bf16", r orelse x), p("W", "*bf16", w), p("H", "*bf16", if (r != null) h else x), p("Y", "*bf16", y), p("XS", "*fp32", xs), aot.float("eps", eps) }, &.{ ci("D", d), ci("BLOCK", pow2(d)), ci("HAS_R", @intFromBool(r != null)) }); + } + + /// glue.gdn_pre: conv over each row's window of [state; qkv], q/k norms, g and beta; `sid`: several streams. + pub fn gdnPre(t: Tri, qkv: u64, cs: u64, cw: u64, win: u64, sid: ?u64, a: u64, b: u64, alog: u64, dtb: u64, q: u64, k: u64, v: u64, g: u64, beta: u64, rows: usize, m: Gdn) !void { + try t.run("_gdn_pre", .{ u(rows), u(2 * m.kh + m.vh), 1 }, &.{ + p("QKV", "*bf16", qkv), p("CS", "*bf16", cs), p("CW", "*bf16", cw), p("WIN", "*i32", win), p("A", "*bf16", a), p("B", "*bf16", b), p("ALOG", "*fp32", alog), + p("DTB", "*fp32", dtb), p("Q", "*bf16", q), p("K", "*bf16", k), p("V", "*bf16", v), p("G", "*fp32", g), p("BETA", "*fp32", beta), p("SID", "*i32", sid orelse win), + }, &.{ ci("C", m.c), ci("KH", m.kh), ci("VH", m.vh), ci("DK", m.dk), ci("NKEEP", m.keep), ci("MULTI", @intFromBool(sid != null)) }); + } + + /// glue.gated_norm: silu(z) * rmsnorm(y) * w per value head, and its group sums. + pub fn gatedNorm(t: Tri, y: u64, z: u64, w: u64, out: u64, xs: u64, rows: usize, vh: usize, dv: usize, eps: f32) !void { + try t.run("_gated_norm", .{ u(rows), u(vh), 1 }, &.{ p("Yr", "*bf16", y), p("Z", "*bf16", z), p("W", "*bf16", w), p("OUT", "*bf16", out), p("XS", "*fp32", xs), aot.float("eps", eps) }, &.{ ci("VH", vh), ci("DV", dv) }); + } + + /// glue.swiglu: silu(gate) * up in 1024-column blocks, and its group sums. + pub fn swiglu(t: Tri, gate: u64, up: u64, out: u64, xs: u64, rows: usize, n: usize) !void { + try t.run("_swiglu", .{ u(rows), cdiv(n, 1024), 1 }, &.{ p("GATE", "*bf16", gate), p("UP", "*bf16", up), p("OUT", "*bf16", out), p("XS", "*fp32", xs) }, &.{ ci("N", n), ci("BLOCK", 1024) }); + } + + /// glue.attn_prep: q (from the [q | gate] rows) and k normed, then rotated at each row's position. + pub fn attnPrep(t: Tri, qg: u64, kv: u64, qn: u64, kn: u64, pos: u64, inv: u64, qout: u64, kout: u64, rows: usize, a: Attn, eps: f32) !void { + try t.run("_attn_prep", .{ u(rows), u(a.heads + a.kv_heads), 1 }, &.{ p("QG", "*bf16", qg), p("KV", "*bf16", kv), p("QN", "*bf16", qn), p("KN", "*bf16", kn), p("POS", "*i32", pos), p("INV", "*fp32", inv), p("QOUT", "*bf16", qout), p("KOUT", "*bf16", kout), aot.float("eps", eps) }, &.{ + ci("H", a.heads), ci("HKV", a.kv_heads), ci("D", a.dim), ci("HALF", a.half), ci("MROPE", 0), ci("ROWS", 0), ci("HSEC", 11), ci("WSEC", 10), + }); + } + + /// glue.gate_mul: the attention output times sigmoid(gate) from the [q | gate] rows, and its group sums. + pub fn gateMul(t: Tri, o: u64, qg: u64, out: u64, xs: u64, rows: usize, heads: usize, dim: usize) !void { + try t.run("_gate_mul", .{ u(rows), u(heads), 1 }, &.{ p("O", "*bf16", o), p("QG", "*bf16", qg), p("OUT", "*bf16", out), p("XS", "*fp32", xs) }, &.{ ci("H", heads), ci("D", dim) }); + } + + /// qmm.group_sums: each row's 64-group input sums in fp32 (rows may be strided by `ld`). + pub fn groupSums(t: Tri, x: u64, xs: u64, ld: usize, rows: usize, k: usize) !void { + try t.run("_group_sums", .{ u(rows), cdiv(k / 64, 16), 1 }, &.{ p("X", "*bf16", x), p("XS", "*fp32", xs), int("ldx", ld) }, &.{ ci("KG", k / 64), ci("GS", 64), ci("GB", 16) }); + } + + /// attention.from_packed's _paths: each row's root-to-row window rows and its depth. + pub fn paths(t: Tri, parents: u64, out: u64, depths: u64, rows: usize) !void { + try t.run("_paths", .{ u(rows), 1, 1 }, &.{ p("PARENTS", "*i32", parents), p("PATHS", "*i32", out), p("DEPTHS", "*i32", depths) }, &.{ci("MAXD", max_nodes)}); + } + + /// The layout attention.attention reads: the plan's tables and the partial buffers it writes. + pub const Plan = struct { streams: u64, items: u64, n_items: usize, rows: u64, paths: u64, depths: u64, width: usize }; + pub const Partials = struct { o: u64, m: u64, l: u64 }; + + /// attention.attention: committed keys in 512-key chunks, the row's own path in its tail, merged in order. + pub fn attention(t: Tri, q: u64, kn: u64, vn: u64, base: u64, offs: u64, plan: Plan, part: Partials, out: u64, a: Attn) !void { + const g = a.heads / a.kv_heads; + const scale: f32 = @floatCast(std.math.pow(f64, @floatFromInt(a.dim), -0.5)); + const w = plan.width; + if (plan.n_items > 0) try t.run("_shared", .{ u(plan.n_items * a.kv_heads), 1, 1 }, &.{ + p("Q", "*bf16", q), p("KC", "*bf16", base), p("VC", "*bf16", base), p("OFF", "*i64", offs), p("STREAM", "*i32", plan.streams), + p("ITEMS", "*i32", plan.items), p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), int("W", w), + }, &.{ ci("H", a.heads), ci("HK", a.kv_heads), ci("D", a.dim), ci("G", g), ci("CH", chunk), aot.cf("SCALE", scale), ci("GR", group_chunks) }); + const tails = 1 + (max_nodes + chunk - 1) / chunk; + try t.run("_tail", .{ u(w), u(a.kv_heads), u(tails) }, &.{ + p("Q", "*bf16", q), p("KN", "*bf16", kn), p("VN", "*bf16", vn), p("KC", "*bf16", base), p("VC", "*bf16", base), p("OFF", "*i64", offs), p("STREAM", "*i32", plan.streams), + p("ROWS", "*i32", plan.rows), p("PATHS", "*i32", plan.paths), p("DEPTHS", "*i32", plan.depths), p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), int("W", w), + }, &.{ ci("H", a.heads), ci("HK", a.kv_heads), ci("D", a.dim), ci("G", g), ci("CH", chunk), ci("MAXD", max_nodes), aot.cf("SCALE", scale), ci("GR", group_chunks) }); + try t.run("_merge", .{ u(w), u(a.kv_heads), u(a.dim / merge_columns) }, &.{ + p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), p("OUT", "*bf16", out), p("STREAM", "*i32", plan.streams), p("ROWS", "*i32", plan.rows), int("W", w), + }, &.{ ci("H", a.heads), ci("D", a.dim), ci("G", g), ci("DS", merge_columns), ci("CH", chunk), ci("GR", group_chunks) }); + } +}; + +/// attention.groups: whole committed 2048-key groups fold in their own programs only when they fill the GPU. +pub fn groups(p_: usize, w: usize) usize { + const g = p_ / (chunk * group_chunks); + return if (g * w >= 64) g else 0; +} + +/// attention.slots: one partial slot per folded group, then one per chunk through the window's last key. +pub fn slots(p_: usize, w: usize) usize { + const g = groups(p_, w); + return g + (p_ + w + chunk - 1) / chunk - g * group_chunks; +} + +test "attention slots follow the Python plan" { + try std.testing.expectEqual(@as(usize, 1), slots(0, 1)); + try std.testing.expectEqual(@as(usize, 2), slots(512, 1)); + try std.testing.expectEqual(@as(usize, 9), slots(4096, 1)); // 8 chunks + the window's own + try std.testing.expectEqual(@as(usize, 13), slots(6144, 16)); // 3 groups x 16 rows < 64: every chunk its own + try std.testing.expectEqual(@as(usize, 4), slots(6144, 32)); // 3 folded groups, then the window's chunk +} diff --git a/zig/src/families/qwen27/cuda/weights.zig b/zig/src/families/qwen27/cuda/weights.zig new file mode 100644 index 0000000000..5c796bd43a --- /dev/null +++ b/zig/src/families/qwen27/cuda/weights.zig @@ -0,0 +1,252 @@ +//! The 27B's weights on the GPU in the Python engine's layouts: tiled projections, the stored embedding, fp32 gates. + +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const source = @import("nemotron").source; +const c = @import("shape.zig"); +const config_eos = @import("../config.zig").max_eos; +const kern = @import("kernels.zig"); + +pub const QLinear = kern.QLinear; +const Tensor = core.checkpoint.Tensor; +const prefix = "language_model."; + +/// The token table as stored (MLX words, scales, biases): a row lookup, not a matmul. +pub const Embed = struct { w: u64, s: u64, b: u64 }; +pub const Delta = struct { qkv: QLinear, z: QLinear, b: QLinear, a: QLinear, out: QLinear, conv: u64, a_log: u64, dt_bias: u64, norm: u64 }; +pub const Attention = struct { q: QLinear, k: QLinear, v: QLinear, o: QLinear, q_norm: u64, k_norm: u64 }; +pub const Mixer = union(enum) { delta: Delta, attention: Attention }; +pub const Layer = struct { input_norm: u64, post_norm: u64, mixer: Mixer, gate: QLinear, up: QLinear, down: QLinear }; + +pub const Weights = struct { + gpa: std.mem.Allocator, + g: c.Geometry, + embed: Embed = undefined, + layers: []Layer = &.{}, + norm: u64 = 0, + head: QLinear = undefined, + inv_freq: u64 = 0, // (rotary_dim / 2,) fp32 + eos: [config_eos]u32 = undefined, // config.json's end tokens, then generation_config.json's + eos_count: usize = 0, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + + pub fn deinit(w: *Weights) void { + for (w.buffers.items) |*b| b.free(); + w.buffers.deinit(w.gpa); + w.gpa.free(w.layers); + w.* = undefined; + } + + pub fn isEos(w: *const Weights, token: u32) bool { + for (w.eos[0..w.eos_count]) |e| if (e == token) return true; + return false; + } + + /// Device bytes the weights hold. + pub fn bytes(w: *const Weights) usize { + var n: usize = 0; + for (w.buffers.items) |b| n += b.len; + return n; + } +}; + +const Loader = struct { + gpa: std.mem.Allocator, + ops: kern.Ops, + w: *Weights, + src: *source.Source, + scratch: cuda.DeviceBuffer, + host: std.ArrayList(u8) = .empty, + + fn alloc(L: *Loader, len: usize) !u64 { + const b = try cuda.DeviceBuffer.alloc(L.ops.k.d, len); + try L.w.buffers.append(L.gpa, b); + return b.ptr; + } + + /// Device scratch of at least `len` bytes; growing waits for the stream so pending packs keep their inputs. + fn tmp(L: *Loader, len: usize) !u64 { + if (L.scratch.len < len) { + try L.src.flush(); + try L.ops.s.synchronize(); + L.scratch.free(); + L.scratch = try cuda.DeviceBuffer.alloc(L.ops.k.d, len); + } + return L.scratch.ptr; + } + + /// The host staging buffer, once the stream has read its last contents. + fn staging(L: *Loader, len: usize) ![]u8 { + try L.src.flush(); + try L.ops.s.synchronize(); + try L.host.resize(L.gpa, len); + return L.host.items; + } + + fn raw(L: *Loader, t: Tensor) !u64 { + const ptr = try L.alloc(t.bytes.len); + try L.src.upload(ptr, t.bytes); + return ptr; + } + + /// `.float()` of a bf16 tensor (or an f32 one as stored): exact. + fn widen(L: *Loader, t: Tensor) !u64 { + if (t.dtype == .f32) return L.raw(t); + if (t.dtype != .bf16) return error.UnexpectedTensor; + const n = t.bytes.len / 2; + const out = std.mem.bytesAsSlice(u32, try L.staging(n * 4)); + const in = try L.src.view(t.bytes); + for (out, 0..) |*o, i| o.* = @as(u32, std.mem.readInt(u16, in[2 * i ..][0..2], .little)) << 16; + const ptr = try L.alloc(n * 4); + try L.ops.upload(ptr, L.host.items); + return ptr; + } + + /// qmm_fast.tile: MLX words, scales and biases packed into the lane matmul's tiled layout. + fn tile(L: *Loader, ck: *core.Checkpoint, name: []const u8, n: usize, k: usize) !QLinear { + var parts: [3]Tensor = undefined; + var buf: [192]u8 = undefined; + for ([_][]const u8{ "weight", "scales", "biases" }, 0..) |s, i| parts[i] = try ck.get(try std.fmt.bufPrint(&buf, "{s}{s}.{s}", .{ prefix, name, s })); + const k8 = k / 8; + const kg = k / 64; + if (parts[0].dtype != .u32 or parts[1].dtype != .bf16 or parts[2].dtype != .bf16) return error.UnsupportedQuantization; + if (!parts[0].is(.u32, &.{ n, k8 }) or !parts[1].is(.bf16, &.{ n, kg }) or !parts[2].is(.bf16, &.{ n, kg })) { + std.log.err("{s}: not a 4-bit group-64 ({d}, {d}) projection", .{ name, n, k }); + return error.UnexpectedTensor; + } + const npad = (n + 127) / 128 * 128; + const sizes = [3]usize{ n * k8 * 4, n * kg * 2, n * kg * 2 }; + const base = try L.tmp(sizes[0] + sizes[1] + sizes[2]); + const at = [3]usize{ 0, sizes[0], sizes[0] + sizes[1] }; + for (0..3) |j| try L.src.upload(base + at[j], parts[j].bytes); + const q: QLinear = .{ .w = try L.alloc(npad * k / 2), .s = try L.alloc(kg * npad * 2), .b = try L.alloc(kg * npad * 2), .n = n, .k = k, .npad = npad }; + const total: u64 = @as(u64, npad / 64) * kg * 512; + try L.src.flush(); + var a: cuda.Args = .{}; + a.add(base); + for ([_]usize{ n, k8, kg }) |v| a.add(@as(c_int, @intCast(v))); + a.add(q.w); + a.add(@as(c_longlong, @intCast(total))); + try cuda.launch.launch(L.ops.k.pack_dense, .{ .grid = .{ .x = @intCast((total + 255) / 256) }, .block = .{ .x = 256 } }, L.ops.s, &a); + for ([_]u64{ q.s, q.b }, [_]usize{ at[1], at[2] }) |out, off| { + var t: cuda.Args = .{}; + t.add(base + off); + for ([_]usize{ n, kg, npad }) |v| t.add(@as(c_int, @intCast(v))); + t.add(out); + const cells = @as(u64, kg) * npad; + try cuda.launch.launch(L.ops.k.transpose16, .{ .grid = .{ .x = @intCast((cells + 255) / 256) }, .block = .{ .x = 256 } }, L.ops.s, &t); + } + return q; + } + + fn vector(L: *Loader, ck: *core.Checkpoint, name: []const u8, len: usize) !u64 { + var buf: [192]u8 = undefined; + return L.raw(try ck.expect(try std.fmt.bufPrint(&buf, "{s}{s}", .{ prefix, name }), .bf16, &.{len})); + } + + fn delta(L: *Loader, ck: *core.Checkpoint, p: []const u8, g: c.Geometry) !Delta { + var b1: [160]u8 = undefined; + var b2: [192]u8 = undefined; + const at = struct { + fn f(buf: []u8, pre: []const u8, name: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, "{s}linear_attn.{s}", .{ pre, name }); + } + }.f; + var d: Delta = undefined; + d.qkv = try L.tile(ck, try at(&b1, p, "in_proj_qkv"), g.convDim(), g.hidden); + d.z = try L.tile(ck, try at(&b1, p, "in_proj_z"), g.vInner(), g.hidden); + d.b = try L.tile(ck, try at(&b1, p, "in_proj_b"), g.linear_v_heads, g.hidden); + d.a = try L.tile(ck, try at(&b1, p, "in_proj_a"), g.linear_v_heads, g.hidden); + d.out = try L.tile(ck, try at(&b1, p, "out_proj"), g.hidden, g.vInner()); + // conv1d.weight (C, 4, 1) is (C, 4) as stored: the reshape moves no bytes + d.conv = try L.raw(try ck.expect(try std.fmt.bufPrint(&b2, "{s}{s}", .{ prefix, try at(&b1, p, "conv1d.weight") }), .bf16, &.{ g.convDim(), c.conv_taps, 1 })); + d.a_log = try L.widen(try ck.get(try std.fmt.bufPrint(&b2, "{s}{s}", .{ prefix, try at(&b1, p, "A_log") }))); + d.dt_bias = try L.widen(try ck.get(try std.fmt.bufPrint(&b2, "{s}{s}", .{ prefix, try at(&b1, p, "dt_bias") }))); + d.norm = try L.vector(ck, try at(&b1, p, "norm.weight"), c.linear_dim); + return d; + } + + fn attention(L: *Loader, ck: *core.Checkpoint, p: []const u8, g: c.Geometry) !Attention { + var b1: [160]u8 = undefined; + const at = struct { + fn f(buf: []u8, pre: []const u8, name: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, "{s}self_attn.{s}", .{ pre, name }); + } + }.f; + return .{ + .q = try L.tile(ck, try at(&b1, p, "q_proj"), 2 * g.qInner(), g.hidden), + .k = try L.tile(ck, try at(&b1, p, "k_proj"), g.kvInner(), g.hidden), + .v = try L.tile(ck, try at(&b1, p, "v_proj"), g.kvInner(), g.hidden), + .o = try L.tile(ck, try at(&b1, p, "o_proj"), g.hidden, g.qInner()), + .q_norm = try L.vector(ck, try at(&b1, p, "q_norm.weight"), c.head_dim), + .k_norm = try L.vector(ck, try at(&b1, p, "k_norm.weight"), c.head_dim), + }; + } +}; + +/// weights.inv_freq: theta ** (-i / half) in float64, rounded to fp32. +pub fn invFreq(out: []f32) void { + const half: f64 = @floatFromInt(out.len); + for (out, 0..) |*f, i| f.* = @floatCast(std.math.pow(f64, c.theta, -@as(f64, @floatFromInt(i)) / half)); +} + +/// weights.load (tiled, one GPU): the model folder's text tensors on the GPU, leftovers refused. +pub fn load(gpa: std.mem.Allocator, io: std.Io, ops: kern.Ops, dir: []const u8, cfg: c.Config) !Weights { + const g = cfg.g; + var w: Weights = .{ .gpa = gpa, .g = g, .eos = cfg.eos, .eos_count = cfg.eos_count }; + errdefer w.deinit(); + var src = try source.Source.init(gpa, .{ .d = ops.k.d, .s = ops.s, .discrete = ops.k.discrete }); + defer src.deinit(); + var L: Loader = .{ .gpa = gpa, .ops = ops, .w = &w, .src = &src, .scratch = try cuda.DeviceBuffer.alloc(ops.k.d, 1 << 20) }; + defer { + src.flush() catch {}; + ops.s.synchronize() catch {}; + L.scratch.free(); + L.host.deinit(gpa); + } + // the vision tower and the MTP head stay on disk, as weights._Tensors skips them + var ck = try core.Checkpoint.openModelPrefix(gpa, io, dir, prefix); + defer ck.close(); + try src.add(&ck); + w.layers = try gpa.alloc(Layer, g.layers); + for (w.layers, 0..) |*layer, i| { + var pb: [64]u8 = undefined; + var nb: [160]u8 = undefined; + const p = try std.fmt.bufPrint(&pb, "model.layers.{d}.", .{i}); + const join = struct { + fn f(buf: []u8, a: []const u8, b: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, "{s}{s}", .{ a, b }); + } + }.f; + layer.input_norm = try L.vector(&ck, try join(&nb, p, "input_layernorm.weight"), g.hidden); + layer.mixer = if (c.linear(i)) .{ .delta = try L.delta(&ck, p, g) } else .{ .attention = try L.attention(&ck, p, g) }; + layer.gate = try L.tile(&ck, try join(&nb, p, "mlp.gate_proj"), g.intermediate, g.hidden); + layer.up = try L.tile(&ck, try join(&nb, p, "mlp.up_proj"), g.intermediate, g.hidden); + layer.down = try L.tile(&ck, try join(&nb, p, "mlp.down_proj"), g.hidden, g.intermediate); + layer.post_norm = try L.vector(&ck, try join(&nb, p, "post_attention_layernorm.weight"), g.hidden); + } + w.embed = .{ + .w = try L.raw(try ck.expect(prefix ++ "model.embed_tokens.weight", .u32, &.{ c.vocab, g.hidden / 8 })), + .s = try L.raw(try ck.expect(prefix ++ "model.embed_tokens.scales", .bf16, &.{ c.vocab, g.hidden / 64 })), + .b = try L.raw(try ck.expect(prefix ++ "model.embed_tokens.biases", .bf16, &.{ c.vocab, g.hidden / 64 })), + }; + w.norm = try L.vector(&ck, "model.norm.weight", g.hidden); + w.head = try L.tile(&ck, "lm_head", c.vocab, g.hidden); + if (ck.unused() != 0) return error.UnusedCheckpointTensors; + var inv: [c.rotary_dim / 2]f32 = undefined; + invFreq(&inv); + w.inv_freq = try L.alloc(@sizeOf(@TypeOf(inv))); + try ops.upload(w.inv_freq, std.mem.asBytes(&inv)); + try src.flush(); + try ops.s.synchronize(); + return w; +} + +test "inv_freq: theta ** (-i / 32) rounded to fp32" { + var inv: [32]f32 = undefined; + invFreq(&inv); + try std.testing.expectEqual(@as(f32, 1.0), inv[0]); + try std.testing.expectEqual(@as(f32, 0.6042963862419128), inv[1]); + try std.testing.expectEqual(@as(f32, 0.22067341208457947), inv[3]); +} diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 296aa21409..032f64c603 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -4,13 +4,14 @@ const cuda = @import("cuda"); const api = @import("engine_api"); const lanes = @import("lanes"); const nemotron = @import("nemotron"); +const qwen27 = @import("qwen27"); const Allocator = std.mem.Allocator; const budget = @import("cuda_memory.zig"); const nemotron_slide = @import("nemotron_slide.zig"); const Pool = budget.Pool; /// CUDA families provide metadata, open their lane backend and explain their refusals. -const registry = .{nemotron.native}; +const registry = .{ nemotron.native, qwen27.native }; /// Nemotron's prompt-cache copies. A file-level value so the store's pointer stays valid for the process. const nemotron_snaps: api.prompt_cache.Snapshots.VTable = .{ @@ -410,7 +411,10 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O problem.* = try std.fmt.allocPrint(a, "the checkpoint's {d:.1} GiB of weights do not fit the {d:.1} GiB the CUDA memory budget grants ({d:.1} GiB free less a {d:.1} GiB reserve{s}); free device memory or adjust TENSORFOLD_MEMORY_RESERVE_GIB / TENSORFOLD_CUDA_MEMORY_LIMIT_GB", .{ toGib(weights), toGib(before.room(held0)), toGib(before.free), toGib(before.reserve), if (before.limit != null) ", under TENSORFOLD_CUDA_MEMORY_LIMIT_GB" else "" }); return null; } - const loaded = F.open(gpa, io, &g.ctx, o.dir, kernels, .{ .context = @intCast(window), .drafts = o.drafts, .segments = segments, .slide = o.slide }) catch |e| { + var family_options: F.Options = .{ .context = @intCast(window), .drafts = o.drafts, .segments = segments }; + if (@hasField(F.Options, "slide")) family_options.slide = o.slide; + if (@hasField(F.Options, "drafter")) family_options.drafter = o.drafter; + const loaded = F.open(gpa, io, &g.ctx, o.dir, kernels, family_options) catch |e| { problem.* = try std.fmt.allocPrint(a, "the native CUDA engine cannot load {s} with {s} glue kernels ({s})", .{ o.dir, kernels orelse "its own", @errorName(e) }); return null; }; @@ -429,13 +433,14 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O const h = try gpa.create(Host); errdefer gpa.destroy(h); h.* = .{ .gpa = gpa, .gpu = g, .family = loaded.ctx, .release = loaded.deinit, .inner = loaded.backend, .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .lone = loaded.lone }; - const cache = budget.cacheBytes(o.prompt_cache_gib, room, loaded.stream_bytes * (streams -| free)); + // prompt-cache snapshots are Nemotron's (cuda_reuse.zig); a family without them serves without a cache + const cache = if (@hasDecl(F, "snap_bytes")) budget.cacheBytes(o.prompt_cache_gib, room, loaded.stream_bytes * (streams -| free)) else 0; h.startup = try std.fmt.allocPrint(gpa, "CUDA sm_{d} device {d} ({s}{s}): model {d:.2} GiB{s}; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window, of {d:.1} GiB left after a {d:.1} GiB reserve; prompts in {d}-row chunks{s}{s}; {s}", .{ capability, device, name, if (after.unified) ", memory shared with the host" else "", toGib(model), if (loaded.learn_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for --slide's trainer", .{toGib(loaded.learn_bytes)}) else "", streams, if (streams == 1) "" else "s", toGib(loaded.stream_bytes), window, toGib(room), toGib(after.reserve), F.prompt_rows, if (segments > 1) try std.fmt.allocPrint(a, ", {d} staggered segments a call", .{segments}) else "", if (cache > 0) try std.fmt.allocPrint(a, ", a {d:.1} GiB prompt cache", .{toGib(cache)}) else ", no prompt cache", if (kernels) |dir| try std.fmt.allocPrint(a, "glue kernels captured at {s}", .{dir}) else "own glue kernels", }); errdefer gpa.free(h.startup); - if (cache > 0) { + if (@hasDecl(F, "snap_bytes") and cache > 0) { const pc = api.prompt_cache; const store = try gpa.create(pc.Store); // states kept and resumed on the family's grid, where a cache-off pass cuts; the head reads one token on @@ -446,7 +451,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O store.deinit(); gpa.destroy(store); }; - if (loaded.learns) |e| { + if (@hasDecl(F, "slide")) if (loaded.learns) |e| { const Slide = nemotron_slide.Adapter(F.slide); const s = try gpa.create(Slide); s.* = Slide.init(gpa, io, e); @@ -459,7 +464,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O } }.f; h.learn = s.hook(); - } + }; errdefer if (h.slide) |s| h.slide_free.?(gpa, s); // the family cuts its own prompt grid from position 0, as `tensorfold run` does: prefill_step 0 try h.serve(io, loaded.facts, loaded.rows, .{ .lanes = streams, .context_window = @intCast(window), .startup = h.startup, .prompt_cache = h.store != null, .logprobs = loaded.backend.vtable.first_row != null }, .{ .ctx = loaded.ctx, .text = F.explain }); diff --git a/zig/tests/cuda/qwen27/capture.py b/zig/tests/cuda/qwen27/capture.py new file mode 100644 index 0000000000..a21dd828eb --- /dev/null +++ b/zig/tests/cuda/qwen27/capture.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""The 27B's Python CUDA engine as the Zig engine's oracle: Triton launches, per-layer dumps, tokens.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +import time +from pathlib import Path + +TEXTS = { + "story": "Write a short story about a lighthouse keeper who finds a message in a bottle.", + "code": "Write a Python function that merges two sorted lists, with a docstring and three tests.", + "facts": "Explain how a refrigerator moves heat out of its cabinet, step by step.", +} +LONG_BODY = 5000 # tokens of module source in the long prompt: two 4096-row prompt chunks +TEACHER = 32 # teacher-forced decode steps (one row each, from an empty state) +DUMP_STEPS = (0, 1, TEACHER - 1) + + +def chat(user: str) -> str: + return f"<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + + +def prompts(model: Path) -> dict[str, list[int]]: + from tokenizers import Tokenizer + import textwrap + + tok = Tokenizer.from_file(str(model / "tokenizer.json")) + out = {name: tok.encode(chat(text), add_special_tokens=False).ids for name, text in TEXTS.items()} + words = Path(textwrap.__file__).read_text() + body = tok.encode(words * (1 + LONG_BODY // max(1, len(words) // 3)), add_special_tokens=False).ids[:LONG_BODY] + head = tok.encode("<|im_start|>user\nReview this module and list its public functions:\n\n", + add_special_tokens=False).ids + tail = tok.encode("<|im_end|>\n<|im_start|>assistant\n\n\n\n\n", add_special_tokens=False).ids + out["long"] = head + body + tail + return out + + +def sha12(tokens: list[int]) -> str: + return hashlib.sha256(json.dumps([int(t) for t in tokens]).encode()).hexdigest()[:12] + + +def digest(t) -> str: + import torch + + raw = t.detach().contiguous() + return hashlib.sha256(raw.view(torch.uint8).cpu().numpy().tobytes()).hexdigest() + + +class Dumps: + """Raw little-endian tensors by name under the current directory; None turns dumping off.""" + + def __init__(self) -> None: + self.dir: Path | None = None + self.i = 0 + + def at(self, d: Path | None) -> None: + self.dir, self.i = d, 0 + if d is not None: + d.mkdir(parents=True, exist_ok=True) + + def save(self, name: str, t) -> None: + import torch + + if self.dir is None: + return + torch.cuda.synchronize() + t.detach().contiguous().view(torch.uint8).cpu().numpy().tofile(self.dir / f"{name}.bin") + + +def hook(dumps: Dumps) -> None: + """Every add_rmsnorm call's (h, y, xs), in call order: two a layer, then the final norm.""" + + from tensorfold.families.qwen3_5.cuda import glue + + norm = glue.add_rmsnorm + + def traced(x, r, w, eps): + h, y, xs = norm(x, r, w, eps) + if dumps.dir is not None: + i = dumps.i + dumps.i += 1 + dumps.save(f"{i:03d}_h", h) + dumps.save(f"{i:03d}_y", y) + dumps.save(f"{i:03d}_xs", xs) + return h, y, xs + + glue.add_rmsnorm = traced + + +def specialization() -> dict: + """Each launched JIT function's parameter names and which ones Triton never specializes.""" + + from triton.runtime.jit import JITFunction + import gc + + out = {} + for fn in gc.get_objects(): + if isinstance(fn, JITFunction): + name = f"{fn.fn.__module__}.{fn.fn.__qualname__}" + out[name] = {"params": [p.name for p in fn.params], + "do_not_specialize": [p.name for p in fn.params if p.do_not_specialize], + "no_align": [p.name for p in fn.params if p.do_not_specialize_on_alignment]} + return out + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--model", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--tools", default="", help="folder of triton_aot_manifest.py: record every Triton launch") + ap.add_argument("--max-tokens", type=int, default=128) + ap.add_argument("--repeats", type=int, default=2) + ap.add_argument("--context", type=int, default=16384) + a = ap.parse_args() + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + rec = None + if a.tools: + sys.path.insert(0, a.tools) + import triton_aot_manifest as aot + + rec = aot.Recorder().install() + + import torch + from contextlib import nullcontext + + def phase(name: str, detail: bool = False): + return rec.scope(name, detail) if rec is not None else nullcontext() + + model = Path(a.model) + ids = prompts(model) + (out / "prompts.json").write_text(json.dumps(ids) + "\n") + dumps = Dumps() + hook(dumps) + from tensorfold.families.qwen3_5.cuda.engine import Qwen27Engine + + t0 = time.perf_counter() + with phase("startup"): + eng = Qwen27Engine(model, None, streams=1, context=a.context, context_explicit=True) + if rec is not None: + from tensorfold.cuda.kernels import gdn, prefill_attention, qmm + + rec.wrap(qmm._ext(), ("qmm", "qmm_group", "qmm_prefill"), "qmm") + rec.wrap(gdn._ext(), ("tree", "replay", "prefill"), "gdn") + rec.wrap(prefill_attention._ext(), ("prefill_attention",), "prefill_attention") + info = {"startup_s": round(time.perf_counter() - t0, 2), "context": eng.context_window, "eos": list(eng.eos), + "prompt_rows": eng.w.prompt_rows, "torch": torch.__version__, "gpu": torch.cuda.get_device_name(0)} + print(json.dumps(info), flush=True) + + results: dict[str, dict] = {} + for name, prompt in ids.items(): + runs = [] + for _ in range(a.repeats): + toks: list[int] = [] + with phase(f"serial-{name}"): + torch.cuda.synchronize() + start = time.perf_counter() + stats = eng.generate(prompt, a.max_tokens, None, lambda new: toks.extend(map(int, new)) and False, + draft=False, stop_eos=True) + torch.cuda.synchronize() + wall = time.perf_counter() - start + runs.append({"tokens": toks, "sha": sha12(toks), "wall_s": round(wall, 4), **stats}) + last = runs[-1] + same = all(r["tokens"] == last["tokens"] for r in runs) + step = last.get("decode_s", 0.0) / max(1, len(last["tokens"]) - 1) * 1e3 + results[name] = {**last, "repeats_same": same, "ms_per_token": round(step, 4)} + print(f"serial {name}: {len(last['tokens'])} tokens sha {last['sha']} prefill {last.get('prefill_s'):.3f}s " + f"{step:.3f} ms/token same {same}", flush=True) + + from tensorfold.families.qwen3_5.cuda.decode import prefill + from tensorfold.families.qwen3_5.cuda.forward import State, commit, tree_forward + + w = eng.w + tf = ids["code"][:TEACHER] + sampled, logit_sha = [], [] + st = State(w) + with phase("teacher", detail=True): + for i, t in enumerate(tf): + dumps.at(out / "teacher" / f"step{i:03d}" if i in DUMP_STEPS else None) + logits, record = tree_forward(w, torch.tensor([t], dtype=torch.int32, device="cuda"), [-1], st) + dumps.save("logits", logits) + sampled.append(int(logits.argmax(dim=-1)[0])) + logit_sha.append(digest(logits)) + commit(st, record, [0]) + dumps.at(None) + pre_out = {} + for name in ("code", "long"): + dumps.at(out / "prefill" / name if name == "code" else None) + with phase(f"prefill-{name}", detail=name == "code"): + _, pending = prefill(w, ids[name], None, limit=a.context) + dumps.at(None) + pre_out[name] = {"pending": pending} + (out / "teacher.json").write_text(json.dumps({"tokens": tf, "sampled": sampled, "logits_sha256": logit_sha, + "dump_steps": list(DUMP_STEPS), "prefill": pre_out}) + "\n") + (out / "results.json").write_text(json.dumps({"info": info, "results": results}, indent=1) + "\n") + if rec is not None: + rec.dump(out / "launches.json") + (out / "jit.json").write_text(json.dumps(specialization(), indent=1, sort_keys=True) + "\n") + print("done", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/zig/tests/cuda/qwen27/capture_draft.py b/zig/tests/cuda/qwen27/capture_draft.py new file mode 100644 index 0000000000..b5aa457ebc --- /dev/null +++ b/zig/tests/cuda/qwen27/capture_draft.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""The 27B's DFlash2 drafting as the Zig engine's oracle: drafted replies (equal to serial), rounds, Triton launches.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +import time +from pathlib import Path + + +def sha12(tokens: list[int]) -> str: + return hashlib.sha256(json.dumps([int(t) for t in tokens]).encode()).hexdigest()[:12] + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--model", required=True) + ap.add_argument("--draft", required=True) + ap.add_argument("--prompts", required=True, help="capture.py's prompts.json") + ap.add_argument("--out", required=True) + ap.add_argument("--tools", default="") + ap.add_argument("--max-tokens", type=int, default=128) + a = ap.parse_args() + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + rec = None + if a.tools: + sys.path.insert(0, a.tools) + import triton_aot_manifest as aot + + rec = aot.Recorder().install() + import torch + + from tensorfold.families.qwen3_5.cuda.decode import draft_decode, prefill + from tensorfold.families.qwen3_5.cuda.engine import Qwen27Engine + + eng = Qwen27Engine(Path(a.model), Path(a.draft), streams=1, context=16384, context_explicit=True) + if rec is not None: + from tensorfold.cuda.kernels import gdn, prefill_attention, qmm + + rec.wrap(qmm._ext(), ("qmm", "qmm_group", "qmm_prefill"), "qmm") + rec.wrap(gdn._ext(), ("tree", "replay", "prefill"), "gdn") + rec.wrap(prefill_attention._ext(), ("prefill_attention",), "prefill_attention") + prompts = json.loads(Path(a.prompts).read_text()) + results = {} + for name, ids in prompts.items(): + for _ in range(2): # the second run is the timed one + drafter = eng.draft + drafter.restore(([None] * drafter.layers, [None] * drafter.layers, 0, 0)) + torch.cuda.synchronize() + t0 = time.perf_counter() + st, pending = prefill(eng.w, ids, None, drafter, limit=16384) + trace: list = [] + r = draft_decode(eng.w, st, ids, pending, a.max_tokens, None, drafter, max_rows=eng.max_rows, + tree_rows=eng.tree_rows, allow_copy=True, stop_eos=True, trace=trace, inplace=True) + torch.cuda.synchronize() + wall = time.perf_counter() - t0 + results[name] = {"tokens": r.tokens, "sha": sha12(r.tokens), "rounds": r.rounds, "drafted": r.drafted_rows, + "accepted": r.accepted_drafts, "decode_s": round(r.seconds, 4), "wall_s": round(wall, 4), + "widths": r.widths, "paths": [len(t.get("path", [])) for t in trace]} + print(f"{name}: {len(r.tokens)} tokens sha {sha12(r.tokens)} rounds {r.rounds} accepted {r.accepted_drafts} " + f"{len(r.tokens) / r.seconds:.1f} tok/s", flush=True) + (out / "draft.json").write_text(json.dumps({"max_rows": eng.max_rows, "results": results}) + "\n") + if rec is not None: + rec.dump(out / "launches.json") + print("done", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/zig/tests/cuda/qwen27/capture_multi.py b/zig/tests/cuda/qwen27/capture_multi.py new file mode 100644 index 0000000000..6d18232073 --- /dev/null +++ b/zig/tests/cuda/qwen27/capture_multi.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""The 27B's drafted shared rounds as the Zig engine's oracle: MultiDecoder's windows each round, and every reply.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +from pathlib import Path + +TOPICS = ["lighthouses", "volcanoes", "bread", "rivers", "chess", "glaciers", "owls", "trains"] +CODE = '''def fibonacci(n): + """Return the nth Fibonacci number.""" + if n < 2: + return n + a, b = 0, 1 + for _ in range(n - 1): + a, b = b, a + b + return b +''' + + +def chat(user: str) -> str: + return f"<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + + +def sha12(tokens: list[int]) -> str: + return hashlib.sha256(json.dumps([int(t) for t in tokens]).encode()).hexdigest()[:12] + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--model", required=True) + ap.add_argument("--draft", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--tools", default="") + ap.add_argument("--streams", type=int, default=6) + ap.add_argument("--max-tokens", type=int, default=96) + a = ap.parse_args() + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + rec = None + if a.tools: + sys.path.insert(0, a.tools) + import triton_aot_manifest as aot + + rec = aot.Recorder().install() + from tokenizers import Tokenizer + + from tensorfold.cuda.streams import Stream + from tensorfold.families.qwen3_5.cuda.engine import Qwen27Engine + from tensorfold.families.qwen3_5.cuda.multi import MultiDecoder + + model = Path(a.model) + tok = Tokenizer.from_file(str(model / "tokenizer.json")) + users = [f"Rewrite this function with a docstring that explains each step, keeping the code the same:\n\n{CODE}"] + users += [f"Write four sentences about {t}." for t in TOPICS] + prompts = [tok.encode(chat(u), add_special_tokens=False).ids for u in users[:a.streams]] + eng = Qwen27Engine(model, Path(a.draft), streams=1, context=8192, context_explicit=True) + if rec is not None: + from tensorfold.cuda.kernels import gdn, prefill_attention, qmm + + rec.wrap(qmm._ext(), ("qmm", "qmm_group", "qmm_prefill"), "qmm") + rec.wrap(gdn._ext(), ("tree", "replay", "prefill"), "gdn") + rec.wrap(prefill_attention._ext(), ("prefill_attention",), "prefill_attention") + # GB10's planning: no measured costs (every tree node verified), the drafter's block 16 rows a stream + md = MultiDecoder(eng.w, eng.draft, allow_copy=True, context=8192, keep=1) + md.depth = False + rounds: list[list[dict]] = [] + windows = md._windows + + def logged(plan, copied, blocks): + wins = windows(plan, copied, blocks) + rounds.append([{"stream": sid, "mode": ["copy", "tree", "one"][mode], "tokens": t, "parents": p} + for (sid, mode, _, _), (t, p) in zip(plan, wins)]) + return wins + + md._windows = logged + scores: list[list[float]] = [] # each tree's path scores, in finish order + finish = md.draft.finish_tree + + def scored(*args, **kw): + t = finish(*args, **kw) + scores.append([float(x) for x in t[2]]) + return t + + md.draft.finish_tree = scored + streams = [Stream(list(p), a.max_tokens, None, draft=True, stop_eos=True) for p in prompts] + for s in streams: + md.admit(s) + while any(not s.done for s in streams): + md.finish(md.round()) + results = [{"tokens": s.out, "sha": sha12(s.out), "rounds": s.rounds, "drafted": s.drafted, + "accepted": s.accepted} for s in streams] + for k, r in enumerate(results): + print(f"stream {k}: {len(r['tokens'])} tokens sha {r['sha']} rounds {r['rounds']} accepted {r['accepted']}", + flush=True) + (out / "multi.json").write_text(json.dumps({"prompts": prompts, "max_tokens": a.max_tokens, "results": results, + "rounds": rounds, "scores": scores}) + "\n") + if rec is not None: + rec.dump(out / "launches.json") + print(f"{len(rounds)} rounds", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/zig/tests/cuda/qwen27/capture_windows.py b/zig/tests/cuda/qwen27/capture_windows.py new file mode 100644 index 0000000000..78b7558951 --- /dev/null +++ b/zig/tests/cuda/qwen27/capture_windows.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""The 27B's verify windows as the Zig engine's oracle: chains of 1-16 rows and shared forwards, each row hashed.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +from pathlib import Path + +TOPICS = ["lighthouses", "volcanoes", "bread", "rivers", "chess", "glaciers", "owls", "trains", + "deserts", "bees", "clocks", "ferns", "kites", "salt", "comets", "violins"] +REPLY = 24 # serial tokens each stream decodes first: the chain windows' tokens + + +def chat(user: str) -> str: + return f"<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" + + +def sha(t) -> str: + import torch + + return hashlib.sha256(t.detach().contiguous().view(torch.uint8).cpu().numpy().tobytes()).hexdigest() + + +def rows(logits) -> list[dict]: + return [{"sha": sha(logits[r]), "argmax": int(logits[r].argmax())} for r in range(logits.shape[0])] + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--model", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--tools", default="") + ap.add_argument("--wide", action="store_true", help="also rounds past 16 rows") + ap.add_argument("--sweep", action="store_true", help="also every alignment of a shared round's packed inputs") + a = ap.parse_args() + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + rec = None + if a.tools: + sys.path.insert(0, a.tools) + import triton_aot_manifest as aot + + rec = aot.Recorder().install() + import torch + from tokenizers import Tokenizer + + from tensorfold.families.qwen3_5.cuda.decode import clone_state, prefill, serial_decode + from tensorfold.families.qwen3_5.cuda.engine import Qwen27Engine + from tensorfold.families.qwen3_5.cuda.forward import commit_streams, multi_tree_forward, tree_forward + + model = Path(a.model) + tok = Tokenizer.from_file(str(model / "tokenizer.json")) + prompts = [tok.encode(chat(f"Write four sentences about {t}."), add_special_tokens=False).ids for t in TOPICS] + eng = Qwen27Engine(model, None, streams=1, context=4096, context_explicit=True) + if rec is not None: + from tensorfold.cuda.kernels import gdn, prefill_attention, qmm + + rec.wrap(qmm._ext(), ("qmm", "qmm_group", "qmm_prefill"), "qmm") + rec.wrap(gdn._ext(), ("tree", "replay", "prefill"), "gdn") + rec.wrap(prefill_attention._ext(), ("prefill_attention",), "prefill_attention") + w = eng.w + states, replies = [], [] + for p in prompts: + st, pending = prefill(w, p, None, limit=4096) + states.append(st) + replies.append(serial_decode(w, st, pending, REPLY, None, stop_eos=False).tokens) + dev = w.norm.device + cases = [] + + def tokens(ids): + return torch.tensor(ids, dtype=torch.int32, device=dev) + + # chains of one stream: the serial reply's first W tokens, each row's draw the next serial token + for width in range(1, 17): + st = clone_state(states[0]) + logits, _ = tree_forward(w, tokens(replies[0][:width]), list(range(-1, width - 1)), st) + cases.append({"kind": "chain", "streams": [{"stream": 0, "tokens": replies[0][:width]}], "rows": rows(logits)}) + # shared forwards: each stream its own chain from its own state, rows in stream order + layouts = [[1, 1], [1] * 4, [1] * 8, [1] * 16, [4, 4, 4, 4], [2, 5, 1, 8], [3] * 5, [16]] + if a.wide: # rounds past 16 rows: the wider matmul tiles (to 32, 64, more) + layouts += [[16, 16], [5, 16, 3], [16] * 4, [9, 16, 2, 16, 7, 16, 1, 5], [12] * 8, [16] * 16] + if a.sweep: # the packed copy's pointer alignments: rows and streams mod 4, 16-row multiples + for n in range(2, 6): + for total in (16 * n, 16 * n - 12, 16 * n - 11, 16 * n - 10, 16 * n - 9): + layouts.append([total // n + (i < total % n) for i in range(n)]) + for layout in layouts: + sts = [clone_state(states[s]) for s in range(len(layout))] + wins = [(replies[s][:n], list(range(-1, n - 1)), sts[s]) for s, n in enumerate(layout)] + logits, record, _, starts = multi_tree_forward(w, wins) + case = {"kind": "shared", "streams": [{"stream": s, "tokens": replies[s][:n]} for s, n in enumerate(layout)], + "rows": rows(logits)} + # each stream keeps a prefix of its rows (as multi._commit names them: window rows), then one more row each + keep = [list(range(max(1, n - 1))) for n in layout] + commit_streams(sts, record, [[starts[s] + r for r in k] for s, k in enumerate(keep)]) + nxt = [([replies[s][len(k)]], [-1], sts[s]) for s, k in enumerate(keep)] + after, _, _, _ = multi_tree_forward(w, nxt) + case["keep"] = [len(k) for k in keep] + case["after"] = rows(after) + cases.append(case) + # trees: each stream's serial reply as the main chain, with other tokens hung beside it + def tree(stream: int, shape: str): + r = replies[stream] + alt = lambda t: (t + 7919) % w.config.vocab # noqa: E731 + if shape == "fork": # 0 r0; 1 r1 (0); 2 alt (0); 3 r2 (1); 4 alt (1); 5 r3 (3); 6 alt (2) + return [r[0], r[1], alt(r[1]), r[2], alt(r[2]), r[3], alt(r[3])], [-1, 0, 0, 1, 1, 3, 2] + if shape == "fan": # the root's six children (r1 first), then r2 under r1 + return [r[0], r[1]] + [alt(r[1] + j) for j in range(5)] + [r[2]], [-1, 0, 0, 0, 0, 0, 0, 1] + raise ValueError(shape) + + tree_cases = [([(0, "fork")], [[0, 1, 3, 5]]), ([(1, "fan")], [[0, 1, 7]]), + ([(2, "fork"), (3, "fork")], [[0, 1, 3, 5], [0, 2, 6]])] + if a.wide: # every stream a tree in one round, 120 rows + tree_cases.append(([(s, "fork" if s % 2 else "fan") for s in range(16)], + [[0, 1, 3, 5] if s % 2 else [0, 1, 7] for s in range(16)])) + for spec, paths in tree_cases: + sts = [clone_state(states[s]) for s, _ in spec] + wins = [(*tree(s, shape), st) for (s, shape), st in zip(spec, sts)] + if len(spec) == 1: + logits, record = tree_forward(w, tokens(wins[0][0]), wins[0][1], sts[0]) + starts = [0, len(wins[0][0])] + else: + logits, record, _, starts = multi_tree_forward(w, [(t, p, st) for t, p, st in wins]) + case = {"kind": "tree", "streams": [{"stream": s, "tokens": t, "parents": p} for (s, _), (t, p, _) in + zip(spec, wins)], "rows": rows(logits), "paths": paths} + nxt = [int(logits[starts[k] + path[-1]].argmax()) for k, path in enumerate(paths)] + commit_streams(sts, record, [[starts[k] + r for r in path] for k, path in enumerate(paths)]) + after, _, _, _ = multi_tree_forward(w, [([t], [-1], st) for t, st in zip(nxt, sts)]) + case["next"] = nxt + case["after"] = rows(after) + cases.append(case) + torch.cuda.synchronize() + (out / "windows.json").write_text(json.dumps({"prompts": prompts, "replies": replies, "cases": cases}) + "\n") + if rec is not None: + rec.dump(out / "launches.json") + print(f"{len(cases)} cases", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 907e013d15d2e5e4c8b9cc946acdcf97e9cb574d Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:57:08 -0500 Subject: [PATCH 04/17] Native image input: images from a request's image parts, prepared before admission; GLM-5.3-Flash reads them on Metal Server (engine-independent): - `Info.vision` is an engine's offer: a `prepare` hook (an image's bytes to its tower's patches, grid, tokens and a content hash, decoded by the platform's own decoder), the image token, the wrapper's tokens, and a request's visual-token budget and image limit. `--vision`, `--vision-max-images` and `--vision-image-tokens` reach native engines. - User messages keep their image_url parts (data URLs) beside their text for the template. Images are counted from those parts, never from text: a marker that a user's words or a tool's output spells is rendered as ordinary text tokens (each quoted marker stands in as a private sentinel while the template renders, then is read without added-token matching), so every image token in the prompt is the template's, one wrapper a part (#511). A prompt that quotes no marker gets exactly the ids it got before. - Each image's placeholder is expanded to its tokens before the window, the chunks and the cache see the prompt; `Request.images` carries the prepared patches and positions, and `Request.cache_key` replaces each image's rows by ids derived from its content, so a kept state of one image never resumes another under the same placeholders. - 0.6.6's limits and refusals: 4 images, 10 MB each and 20 MB a request, 8192 px a side and 16 MP, a single frame, a shared visual-token budget, detail low at 256 tokens; PNG and JPEG (images.py's formats), WebP refused by name until a decoder exists; remote URLs refused. GLM-5.3-Flash on Metal: the image tower (24 pre-norm blocks with 2-D rotary attention, the 2x2 merge and the merger, its projections on gemm_nax), its rows written over the placeholders' embeddings in the prompt pass and one position on for the MTP head; preprocessing as 0.6.6's vision/images.py and mlx-vlm's Glm5NextImageProcessor (EXIF orientation, alpha over white, PIL's 8-bit bicubic resampler). tf-glm-vision compares a reference dump's stages. tools/zig/glm_vision_fixtures.py draws the fixed image set and dumps the Python frontend's tensors; tools/zig/vision_served.py checks a running server. --- build.zig | 3 + docs/api.md | 3 +- docs/vision.md | 20 + tools/zig/glm_vision_fixtures.py | 165 ++++++++ tools/zig/vision_served.py | 173 ++++++++ zig/kernels/metal/glm_vision.metal | 229 +++++++++++ zig/kernels/metal/sources.zig | 2 + zig/src/core/engine_api.zig | 42 ++ zig/src/core/lane_host.zig | 16 +- zig/src/core/lane_host_reuse_test.zig | 88 +++++ zig/src/core/lanes/stream.zig | 7 + zig/src/core/tokenizer/tokenizer.zig | 24 +- zig/src/families/glm/backend.zig | 6 + zig/src/families/glm/checks.zig | 2 +- zig/src/families/glm/engine.zig | 16 +- zig/src/families/glm/forward.zig | 28 +- zig/src/families/glm/glm.zig | 4 + zig/src/families/glm/image.zig | 453 +++++++++++++++++++++ zig/src/families/glm/mtp.zig | 1 + zig/src/families/glm/prompt.zig | 3 +- zig/src/families/glm/slot_images.zig | 37 ++ zig/src/families/glm/slots.zig | 1 + zig/src/families/glm/vision.zig | 541 ++++++++++++++++++++++++++ zig/src/native/glm_host.zig | 16 +- zig/src/native/metal.zig | 10 +- zig/src/server/anthropic.zig | 2 +- zig/src/server/chat.zig | 35 +- zig/src/server/cli.zig | 20 +- zig/src/server/hf_text.zig | 5 + zig/src/server/images.zig | 350 +++++++++++++++++ zig/src/server/messages.zig | 51 ++- zig/src/server/model_text.zig | 7 + zig/src/server/openai.zig | 4 +- zig/src/server/prompt.zig | 21 +- zig/src/server/reply_text.zig | 29 ++ zig/src/server/root.zig | 1 + zig/tests/glm_vision.zig | 148 +++++++ 37 files changed, 2495 insertions(+), 68 deletions(-) create mode 100644 tools/zig/glm_vision_fixtures.py create mode 100644 tools/zig/vision_served.py create mode 100644 zig/kernels/metal/glm_vision.metal create mode 100644 zig/src/families/glm/image.zig create mode 100644 zig/src/families/glm/slot_images.zig create mode 100644 zig/src/families/glm/vision.zig create mode 100644 zig/src/server/images.zig create mode 100644 zig/tests/glm_vision.zig diff --git a/build.zig b/build.zig index 054e688280..b2c9e0d8e4 100644 --- a/build.zig +++ b/build.zig @@ -410,6 +410,7 @@ fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b .{ .name = "tf-grid-sync-bench", .path = "zig/tests/grid_sync_bench.zig", .about = "A GPU-wide barrier in one persistent dispatch against dependent relaunches" }, .{ .name = "tf-weight-read-check", .path = "zig/tests/weight_read_check.zig", .about = "Check native file reads and failed-read cleanup", .c_source = "zig/tests/pread_fault.c" }, .{ .name = "tf-glm-run", .path = "zig/tests/glm_run.zig", .about = "GLM-5.3-Flash greedy replies at each draft depth against depth 0 and reference tokens" }, + .{ .name = "tf-glm-vision", .path = "zig/tests/glm_vision.zig", .about = "GLM-5.3-Flash's image tower on an image or a reference dump's patches, compared with the dump" }, .{ .name = "tf-glm-attn-probe", .path = "zig/tests/glm_attn_probe.zig", .about = "GLM-5.3-Flash's dense latent attention kernels on given inputs (scores, probabilities, outputs)" }, .{ .name = "tf-moe-bench", .path = "zig/tests/moe_bench.zig", .about = "Routed-expert prompt kernels from .metal files on a skewed routing: chained speed, bits against the first" }, .{ .name = "tf-mm-bench", .path = "zig/tests/mm_bench.zig", .about = "Prompt matmul kernels from .metal files: chained speed at one shape, bits against the first, error against fp64" }, @@ -540,6 +541,8 @@ fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: metal.linkFramework("Metal", .{}); metal.linkFramework("Foundation", .{}); metal.linkFramework("IOSurface", .{}); // the Neural Engine's prompt share passes IOSurfaces + metal.linkFramework("ImageIO", .{}); // GLM-5.3-Flash's image input: decoding (families/glm/image.zig) + metal.linkFramework("CoreGraphics", .{}); metal.linkSystemLibrary("objc", .{}); const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = target, .optimize = optimize, .link_libc = true }); const fabric = b.createModule(.{ .root_source_file = b.path("zig/src/fabric/fabric.zig"), .target = target, .optimize = optimize, .link_libc = true }); diff --git a/docs/api.md b/docs/api.md index dc5ff8bb1a..76a950230b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -67,7 +67,8 @@ chat fields that shape the prompt (`tools`, `reasoning_effort`, `chat_template_k `tokens`, and `token_strs` with `return_token_strs: true`. The IDs are the ones the chat route runs for the same request, images expanded. `/detokenize` takes `tokens` and returns `prompt`. With `--vision`, supported Qwen3.5/3.8 dense checkpoints accept `image_url` content parts alongside text in user -messages and in tool results (`role: "tool"`), such as an agent's screenshots. +messages and in tool results (`role: "tool"`), such as an agent's screenshots. The native server does the same for +GLM-5.3-Flash on Metal, with data URLs only ([image input](vision.md#the-native-server)). See [image input](vision.md) for data URLs, public image URLs, limits and cache behavior. Unsupported image input, audio, video and non-text output requests receive HTTP 400. diff --git a/docs/vision.md b/docs/vision.md index 5e6bfa608b..75a37c1c58 100644 --- a/docs/vision.md +++ b/docs/vision.md @@ -129,6 +129,26 @@ This prevents identical image-placeholder token IDs from reusing another image's Multi-turn image conversations work when the request includes the original image content parts, but image-prefix reuse and persisted image KV are not implemented. For Qwen, each image request carries its own multimodal rotary positions and continuation offset, including during concurrent lane rounds. GLM uses its native KDA/NoPE attention state. +## The native server + +`tensorfold-native serve` takes `--vision`, `--vision-max-images` (default 4) and `--vision-image-tokens` (default +4,096) for engines that read images; GLM-5.3-Flash on one Mac reads them so far, and other native engines refuse the +flag at startup. + +- Images arrive as `image_url` data URLs in user messages and tool results. Remote URLs are refused, since + `--vision-urls` isn't on the native server yet. +- PNG and JPEG are decoded by the platform's decoder (ImageIO on macOS). WebP is refused by name until a decoder + exists; other formats are refused. +- The limits and the processing are 0.6.6's: EXIF orientation, alpha composited over white, the GLM5-Next processor's + sizing and PIL's bicubic resampler. Six drawn PNG fixtures give patches bit-equal to 0.6.6 with mlx-vlm + (`tools/zig/glm_vision_fixtures.py`). JPEG patches differ slightly, because ImageIO and libjpeg-turbo decode + differently. +- Images are counted from the request's image parts. A user or tool message whose text spells the model's image + markers (`<|image|>`, `<|begin_of_image|>`, `<|end_of_image|>`) is tokenized as ordinary text, so only the chat + template's own markers, one wrapper for each image part, become image tokens. +- The prompt cache keys each image's placeholder rows by the image's content, so a kept state resumes the same image + and never another one under the same placeholders. Image conversations reuse their history like text ones. + ## Verification Compare image requests with `draft: true` and `draft: false` at identical sampling settings and seed, then compare concurrent requests with their solo results. diff --git a/tools/zig/glm_vision_fixtures.py b/tools/zig/glm_vision_fixtures.py new file mode 100644 index 0000000000..ee17c15eb5 --- /dev/null +++ b/tools/zig/glm_vision_fixtures.py @@ -0,0 +1,165 @@ +"""GLM-5.3-Flash image input against the Python frontend, on a fixed image set (#565's gate). + + python -I tools/zig/glm_vision_fixtures.py --model DIR --out DIR [--tower zig-out/bin/tf-glm-vision] + +Draws the image set (each case a preprocessing path: padding only, an antialiased downscale, an upscale, alpha over +white, a palette with a transparent entry, gray with alpha, EXIF orientation, baseline JPEG), then for each image +writes what TensorFold 0.6.6's --vision gives (vision/images.py's decode: EXIF orientation, alpha over white; then +mlx-vlm's Glm5NextImageProcessor and tower, the code 0.6.6 serves): + patches.f32 (grid_h*grid_w, 1176) normalized patches, temporal frames duplicated + embed.f32 / block0.f32 / blocks.f32 / features.f32 the tower's stages, features the rows that replace <|image|> +and meta.json. With --tower it then runs tf-glm-vision on each image: the native patches compared value by value, +the native tower's rows by cosine (bf16 against bf16). + +Needs TensorFold 0.6.6 with its vision extra (mlx-vlm 0.7.x) and Pillow. Loads only model.visual.* (about 1 GB). +""" + +from __future__ import annotations + +import argparse +import io +import json +import re +import subprocess +import sys +from pathlib import Path + +import mlx.core as mx +import numpy as np +from PIL import Image, ImageDraw + + +def draw_shapes(size: tuple[int, int]) -> Image.Image: + w, h = size + im = Image.new("RGB", size, (245, 240, 230)) + d = ImageDraw.Draw(im) + d.ellipse((w * 0.08, h * 0.25, w * 0.42, h * 0.7), fill=(210, 40, 40)) + d.rectangle((w * 0.55, h * 0.25, w * 0.9, h * 0.7), fill=(40, 70, 200)) + for x in range(int(w * 0.1), int(w * 0.9), 6): + d.line((x, h * 0.8, x, h * 0.92), fill=(20, 20, 20), width=2) + d.text((w * 0.4, h * 0.06), "GLM 7", fill=(0, 0, 0)) + return im + + +def fixtures(folder: Path) -> list[Path]: + folder.mkdir(parents=True, exist_ok=True) + out = [] + + def save(name: str, im: Image.Image, **kw) -> None: + p = folder / name + im.save(p, **kw) + out.append(p) + + save("shapes.png", draw_shapes((517, 389))) # padding only + big = draw_shapes((2000, 1500)) + px = big.load() + for y in range(0, 1500, 3): # fine detail for the antialias + for x in range(0, 2000, 7): + px[x, y] = ((x * 3) % 256, (y * 5) % 256, (x + y) % 256) + save("large.png", big) # antialiased downscale + save("tiny.png", draw_shapes((20, 15))) # upscale to the token floor + logo = Image.new("RGBA", (96, 96), (0, 0, 0, 0)) + d = ImageDraw.Draw(logo) + d.rounded_rectangle((4, 4, 92, 92), 16, fill=(30, 30, 40, 255)) + d.polygon([(26, 28), (70, 28), (30, 68), (70, 68), (70, 74), (24, 74), (64, 34), (26, 34)], fill=(255, 255, 255, 230)) + save("logo.png", logo) # RGBA upscale, alpha over white + pal = draw_shapes((517, 389)).quantize(32) + pal.info["transparency"] = 0 + save("palette.png", pal, transparency=0) # palette, a transparent entry + la = Image.new("LA", (240, 180), (128, 0)) + d = ImageDraw.Draw(la) + for r in range(80, 0, -8): + d.ellipse((120 - r, 90 - r, 120 + r, 90 + r), fill=(255 - 3 * r, 255 - 2 * r)) + save("gray-alpha.png", la) # gray with alpha + rot = draw_shapes((300, 200)) + exif = Image.Exif() + exif[0x0112] = 6 # rotate 90 degrees clockwise + save("rotated.jpg", rot, quality=90, exif=exif.tobytes()) # EXIF orientation + save("shapes.jpg", draw_shapes((517, 389)), quality=85) # baseline JPEG + return out + + +def reference(model: Path, image_path: Path, out: Path, tower, processor, max_tokens: int) -> dict: + from tensorfold.vision.images import DEFAULT_LIMITS, _decode + + out.mkdir(parents=True, exist_ok=True) + image = _decode(image_path.read_bytes(), "auto", DEFAULT_LIMITS, DEFAULT_LIMITS.max_total_pixels).to_pil() + done = processor([image], return_tensors="np", min_image_tokens=min(16, max_tokens), max_image_tokens=max_tokens) + patches = np.asarray(done["pixel_values"], dtype=np.float32) + grid = np.asarray(done["image_grid_thw"], dtype=np.int64) + dtype = tower.patch_embed.proj.weight.dtype + x = mx.array(patches).astype(dtype) + g = mx.array(grid, dtype=mx.int32) + h = tower.patch_embed(x) + embed = h + pos = tower._rotary_embeddings(g) + cu = mx.array([0, int(h.shape[0])]) + block0 = None + for i, block in enumerate(tower.blocks): + h = block(h, cu, pos) + if i == 0: + block0 = h + blocks = h + features = tower(x, g) + mx.eval(embed, block0, blocks, features) + for name, a in (("patches", patches), ("embed", embed), ("block0", block0), ("blocks", blocks), ("features", features)): + np.asarray(a.astype(mx.float32) if isinstance(a, mx.array) else a, dtype=np.float32).tofile(out / f"{name}.f32") + meta = {"image": str(image_path), "size": list(image.size), "mode": Image.open(image_path).mode, "grid_thw": grid[0].tolist(), + "max_tokens": max_tokens, "tokens": int(features.shape[0]), "patch_width": int(patches.shape[1]), "dtype": str(dtype)} + (out / "meta.json").write_text(json.dumps(meta, indent=1) + "\n") + return meta + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--model", required=True, help="the GLM-5.3-Flash checkpoint folder") + ap.add_argument("--out", required=True, help="where the images and their references go") + ap.add_argument("--max-tokens", type=int, default=4096, help="the visual-token budget an image is sized to") + ap.add_argument("--tower", help="tf-glm-vision: also compare the native patches and tower with each reference") + args = ap.parse_args() + + from mlx_vlm.models.glm5_next.config import VisionConfig + from mlx_vlm.models.glm5_next.processing import Glm5NextImageProcessor + from mlx_vlm.models.glm5_next.vision import VisionModel + + model, out = Path(args.model), Path(args.out) + config = json.loads((model / "config.json").read_text()) + proc_cfg = json.loads((model / "processor_config.json").read_text())["image_processor"] + proc_cfg.pop("image_processor_type", None) + processor = Glm5NextImageProcessor(**proc_cfg) + tower = VisionModel(VisionConfig.from_dict(config["vision_config"])) + index = json.loads((model / "model.safetensors.index.json").read_text())["weight_map"] + weights = {} + for shard in sorted({f for k, f in index.items() if k.startswith("model.visual.")}): + for k, v in mx.load(str(model / shard)).items(): + if k.startswith("model.visual."): + weights[k[len("model.visual."):]] = v + tower.load_weights(list(tower.sanitize(weights).items()), strict=True) + mx.eval(tower.parameters()) + + failures = 0 + for image in fixtures(out / "images"): + ref = out / image.name.replace(".", "-") + meta = reference(model, image, ref, tower, processor, args.max_tokens) + line = f"{image.name:15} {meta['size'][0]}x{meta['size'][1]} {meta['mode']:5} grid {meta['grid_thw']} {meta['tokens']} tokens" + if args.tower: + run = subprocess.run([args.tower, str(model), str(ref), "features", str(image)], capture_output=True, text=True) + text = run.stdout + run.stderr + p = re.search(r"patches: (\d+) of (\d+) values differ", text) + c = re.search(r"cosine mean ([0-9.]+) worst ([0-9.]+)", text) + if run.returncode != 0 or not p or not c: + failures += 1 + line += f" FAIL: {text.strip().splitlines()[-1] if text.strip() else run.returncode}" + else: + differ = int(p.group(1)) + exact = differ == 0 + # PNG patches must be bit-exact; JPEG patches differ by decoder (ImageIO against libjpeg-turbo) + failures += (not exact) and image.suffix == ".png" + line += f" patches {'equal' if exact else f'{differ} of {p.group(2)} differ'}, rows' cosine {c.group(1)} (worst {c.group(2)})" + print(line) + print("PASS" if failures == 0 else f"FAIL: {failures}") + return 0 if failures == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/zig/vision_served.py b/tools/zig/vision_served.py new file mode 100644 index 0000000000..49bd56bca6 --- /dev/null +++ b/tools/zig/vision_served.py @@ -0,0 +1,173 @@ +"""Image input served end to end on a running ``tensorfold-native --vision`` (#565's served checks). + + python tools/zig/vision_served.py --url http://127.0.0.1:8000 --images DIR + +DIR holds PNG and JPEG test images. Checks: an image request answers, and text or a tool result that quotes the +model's image marker beside a real image is ordinary text (images come from the request's image parts, #511); drafted +equals ``"draft": false`` and concurrent equals alone with images; an image conversation's next turn resumes past +its image, and another image under the same placeholders resumes none of the first one's rows; and the refusals (WebP by name, other formats, an image outside a +user or tool message, too many images, remote URLs, bad data URLs, a bad detail). +""" + +from __future__ import annotations + +import argparse +import base64 +import concurrent.futures as cf +import json +import sys +import urllib.error +import urllib.request +from pathlib import Path + + +def post(url: str, body: dict) -> tuple[int, dict]: + req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=1800) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + return e.code, json.loads(e.read() or b"{}") + + +def data_url(raw: bytes, mime: str) -> str: + return f"data:{mime};base64,{base64.b64encode(raw).decode()}" + + +def image_part(url: str, detail: str | None = None) -> dict: + inner = {"url": url} + if detail: + inner["detail"] = detail + return {"type": "image_url", "image_url": inner} + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--url", default="http://127.0.0.1:8000") + ap.add_argument("--images", required=True) + ap.add_argument("--tokens", type=int, default=48) + ap.add_argument("--fresh-url", help="the same model served with --prompt-cache-gib 0: the cache check's reference reply") + args = ap.parse_args() + with urllib.request.urlopen(args.url + "/v1/models") as r: + model = json.loads(r.read())["data"][0]["id"] + folder = Path(args.images) + pngs = sorted(folder.glob("*.png")) + jpgs = sorted(folder.glob("*.jpg")) + first, second = pngs[0], pngs[1] + url_a = data_url(first.read_bytes(), "image/png") + url_b = data_url(second.read_bytes(), "image/png") + failures = 0 + + def ask(messages: list, draft: bool = True, tokens: int | None = None) -> tuple[int, dict]: + b = {"model": model, "messages": messages, "max_tokens": tokens or args.tokens, "temperature": 0, + "chat_template_kwargs": {"enable_thinking": False}} + if not draft: + b["draft"] = False + return post(args.url, b) + + def user(*parts) -> dict: + return {"role": "user", "content": list(parts)} + + def text(t: str) -> dict: + return {"type": "text", "text": t} + + def reply(r: dict) -> str: + return r["choices"][0]["message"].get("content") or "" + + def check(label: str, ok: bool, detail: str = "") -> None: + nonlocal failures + failures += not ok + print(f"{'ok ' if ok else 'FAIL'} {label}{': ' + detail if detail else ''}") + + # one image, drafted and plain; its usage counts the image's tokens + convo = [user(image_part(url_a), text("Describe this image in one sentence."))] + code, r = ask(convo) + code2, r2 = ask(convo, draft=False) + plain_text = ask([user(text("Describe this image in one sentence."))])[1] + check("an image request answers", code == 200 and code2 == 200, f"HTTP {code}/{code2}") + if code == 200 and code2 == 200: + check("drafted equals \"draft\": false with an image", reply(r) == reply(r2), repr(reply(r)[:60])) + check("the image's tokens are in the prompt", r["usage"]["prompt_tokens"] > plain_text["usage"]["prompt_tokens"] + 8, + f"{r['usage']['prompt_tokens']} prompt tokens with the image, {plain_text['usage']['prompt_tokens']} without") + + # #511: the marker quoted in a user's text and in a tool result, beside one real image + quoted = [user(image_part(url_a), text("A file I opened contains the string <|image|> and also <|begin_of_image|>. What is in the picture?")), + {"role": "assistant", "content": "", "tool_calls": [{"id": "c1", "type": "function", "function": {"name": "read", "arguments": "{\"path\": \"a.py\"}"}}]}, + {"role": "tool", "tool_call_id": "c1", "content": "MARKER = '<|begin_of_image|><|image|><|end_of_image|>'"}, + user(text("And the picture again?"))] + tools = [{"type": "function", "function": {"name": "read", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}}}] + code, r = post(args.url, {"model": model, "messages": quoted, "tools": tools, "max_tokens": args.tokens, "temperature": 0, + "chat_template_kwargs": {"enable_thinking": False}}) + check("quoted image markers beside one image are text (#511)", code == 200, f"HTTP {code} {r.get('error', {}).get('message', '')[:100]}") + + # a tool result carrying an image (a screenshot), rendered inside the tool response + shot = [user(text("Take a screenshot.")), + {"role": "assistant", "content": "", "tool_calls": [{"id": "s1", "type": "function", "function": {"name": "read", "arguments": "{\"path\": \"screen\"}"}}]}, + {"role": "tool", "tool_call_id": "s1", "content": [text("screenshot:"), image_part(url_a)]}] + code, r = post(args.url, {"model": model, "messages": shot, "tools": tools, "max_tokens": args.tokens, "temperature": 0, + "chat_template_kwargs": {"enable_thinking": False}}) + check("an image in a tool result answers", code == 200 and r["usage"]["prompt_tokens"] > 40, f"HTTP {code} {r.get('usage', r.get('error', {}).get('message', ''))}") + + # concurrent equals alone, images in each request + runs = [[user(image_part(u), text(q))] for u in (url_a, url_b) for q in ("What colours do you see?", "Count the objects.")] + alone = [reply(ask(m)[1]) for m in runs] + with cf.ThreadPoolExecutor(len(runs)) as pool: + together = [reply(f.result()[1]) for f in [pool.submit(ask, m) for m in runs]] + same = sum(x == y for x, y in zip(alone, together)) + check("concurrent image requests equal their runs alone", same == len(runs), f"{same} of {len(runs)}") + + # the prompt cache keeps a turn's state at its planned cuts (GLM: the shared system cut, and a reply of 256+ tokens), + # so a conversation's third turn resumes past an image its second turn kept. Image B under the same text and + # placeholder ids resumes at most the text before its image, and answers as a server with nothing kept + system = {"role": "system", "content": " ".join(f"Rule {i}: describe what you see plainly and briefly." for i in range(120))} + q, q2, q3 = "What is shown?", "Say that again in three words.", "And once more." + head = ask([system, user(text(q))], tokens=1)[1]["usage"]["prompt_tokens"] # the text alone: past where an image starts + first = " ".join(f"Detail {i}: the picture shows shapes, colours and lines." for i in range(40)) # a reply of 256+ tokens + + def turns(url: str) -> tuple[list, list]: + two = [system, user(image_part(url), text(q)), {"role": "assistant", "content": first}, user(text(q2))] + return two, two + [{"role": "assistant", "content": "Three words here."}, user(text(q3))] + + two_a, three_a = turns(url_a) + two_b, three_b = turns(url_b) + if args.fresh_url: # B's reply with nothing kept + rf = post(args.fresh_url, {"model": model, "messages": three_b, "max_tokens": 24, "temperature": 0, "chat_template_kwargs": {"enable_thinking": False}})[1] + ask(two_a, tokens=8) # keeps A's state at the long reply's start, past its image + code, ra = ask(three_a, tokens=24) + cached_a = ra.get("usage", {}).get("prompt_tokens_details", {}).get("cached_tokens", 0) if code == 200 else -1 + check("an image conversation's later turn resumes past its image", code == 200 and cached_a > head, f"cached {cached_a} of {ra.get('usage', {}).get('prompt_tokens')}; the text alone is {head}") + code, rb = ask(three_b, tokens=24) + cached_b = rb.get("usage", {}).get("prompt_tokens_details", {}).get("cached_tokens", 0) if code == 200 else -1 + check("another image under the same placeholders resumes only the text before it", code == 200 and cached_b < head, + f"cached {cached_b} of {rb.get('usage', {}).get('prompt_tokens')}") + if args.fresh_url: + check("and answers as a server with nothing kept", reply(rf) == reply(rb), repr(reply(rb)[:60])) + + # refusals, before any token + webp = b"RIFF\x24\x00\x00\x00WEBPVP8 \x18\x00\x00\x00" + bytes(24) + gif = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00!\xf9\x04\x00\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;" + refusals = [ + ("WebP, by name", [user(image_part(data_url(webp, "image/webp")), text("hi"))], "WebP"), + ("GIF", [user(image_part(data_url(gif, "image/gif")), text("hi"))], "not PNG or JPEG"), + ("an image in an assistant message", [user(text("hi")), {"role": "assistant", "content": [image_part(url_a)]}, user(text("ok"))], "user and tool messages only"), + ("too many images", [user(*[image_part(url_a)] * 5, text("hi"))], "at most"), + ("a remote URL", [user(image_part("https://example.com/cat.png"), text("hi"))], "data: URL"), + ("bad base64", [user(image_part("data:image/png;base64,@@@@"), text("hi"))], "encoding"), + ("a bad detail", [user(image_part(url_a, "medium"), text("hi"))], "detail"), + ("bytes that decode as nothing", [user(image_part(data_url(b"\x89PNG\r\n\x1a\n" + bytes(32), "image/png")), text("hi"))], "could not be decoded"), + ] + for label, messages, words in refusals: + code, r = ask(messages) + message = r.get("error", {}).get("message", json.dumps(r)) + check(f"refused {label}", code == 400 and words in message, f"HTTP {code} {message[:100]!r}") + if jpgs: + code, r = ask([user(image_part(data_url(jpgs[0].read_bytes(), "image/jpeg")), text("Describe it."))]) + check("a JPEG answers", code == 200, f"HTTP {code}") + code, r = ask([user(image_part(url_a, "low"), text("Describe it."))]) + check("detail low answers", code == 200, f"HTTP {code}") + print("PASS" if failures == 0 else f"FAIL: {failures}") + return 0 if failures == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/zig/kernels/metal/glm_vision.metal b/zig/kernels/metal/glm_vision.metal new file mode 100644 index 0000000000..c0fcc513e4 --- /dev/null +++ b/zig/kernels/metal/glm_vision.metal @@ -0,0 +1,229 @@ +// GLM-5.3-Flash's image tower (GLM5-Next vision: 24 pre-norm blocks of 1024, 16 heads of 64, 2-D rotary, a 2x2 merge +// and a SwiGLU merger to the language model's 4096). Compiled after prefill/gemm_nax.metal, whose tfp::gemm_nax runs +// every projection; the rest is MLX's per-op arithmetic as mlx-vlm's glm5_next/vision.py runs it in bf16. + +// ---- the projections and attention products: tfp::gemm_nax (bm64 bn128 bk256 wm2 wn4) by operand layout ---- +#define GLMV_GEMM(NAME, T, TA, TB, AM, AN) \ + [[max_total_threads_per_threadgroup(256)]] [[kernel]] void NAME( \ + const device T* A [[buffer(0)]], const device T* B [[buffer(1)]], const device int32_t* P [[buffer(2)]], \ + device T* D [[buffer(3)]], uint sg [[simdgroup_index_in_threadgroup]], \ + uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { \ + tfp::gemm_nax(A, B, D, P, tg, sg, lane); \ + } +// x [M, K] w^T: every linear layer (bf16 in and out, fp32 sums) +GLMV_GEMM(glmv_gemm_bf16_nt_00, bfloat16_t, false, true, false, false) +GLMV_GEMM(glmv_gemm_bf16_nt_01, bfloat16_t, false, true, false, true) +GLMV_GEMM(glmv_gemm_bf16_nt_10, bfloat16_t, false, true, true, false) +GLMV_GEMM(glmv_gemm_bf16_nt_11, bfloat16_t, false, true, true, true) +// q k^T per head in fp32 (the scores MLX's attention keeps in fp32) +GLMV_GEMM(glmv_gemm_f32_nt_00, float, false, true, false, false) +GLMV_GEMM(glmv_gemm_f32_nt_01, float, false, true, false, true) +GLMV_GEMM(glmv_gemm_f32_nt_10, float, false, true, true, false) +GLMV_GEMM(glmv_gemm_f32_nt_11, float, false, true, true, true) +// p v per head in fp32 +GLMV_GEMM(glmv_gemm_f32_nn_00, float, false, false, false, false) +GLMV_GEMM(glmv_gemm_f32_nn_01, float, false, false, false, true) +GLMV_GEMM(glmv_gemm_f32_nn_10, float, false, false, true, false) +GLMV_GEMM(glmv_gemm_f32_nn_11, float, false, false, true, true) + +struct GlmvRows { + uint rows; + uint width; + float eps; +}; + +inline float glmv_bf(float x) { return float(bfloat(x)); } + +// One threadgroup's sum of every thread's `v` (at most 1024 threads), returned to all of them. +inline float glmv_group_sum(float v, threadgroup float* part, uint t, uint n, uint lane, uint sg) { + v = simd_sum(v); + if (lane == 0) part[sg] = v; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + float s = lane < (n + 31) / 32 ? part[lane] : 0.0f; + s = simd_sum(s); + if (lane == 0) part[32] = s; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const float out = part[32]; + threadgroup_barrier(mem_flags::mem_threadgroup); + return out; +} + +// y[r, c] = y + b[c] (a linear layer's bias, added after its product as nn.Linear's bf16 add rounds it) +[[kernel]] void glmv_bias(device bfloat* y [[buffer(0)]], const device bfloat* b [[buffer(1)]], + constant uint& width [[buffer(2)]], uint2 at [[thread_position_in_grid]]) { + const ulong i = ulong(at.y) * width + at.x; + y[i] = bfloat(float(y[i]) + float(b[at.x])); +} + +// x += y (a block's residual) +[[kernel]] void glmv_add(device bfloat* x [[buffer(0)]], const device bfloat* y [[buffer(1)]], + uint i [[thread_position_in_grid]]) { + x[i] = bfloat(float(x[i]) + float(y[i])); +} + +// mx.fast.rms_norm, one threadgroup a row: w * bf16(x * rsqrt(mean(x^2) + eps)) +[[kernel]] void glmv_rms(const device bfloat* x [[buffer(0)]], const device bfloat* w [[buffer(1)]], + device bfloat* y [[buffer(2)]], constant GlmvRows& p [[buffer(3)]], + uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]], + uint n [[threads_per_threadgroup]], uint lane [[thread_index_in_simdgroup]], + uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[33]; + const device bfloat* xr = x + ulong(row) * p.width; + device bfloat* yr = y + ulong(row) * p.width; + float s = 0.0f; + for (uint i = t; i < p.width; i += n) { + const float v = float(xr[i]); + s += v * v; + } + s = glmv_group_sum(s, part, t, n, lane, sg); + const float inv = metal::precise::rsqrt(s / float(p.width) + p.eps); + for (uint i = t; i < p.width; i += n) yr[i] = bfloat(float(w[i]) * glmv_bf(float(xr[i]) * inv)); +} + +// mx.fast.layer_norm with weight and bias, one threadgroup a row: w * bf16((x - mean) * rsqrt(var + eps)) + b +[[kernel]] void glmv_layer_norm(const device bfloat* x [[buffer(0)]], const device bfloat* w [[buffer(1)]], + const device bfloat* b [[buffer(2)]], device bfloat* y [[buffer(3)]], + constant GlmvRows& p [[buffer(4)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_position_in_threadgroup]], uint n [[threads_per_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[33]; + const device bfloat* xr = x + ulong(row) * p.width; + device bfloat* yr = y + ulong(row) * p.width; + float s = 0.0f; + for (uint i = t; i < p.width; i += n) s += float(xr[i]); + const float mean = glmv_group_sum(s, part, t, n, lane, sg) / float(p.width); + float v = 0.0f; + for (uint i = t; i < p.width; i += n) { + const float d = float(xr[i]) - mean; + v += d * d; + } + const float inv = metal::precise::rsqrt(glmv_group_sum(v, part, t, n, lane, sg) / float(p.width) + p.eps); + for (uint i = t; i < p.width; i += n) { + yr[i] = bfloat(glmv_bf(float(w[i]) * glmv_bf((float(xr[i]) - mean) * inv)) + float(b[i])); + } +} + +struct GlmvQkv { + uint L; // rows (patches) of this image + float eps; // the q and k norms' +}; + +// One simdgroup per (row, head, q|k|v) of qkv [L, 3, 16, 64]: q and k RMS-normed, rotated by the row's 2-D angles +// (cos and sin [L, 64]: the height's 16 frequencies, then the width's, twice), and written head-major in fp32 +// ([16, L, 64], each value a bf16 as MLX hands its attention); v as stored. +[[kernel]] void glmv_qkv(const device bfloat* qkv [[buffer(0)]], const device bfloat* qn [[buffer(1)]], + const device bfloat* kn [[buffer(2)]], const device float* cs [[buffer(3)]], + const device float* sn [[buffer(4)]], device float* Q [[buffer(5)]], + device float* K [[buffer(6)]], device float* V [[buffer(7)]], + constant GlmvQkv& p [[buffer(8)]], uint g [[threadgroup_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { + const uint which = g % 3, h = (g / 3) % 16, r = g / 48; + const device bfloat* src = qkv + ulong(r) * 3072 + which * 1024 + h * 64; + const ulong out = (ulong(h) * p.L + r) * 64; + const float a = float(src[lane]), b = float(src[lane + 32]); + if (which == 2) { + V[out + lane] = a; + V[out + lane + 32] = b; + return; + } + const device bfloat* w = which == 0 ? qn : kn; + const float inv = metal::precise::rsqrt(simd_sum(a * a + b * b) / 64.0f + p.eps); + const float na = glmv_bf(float(w[lane]) * glmv_bf(a * inv)); + const float nb = glmv_bf(float(w[lane + 32]) * glmv_bf(b * inv)); + const device float* c = cs + ulong(r) * 64; + const device float* s = sn + ulong(r) * 64; + device float* dst = which == 0 ? Q : K; + dst[out + lane] = glmv_bf(na * c[lane] - nb * s[lane]); + dst[out + lane + 32] = glmv_bf(nb * c[lane + 32] + na * s[lane + 32]); +} + +// Each row of S [rows, n] (fp32 scores) as softmax(scale * s), in place; one threadgroup a row. +[[kernel]] void glmv_softmax(device float* S [[buffer(0)]], constant uint& n [[buffer(1)]], + constant float& scale [[buffer(2)]], uint row [[threadgroup_position_in_grid]], + uint t [[thread_position_in_threadgroup]], uint tn [[threads_per_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float part[33]; + device float* s = S + ulong(row) * n; + float m = -INFINITY; + for (uint i = t; i < n; i += tn) m = max(m, s[i] * scale); + m = simd_max(m); + if (lane == 0) part[sg] = m; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (sg == 0) { + float v = lane < (tn + 31) / 32 ? part[lane] : -INFINITY; + v = simd_max(v); + if (lane == 0) part[32] = v; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + m = part[32]; + threadgroup_barrier(mem_flags::mem_threadgroup); + float z = 0.0f; + for (uint i = t; i < n; i += tn) { + const float e = metal::precise::exp(s[i] * scale - m); + s[i] = e; + z += e; + } + const float inv = 1.0f / glmv_group_sum(z, part, t, tn, lane, sg); + for (uint i = t; i < n; i += tn) s[i] *= inv; +} + +// O [16, rows, 64] (fp32, one chunk's attention) into rows [r0, r0 + rows) of out [L, 1024] (bf16, heads side by side) +[[kernel]] void glmv_heads(const device float* O [[buffer(0)]], device bfloat* out [[buffer(1)]], + constant uint2& p [[buffer(2)]], uint2 at [[thread_position_in_grid]]) { + const uint rows = p.x, r0 = p.y, h = at.x / 64, d = at.x % 64, r = at.y; + out[ulong(r0 + r) * 1024 + at.x] = bfloat(O[(ulong(h) * rows + r) * 64 + d]); +} + +// The vision MLP's and merger's gate: silu(min(g, limit)) * clip(u, -limit, limit), each op rounded as MLX does. +// gu: g then u, `width` each, a row at a time (stride 2 * width); act [rows, width]. +[[kernel]] void glmv_swiglu(const device bfloat* g [[buffer(0)]], const device bfloat* u [[buffer(1)]], + device bfloat* act [[buffer(2)]], constant float& limit [[buffer(3)]], + uint i [[thread_position_in_grid]]) { + const float gate = glmv_bf(min(float(g[i]), limit)); + const float up = glmv_bf(clamp(float(u[i]), -limit, limit)); + const float sig = glmv_bf(1.0f / (1.0f + metal::precise::exp(-gate))); + act[i] = bfloat(glmv_bf(gate * sig) * up); +} + +// erf to fp32 precision (W. J. Cody's rational approximations, as libm's erff). +inline float glmv_erf(float x) { + const float ax = fabs(x); + if (ax < 0.84375f) { + const float z = x * x; + const float r = 1.28379167e-01f + z * (-3.25042108e-01f + z * (-2.84817495e-02f + z * (-5.77027029e-03f + z * -2.37630166e-05f))); + const float s = 1.0f + z * (3.97917233e-01f + z * (6.50222499e-02f + z * (5.08130628e-03f + z * (1.32494738e-04f + z * -3.96022827e-06f)))); + return x + x * (r / s); + } + if (ax < 1.25f) { + const float s = ax - 1.0f; + const float P = -2.36211857e-03f + s * (4.14856106e-01f + s * (-3.72207481e-01f + s * (3.18346620e-01f + s * (-1.10894694e-01f + s * (3.54783031e-02f + s * -2.16637559e-03f))))); + const float Q = 1.0f + s * (1.06420882e-01f + s * (5.40397942e-01f + s * (7.18286547e-02f + s * (1.26171216e-01f + s * (1.36370836e-02f + s * 1.19844998e-02f))))); + const float e = 8.45062911e-01f + P / Q; + return x >= 0 ? e : -e; + } + if (ax >= 6.0f) return x >= 0 ? 1.0f : -1.0f; + const float s = 1.0f / (ax * ax); + float R, S; + if (ax < 1.0f / 0.35f) { + R = -9.86494403e-03f + s * (-6.93858570e-01f + s * (-1.05586262e+01f + s * (-6.23753357e+01f + s * (-1.62396660e+02f + s * (-1.84605087e+02f + s * (-8.12874374e+01f + s * -9.81432934e+00f)))))); + S = 1.0f + s * (1.96512714e+01f + s * (1.37657754e+02f + s * (4.34565887e+02f + s * (6.45387268e+02f + s * (4.29008148e+02f + s * (1.08635002e+02f + s * (6.57024977e+00f + s * -6.04244141e-02f))))))); + } else { + R = -9.86494310e-03f + s * (-7.99283242e-01f + s * (-1.77579556e+01f + s * (-1.60636383e+02f + s * (-6.37566467e+02f + s * (-1.02509509e+03f + s * -4.83519196e+02f))))); + S = 1.0f + s * (3.03380604e+01f + s * (3.25792511e+02f + s * (1.53672961e+03f + s * (3.19985820e+03f + s * (2.55305029e+03f + s * (4.74528534e+02f + s * -2.24409515e+01f)))))); + } + const float zh = as_type(as_type(ax) & 0xfffff000u); + const float r = metal::precise::exp(-zh * zh - 0.5625f) * metal::precise::exp((zh - ax) * (zh + ax) + R / S); + const float e = 1.0f - r / ax; + return x >= 0 ? e : -e; +} + +// nn.gelu (exact): x * (1 + erf(x / sqrt(2))) / 2, each op rounded to bf16 as the compiled MLX graph does +[[kernel]] void glmv_gelu(device bfloat* x [[buffer(0)]], uint i [[thread_position_in_grid]]) { + const float v = float(x[i]); + const float t = glmv_bf(v / 1.41421356237309504880f); + const float e = glmv_bf(glmv_erf(t)); + const float w = glmv_bf(v * glmv_bf(1.0f + e)); + x[i] = bfloat(w / 2.0f); +} diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index d5fdc24b18..87da9a439a 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -71,6 +71,8 @@ pub const glm = @import("glm/kernels.zig"); pub const glm_glue = @embedFile("glm_glue.metal"); /// GLM-5.3-Flash's latent attention for rows that read every key: 64 heads as one matrix on the tensor units. pub const glm_attn = @embedFile("glm_attn.metal"); +/// GLM-5.3-Flash's image tower: the prefill GEMM template's projections and attention products, then its own steps. +pub const glm_vision = @embedFile("prefill/gemm_nax.metal") ++ @embedFile("glm_vision.metal"); /// A prompt chunk's KDA layer in three passes, appended to the generated kda_rows source (its helpers). pub const glm_kda_prompt = @embedFile("glm_kda_prompt.metal"); /// GLM-5.3-Flash speed-up mode's exchange kernels (families/glm/ep.zig). diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index f72c13b227..cbacca9162 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -9,6 +9,9 @@ pub const Id = u64; /// One request's sampling (Python's exact_sampling.Sampling); a request without one decodes greedily. pub const Sampling = lanes.Sampling; +/// One image of a request (``Request.images``): the tower's input and the placeholder rows its output replaces. +pub const Image = lanes.stream.Image; + /// A prompt's reproducible seed (``seed_for``), for requests that name none. pub const seedFor = lanes.sampling.seedFor; @@ -82,8 +85,43 @@ pub const Request = struct { decide: ?u32 = null, /// Logprob rows for each reply token with this many best tokens (0..20), when ``Info.logprobs``; null: none. logprobs: ?u8 = null, + /// Images whose rows replace placeholder tokens of ``prompt``, in order; only an engine whose ``Info.vision`` is set. + images: []const Image = &.{}, + /// The prompt as the prompt cache matches it (each image's placeholders by its content); empty: ``prompt``. + cache_key: []const u32 = &.{}, + + /// The prompt as the prompt cache matches it: an image request's placeholders stand for their images. + pub fn cacheKey(r: *const Request) []const u32 { + return if (r.cache_key.len > 0) r.cache_key else r.prompt; + } + + /// The decoded prompt rows, for a backend that keeps their bits (``decoded_rows``); otherwise none. + pub fn cacheSpans(r: *const Request, decoded_rows: bool) []const [2]u32 { + return if (decoded_rows) r.decode_spans else &.{}; + } }; +/// An image prepared for the engine's tower (``Vision.prepare``): patches, patch grid, tokens and a content hash. +pub const PreparedImage = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 }; + +/// Image input an engine serves (``Info.vision``): how the server turns an image's bytes into tower input and what +/// a request may hold. +pub const Vision = struct { + ctx: *anyopaque, + /// The image's bytes (any format the platform decodes) at most ``max_tokens`` tokens; allocated in ``a``. + prepare: *const fn (ctx: *anyopaque, a: Allocator, bytes: []const u8, max_tokens: u32) anyerror!PreparedImage, + /// The token the chat template writes once per image, expanded to the image's tokens. + image_token: u32, + /// The tokens the template wraps an image in (the image token among them): text that spells one stays text. + markers: []const u32 = &.{}, + /// Image tokens one request may hold in all, and images. + image_tokens: u32, + max_images: u32, +}; + +/// --vision: image input's limits (``Open.vision``). +pub const VisionOpen = struct { image_tokens: u32 = 4096, max_images: u32 = 4 }; + pub const Reason = enum { stop, length, cancelled, failed }; /// What a finished reply's rounds did, for its runtime fields and /metrics. @@ -148,6 +186,8 @@ pub const Info = struct { plain_only: bool = false, /// The immutable retained-prefix plan applied at startup, not a process memory limit or current cache occupancy. prompt_cache_plan: ?PromptCachePlan = null, + /// Image input (--vision); null: text only. + vision: ?Vision = null, /// The engine decodes greedily only: the server refuses a request with a temperature before admitting it. greedy_only: bool = false, /// Whether a request's caches fit beside the running streams' now (null: a free lane does); else it waits in order. @@ -213,6 +253,8 @@ pub const Open = struct { master_port: u16 = 29551, /// --policy: the engine's policy as `key=value,...`; empty: its defaults. policy: []const u8 = "", + /// --vision: load the checkpoint's image tower (null: text only; an engine without one refuses). + vision: ?VisionOpen = null, }; /// An opened engine; ``close`` stops its thread and frees its backend. diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index 09ff0fa2de..e8d5c5f8a0 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -71,7 +71,7 @@ pub const LaneHost = struct { fn kept(ptr: *anyopaque, s: *lanes.Stream, at: u32) void { const job: *Job = @ptrCast(@alignCast(ptr)); job.reported(); // before a keep can evict the entry the pass restored - if (job.host.cache) |store| _ = store.keep(job.request.prompt, at, s, job.request.chunks, job.host.spans(job.request)); + if (job.host.cache) |store| _ = store.keep(job.request.cacheKey(), at, s, job.request.chunks, job.request.cacheSpans(job.host.decoded_rows)); } /// Report a restored prefix or its failed copy; an untouched prefix remains kept. @@ -81,7 +81,7 @@ pub const LaneHost = struct { const store = job.host.cache orelse return; if (!job.started) return; job.stream.reuse.saved = null; // the backend restores before its first chunk; a later keep may free it - if (job.stream.reuse_failed) store.resumed(e, job.request.prompt, false) else if (job.stream.cached == e.at) store.resumed(e, job.request.prompt, true); + if (job.stream.reuse_failed) store.resumed(e, job.request.cacheKey(), false) else if (job.stream.cached == e.at) store.resumed(e, job.request.cacheKey(), true); } }; @@ -291,7 +291,7 @@ pub const LaneHost = struct { const r = job.request; var reuse: lanes.stream.Reuse = .{}; // the entry stays alive until the backend restores it: nothing keeps between here and this stream's own pass - if (h.cache) |store| if (store.lookupRewind(h.gpa, r.prompt, r.history_len, r.rewind_len, r.shared_prefixes, r.chunks, h.spans(r))) |l| { + if (h.cache) |store| if (store.lookupRewind(h.gpa, r.cacheKey(), r.history_len, r.rewind_len, r.shared_prefixes, r.chunks, r.cacheSpans(h.decoded_rows))) |l| { job.entry = l.entry; job.kept0 = store.counts.kept; job.marks = l.marks; @@ -322,8 +322,9 @@ pub const LaneHost = struct { job.proposer.deinit(); return h.drop(job, if (e == error.OutOfMemory) "out of memory" else "the reply's grammar could not start (xgrammar)"); } else null, - .decode_spans = h.spans(r), + .decode_spans = r.cacheSpans(h.decoded_rows), .decide = r.decide, + .images = r.images, }) catch { job.proposer.deinit(); return h.drop(job, "out of memory"); @@ -395,11 +396,6 @@ pub const LaneHost = struct { emit(job, .{ .prefilled = job.stream.cached }); } - /// A request's decoded prompt rows, for a backend that keeps their bits (`decoded_rows`); otherwise none. - fn spans(h: *const LaneHost, r: *const Request) []const [2]u32 { - return if (h.decoded_rows) r.decode_spans else &.{}; - } - /// A prompt-only pass on a `warm_turns` engine: the backend prefills and the cache keeps where it ends. fn warmPass(h: *LaneHost, job: *Job, began: i96) bool { const be = h.core.backend; @@ -409,7 +405,7 @@ pub const LaneHost = struct { return h.cancel(job); }; h.prefilled(job, began); - if (h.cache) |store| _ = store.keep(job.request.prompt, @intCast(job.request.prompt.len), &job.stream, job.request.chunks, h.spans(job.request)); + if (h.cache) |store| _ = store.keep(job.request.prompt, @intCast(job.request.prompt.len), &job.stream, job.request.chunks, job.request.cacheSpans(h.decoded_rows)); be.release(&job.stream); h.remove(job); h.finish(job, .length, ""); diff --git a/zig/src/core/lane_host_reuse_test.zig b/zig/src/core/lane_host_reuse_test.zig index 549121dd83..c3a1286c21 100644 --- a/zig/src/core/lane_host_reuse_test.zig +++ b/zig/src/core/lane_host_reuse_test.zig @@ -97,6 +97,94 @@ test "a lane host resumes a conversation from its kept prompt state and reports try std.testing.expectEqual(@as(usize, 2), store.entries.items.len); } +test "an image's placeholders are cached by its content: another image under the same ids resumes none of it" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.backend(), clock.clock()); + defer core.deinit(); + const Snaps = struct { + fn bytes(_: *anyopaque, at: u32) u64 { + return 64 + 4 * @as(u64, at); + } + fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!pc.Saved { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + return f.save(@ptrCast(@alignCast(owner.?)), at); + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: pc.Saved) anyerror!void { + return error.BackendRestores; // lane-core backends restore inside their own prompt pass + } + fn drop(ptr: *anyopaque, saved: pc.Saved) void { + const f: *lanes.fake.Fake = @ptrCast(@alignCast(ptr)); + f.drop(saved); + } + }; + var store = pc.Store.init(gpa, .{ .ptr = &target, .vtable = &.{ .bytes = Snaps.bytes, .save = Snaps.save, .restore = Snaps.restore, .drop = Snaps.drop } }, .{ .min_gap = 4, .min_prompt = 0 }, 1 << 20); + defer store.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2 }); + host.cache = &store; + try host.start(); + defer host.stop(); + const Box = struct { + mutex: std.Io.Mutex = .init, + tokens: std.ArrayList(u32) = .empty, + cached: ?u32 = null, + done: ?Reason = null, + fn event(ctx: *anyopaque, _: Id, e: *const Event) void { + const b: *@This() = @ptrCast(@alignCast(ctx)); + b.mutex.lockUncancelable(std.testing.io); + defer b.mutex.unlock(std.testing.io); + switch (e.*) { + .prefilled => |c| b.cached = c, + .logprobs => {}, + .tokens => |t| b.tokens.appendSlice(gpa, t) catch {}, + .finished => |f| b.done = f.reason, + } + } + fn wait(b: *@This()) Reason { + while (true) { + b.mutex.lockUncancelable(std.testing.io); + const d = b.done; + b.mutex.unlock(std.testing.io); + if (d) |r| return r; + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + } + } + }; + const e = host.engine(); + // prompt ids 3..5 are one image's placeholders (token 9); cache_key holds ids derived from each image's content + const t1 = [_]u32{ 3, 1, 9, 9, 9, 9, 2, 6, 5, 3 }; + var key_a = t1; + var key_b = t1; + for (2..6) |k| { + key_a[k] = 0x8000_0000 + @as(u32, @intCast(k)); + key_b[k] = 0x9000_0000 + @as(u32, @intCast(k)); + } + var b1: Box = .{}; + defer b1.tokens.deinit(gpa); + const r1: Request = .{ .prompt = &t1, .max_tokens = 6, .history_len = 8, .cache_key = &key_a }; + try e.submit(1, &r1, .{ .ctx = &b1, .event = Box.event }); + try std.testing.expectEqual(Reason.length, b1.wait()); + try std.testing.expectEqual(@as(usize, 1), store.entries.items.len); // image A's state at 8, past its image + // the same text and placeholder ids with image B: the kept state is A's, so B resumes none of it + var b2: Box = .{}; + defer b2.tokens.deinit(gpa); + const r2: Request = .{ .prompt = &t1, .max_tokens = 6, .history_len = 8, .cache_key = &key_b }; + try e.submit(2, &r2, .{ .ctx = &b2, .event = Box.event }); + try std.testing.expectEqual(Reason.length, b2.wait()); + try std.testing.expectEqual(@as(?u32, 0), b2.cached); + // image A again resumes its own state + var b3: Box = .{}; + defer b3.tokens.deinit(gpa); + const r3: Request = .{ .prompt = &t1, .max_tokens = 6, .history_len = 8, .cache_key = &key_a }; + try e.submit(3, &r3, .{ .ctx = &b3, .event = Box.event }); + try std.testing.expectEqual(Reason.length, b3.wait()); + try std.testing.expectEqual(@as(?u32, 8), b3.cached); +} + test "a turn's mark evicting the state it resumed from: the hit is reported first and the entry freed once" { const gpa = std.testing.allocator; var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); diff --git a/zig/src/core/lanes/stream.zig b/zig/src/core/lanes/stream.zig index d43d01b103..7096e1d517 100644 --- a/zig/src/core/lanes/stream.zig +++ b/zig/src/core/lanes/stream.zig @@ -97,6 +97,10 @@ pub const Held = struct { parents: ?[]i32 = null, }; +/// One image of a prompt: the tower's input (patches [gh * gw, width], the family's layout) and the `tokens` +/// placeholder rows from `at` its output replaces. +pub const Image = struct { pixels: []const f32, gh: u32, gw: u32, at: u32, tokens: u32 }; + pub const Spec = struct { id: []const u8, prompt: []const u32, @@ -121,6 +125,7 @@ pub const Spec = struct { logprobs: ?u8 = null, // the target's log probabilities for each committed token, with this many best tokens grammar: ?*grammar.Constraint = null, // structured output: the reply stays in it (the creator frees it) decode_spans: []const [2]u32 = &.{}, // prompt rows an earlier reply decoded (Request.decode_spans), for backends that keep their bits + images: []const Image = &.{}, // in prompt order; the backend's tower fills their rows }; pub const Stream = struct { @@ -150,6 +155,7 @@ pub const Stream = struct { reuse: Reuse = .{}, decode_spans: []const [2]u32 = &.{}, decide: ?u32 = null, + images: []const Image = &.{}, cached: u32 = 0, // prompt tokens the backend restored from `reuse` (its prompt pass started there) reuse_failed: bool = false, // the backend's restore of `reuse` failed: it prefilled from 0 context: std.ArrayList(u32) = .empty, @@ -209,6 +215,7 @@ pub const Stream = struct { .logprobs = spec.logprobs, .grammar = spec.grammar, .decode_spans = spec.decode_spans, + .images = spec.images, }; // under a grammar a forced close ends at the think end: the grammar takes the reply from the next token if (spec.grammar) |g| if (g.after) |end| if (std.mem.indexOfScalar(u32, s.think_close, end)) |at| { diff --git a/zig/src/core/tokenizer/tokenizer.zig b/zig/src/core/tokenizer/tokenizer.zig index bcb2f5ee8f..69456001ad 100644 --- a/zig/src/core/tokenizer/tokenizer.zig +++ b/zig/src/core/tokenizer/tokenizer.zig @@ -130,10 +130,32 @@ pub const Tokenizer = struct { return a.dupe(u32, ids.items); } + /// `encode` with no added token matched: text that spells one (a quoted marker) is ordinary text. + pub fn encodePlain(t: *const Tokenizer, a: Allocator, text: []const u8) Error![]u32 { + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + var ctx = steps.Context{ .a = arena.allocator(), .matcher = .{ .a = arena.allocator() } }; + var valid = text; + if (!std.unicode.utf8ValidateSlice(text)) { + var fixed: std.ArrayList(u8) = .empty; + try unicode.appendLossy(&fixed, ctx.a, text); + valid = fixed.items; + } + var ids: std.ArrayList(u32) = .empty; + if (valid.len > 0) try t.encodeTextWith(&ctx, valid, true, &ids, false); + return a.dupe(u32, ids.items); + } + fn encodeText(t: *const Tokenizer, ctx: *steps.Context, text: []const u8, first: bool, ids: *std.ArrayList(u32)) Error!void { + return t.encodeTextWith(ctx, text, first, ids, true); + } + + fn encodeTextWith(t: *const Tokenizer, ctx: *steps.Context, text: []const u8, first: bool, ids: *std.ArrayList(u32), added: bool) Error!void { var zero: usize = if (first) unicode.decodeAt(text, 0).len else 0; const normalized = if (t.normalizer) |*n| try n.apply(ctx, text, &zero) else text; - for (try t.splitAdded(ctx, &t.normalized, normalized)) |seg| { + const whole = [_]Segment{.{ .start = 0, .end = normalized.len, .id = null }}; + const segs: []const Segment = if (added) try t.splitAdded(ctx, &t.normalized, normalized) else &whole; + for (segs) |seg| { if (seg.id) |id| { try ids.append(ctx.a, id); continue; diff --git a/zig/src/families/glm/backend.zig b/zig/src/families/glm/backend.zig index d98f41932d..205c367bef 100644 --- a/zig/src/families/glm/backend.zig +++ b/zig/src/families/glm/backend.zig @@ -3,6 +3,7 @@ const std = @import("std"); const lanes = @import("lanes"); const st = @import("state.zig"); const slots_mod = @import("slots.zig"); +const slot_images = @import("slot_images.zig"); const pool = @import("pool.zig"); const mirror = @import("mirror.zig"); const snapshot = @import("snapshot.zig"); @@ -101,6 +102,11 @@ pub const Backend = struct { try mirror.send(e, .begin, b.words.items); try b.sl.begin(i, prompt, s.drafts); s.cached = 0; + if (s.images.len > 0) { // the images through the tower first: the chunks inject their rows + if (e.ep != null) return error.VisionOnPair; + try slot_images.encode(b.sl, i, s.images); + } + defer if (s.images.len > 0) slot_images.end(b.sl); var at: u32 = 0; if (s.reuse.saved) |saved| { // a kept state of this prompt's prefix: the pass starts there const snap: *snapshot.Snap = @ptrCast(@alignCast(saved)); diff --git a/zig/src/families/glm/checks.zig b/zig/src/families/glm/checks.zig index 4b521379c1..78ec7a274b 100644 --- a/zig/src/families/glm/checks.zig +++ b/zig/src/families/glm/checks.zig @@ -167,7 +167,7 @@ pub fn checkMatmul(e: *Engine, prompt: []const u32) !void { const out = try e.arena.buffer(@as(usize, rows) * N * 2); var x = e.ctx(); const b = e.begin(); - fwd.embed(&x, b.enc, e.prompt_ids, rows); + fwd.embed(&x, b.enc, e.prompt_ids, rows, 0); fwd.boundary(&x, b.enc, rows, false, L.hc.?[0], L.in_norm); fwd.qmv(&x, b.enc, e.k.qmv_kda_in, e.sc.normed, a.in_proj, out, rows); affine_mm.rowSums(b.enc, e.k.mm_bf16, 64, e.sc.normed, pr.sums, rows, a.in_proj.k); diff --git a/zig/src/families/glm/engine.zig b/zig/src/families/glm/engine.zig index 5affbae1f3..c37c166c98 100644 --- a/zig/src/families/glm/engine.zig +++ b/zig/src/families/glm/engine.zig @@ -4,6 +4,7 @@ const mtl = @import("metal"); const cfg = @import("config.zig"); const wts = @import("weights.zig"); const page_cache = @import("page_cache.zig"); +const vision_mod = @import("vision.zig"); const st = @import("state.zig"); const fwd = @import("forward.zig"); const mtp = @import("mtp.zig"); @@ -83,6 +84,9 @@ pub const Engine = struct { rank_log: bool = false, // GLM_RANKS=1: each MTP depth's logits kept, and the target's rank in them where drafts miss ep_arena: std.heap.ArenaAllocator, // the link settings, alive as long as the link residency: ?mtl.ResidencySet = null, + vision: ?*vision_mod.Vision = null, // --vision: the image tower + vision_rows: Ref = undefined, // bf16 [image tokens, hidden]: a prompt's image rows (vision only) + vision_limits: vision_mod.Limits = .{}, keepalive_sets: [1]mtl.ResidencySet = undefined, // the residency set, for the idle keepalive's commit keepalive_target: mtl.keepalive.Target = undefined, // the engine's queue, set at load for the server's ticker load_seconds: f64 = 0, @@ -94,11 +98,12 @@ pub const Engine = struct { /// The checkpoint in `dir`, caches for `cap` tokens; GLM_LAYERS=N: the first N layers only; GLM_EP=settings: half the experts. pub fn load(gpa: std.mem.Allocator, dir: []const u8, cap: u32) !*Engine { - return loadWith(gpa, dir, cap, if (std.c.getenv("GLM_EP")) |v| std.mem.span(v) else null, false); + return loadWith(gpa, dir, cap, if (std.c.getenv("GLM_EP")) |v| std.mem.span(v) else null, false, null); } /// `load` with expert parallel over the link in `ep_path` (this Mac's settings), or on one Mac when null. - pub fn loadWith(gpa: std.mem.Allocator, dir: []const u8, cap: u32, ep_path: ?[]const u8, learn: bool) !*Engine { + /// `vision`: the image tower too, with scratch and rows for that many image tokens a prompt. + pub fn loadWith(gpa: std.mem.Allocator, dir: []const u8, cap: u32, ep_path: ?[]const u8, learn: bool, vision: ?vision_mod.Limits) !*Engine { const e = try gpa.create(Engine); // undefined memory: every field is set below errdefer gpa.destroy(e); const pool = mtl.objc.Pool.push(); @@ -107,6 +112,7 @@ pub const Engine = struct { e.gpa = gpa; e.ev = 0; e.residency = null; + e.vision = null; e.gpu = .{ 0, 0 }; e.fused_route = if (std.c.getenv("GLM_ROUTE")) |v| v[0] != '0' else true; e.draft_vocab = if (std.c.getenv("GLM_DRAFT_VOCAB")) |v| std.fmt.parseInt(u32, std.mem.span(v), 10) catch 0 else 0; @@ -212,10 +218,13 @@ pub const Engine = struct { me.rest[2] = @intFromBool(learn); // --learn on both Macs or neither: each holds its half of a learned state e.ep = try ep_mod.Ep.init(gpa, e.device, s, me); } + if (vision) |lim| try vision_mod.attach(e, gpa, dir, f.bytes[0..f.size], lim); // --vision: the tower and its rows + errdefer if (e.vision) |v| v.deinit(); // opt-in: wiring 181 GB leaves macOS nothing to reclaim if another model shares the Mac (Flash Next runs without) - if (std.c.getenv("GLM_RESIDENCY") == null) {} else if (e.device.residencySet(e.w.buffers.items.len + e.arena.buffers.items.len)) |set| { + if (std.c.getenv("GLM_RESIDENCY") == null) {} else if (e.device.residencySet(e.w.buffers.items.len + e.arena.buffers.items.len + if (e.vision) |v| v.buffers().len else 0)) |set| { for (e.w.buffers.items) |b| set.add(b); for (e.arena.buffers.items) |b| set.add(b); + if (e.vision) |v| for (v.buffers()) |b| set.add(b); set.commit(); set.requestResidency(); e.queue.addResidencySet(set); @@ -265,6 +274,7 @@ pub const Engine = struct { set.deinit(); } if (e.ep) |ep| ep.deinit(gpa); + if (e.vision) |v| v.deinit(); e.ep_arena.deinit(); if (e.pr) |*p| p.deinit(); if (e.round_fence) |f| f.deinit(); diff --git a/zig/src/families/glm/forward.zig b/zig/src/families/glm/forward.zig index 018b99d3d3..84748ba88b 100644 --- a/zig/src/families/glm/forward.zig +++ b/zig/src/families/glm/forward.zig @@ -30,8 +30,29 @@ pub const Ctx = struct { draft_vocab: u32 = 154880, // the MTP head's tokens: the vocabulary's first this many m_row: u32 = 0, // the MTP head's logits row in m_logits (a rank log keeps each depth's in its own row) segs: []const Seg = &.{}, // a shared window's streams in row order (empty: every row is `s`'s) + inject: ?*const Inject = null, // a prompt pass's image rows over its placeholder embeddings }; +/// An image prompt's tower output: prompt rows [at, at + n) of each span embed as rows [row, row + n) of `rows`. +pub const Inject = struct { rows: Ref, spans: []const Span }; +pub const Span = struct { at: u32, n: u32, row: u32 }; + +/// The image rows among `rows` embedding rows (prompt positions pos..) written over `out`; nothing without an injection. +pub fn inject(x: *const Ctx, e: mtl.ComputeEncoder, out: Ref, rows: u32, pos: u32) void { + const inj = x.inject orelse return; + const D: usize = x.c.hidden; + for (inj.spans) |sp| { + const lo = @max(sp.at, pos); + const hi = @min(sp.at + sp.n, pos + rows); + if (lo >= hi) continue; + const n: usize = hi - lo; + e.setPipeline(x.k.copy_u32); + bind(e, 0, .{ inj.rows.at((sp.row + lo - sp.at) * D * 2), out.at((lo - pos) * D * 2) }); + e.setValue(@as(u32, @intCast(n * D / 2)), 2); + e.dispatchThreads(size(n * D / 2, 1, 1), size(256, 1, 1)); + } +} + /// One stream's rows in a shared window: its caches, its first row, its rows and the position of the first. pub const Seg = struct { s: *st.State, row0: u32, rows: u32, pos: u32 }; @@ -135,11 +156,12 @@ pub fn scale(x: *const Ctx, e: mtl.ComputeEncoder, in: Ref, out: Ref, rows: u32, e.dispatchThreads(size(width, rows, 1), size(@min(width, 256), 1, 1)); } -/// The window's tokens (`ids`, u32) as embedding rows in all four streams. -pub fn embed(x: *Ctx, e: mtl.ComputeEncoder, ids: Ref, rows: u32) void { +/// The window's tokens (`ids`, u32, at positions pos..) as embedding rows in all four streams, image rows injected. +pub fn embed(x: *Ctx, e: mtl.ComputeEncoder, ids: Ref, rows: u32, pos: u32) void { const sc = x.sc; const D = x.c.hidden; embedRows(x, e, ids, sc.h, rows); + inject(x, e, sc.h, rows, pos); e.setPipeline(x.k.streams); bind(e, 0, .{ sc.h, sc.x[0] }); e.setValue([2]u32{ D, rows }, 2); @@ -415,7 +437,7 @@ pub fn backbone(x: *Ctx, e: mtl.ComputeEncoder, ids: Ref, rows: u32, pos: u32) v const c = x.c; const sc = x.sc; const k = x.skip; - if (k & Class.ends == 0) embed(x, e, ids, rows); + if (k & Class.ends == 0) embed(x, e, ids, rows, pos); const plane = @as(usize, rows) * c.hidden * 2; snap(x, e, sc.h, plane); var pending = false; diff --git a/zig/src/families/glm/glm.zig b/zig/src/families/glm/glm.zig index 34bf628cc9..5b0ffe7425 100644 --- a/zig/src/families/glm/glm.zig +++ b/zig/src/families/glm/glm.zig @@ -13,6 +13,8 @@ pub const pool = @import("pool.zig"); pub const backend = @import("backend.zig"); pub const mirror = @import("mirror.zig"); pub const timing = @import("timing.zig"); +pub const vision = @import("vision.zig"); +pub const image = @import("image.zig"); test { _ = config; @@ -30,4 +32,6 @@ test { _ = pool; _ = mirror; _ = timing; + _ = vision; + _ = image; } diff --git a/zig/src/families/glm/image.zig b/zig/src/families/glm/image.zig new file mode 100644 index 0000000000..4da98c4f4e --- /dev/null +++ b/zig/src/families/glm/image.zig @@ -0,0 +1,453 @@ +//! An image's bytes to GLM5-Next vision patches as TensorFold 0.6.6's --vision makes them: decoded as its +//! vision/images.py does with PIL (ImageIO here: the stored values, no colour management; EXIF orientation applied; +//! alpha composited over white with PIL's integer blend), then mlx-vlm's Glm5NextImageProcessor: sized under the +//! token budget, resized with PIL's 8-bit bicubic resampler, padded with black, normalized, and cut into 2x2 windows +//! of 14x14 patches, each patch's frame given twice (temporal_patch_size 2). +const std = @import("std"); +const vision = @import("vision.zig"); + +pub const Rgb = struct { + w: u32, + h: u32, + px: []u8, // row-major RGB, 3 bytes a pixel + + pub fn deinit(r: Rgb, gpa: std.mem.Allocator) void { + gpa.free(r.px); + } +}; + +/// One image ready for the tower: its patches, its patch grid and its tokens (gh * gw / 4). +pub const Prepared = struct { + pixels: []f32, // [gh * gw, 1176] + gh: u32, + gw: u32, + tokens: u32, + hash: u64, // of the image's bytes: two prompts with the same placeholders but other images are other prompts +}; + +pub const Error = error{ BadImage, ImageTooLarge, Animated, ImageTooSmall, OutOfMemory }; + +/// images.py's ImageLimits: an image's encoded bytes, sides and pixels. +pub const max_bytes = 10 << 20; +pub const max_side = 8192; +pub const max_pixels = 16 << 20; + +// ---- ImageIO and CoreGraphics (C APIs; the server binary links both frameworks) ---- +const CF = *anyopaque; +const CGRect = extern struct { x: f64, y: f64, w: f64, h: f64 }; +extern "c" fn CFDataCreate(alloc: ?CF, bytes: [*]const u8, len: isize) ?CF; +extern "c" fn CFDataGetBytePtr(data: CF) [*]const u8; +extern "c" fn CFDataGetLength(data: CF) isize; +extern "c" fn CFRelease(cf: CF) void; +extern "c" fn CGImageSourceCreateWithData(data: CF, options: ?CF) ?CF; +extern "c" fn CGImageSourceGetCount(src: CF) usize; +extern "c" fn CGImageSourceCreateImageAtIndex(src: CF, index: usize, options: ?CF) ?CF; +extern "c" fn CGImageGetWidth(img: CF) usize; +extern "c" fn CGImageGetHeight(img: CF) usize; +extern "c" fn CGImageGetBitsPerComponent(img: CF) usize; +extern "c" fn CGImageGetBitsPerPixel(img: CF) usize; +extern "c" fn CGImageGetBytesPerRow(img: CF) usize; +extern "c" fn CGImageGetBitmapInfo(img: CF) u32; +extern "c" fn CGImageGetColorSpace(img: CF) ?CF; +extern "c" fn CGColorSpaceGetModel(cs: CF) i32; +extern "c" fn CGImageGetDataProvider(img: CF) ?CF; +extern "c" fn CGDataProviderCopyData(p: CF) ?CF; +extern "c" fn CGColorSpaceCreateDeviceRGB() ?CF; +extern "c" fn CGColorSpaceRelease(cs: CF) void; +extern "c" fn CGBitmapContextCreate(data: ?*anyopaque, w: usize, h: usize, bpc: usize, bpr: usize, cs: CF, info: u32) ?CF; +extern "c" fn CGContextDrawImage(ctx: CF, rect: CGRect, img: CF) void; +extern "c" fn CGContextRelease(ctx: CF) void; +extern "c" fn CGContextSetRGBFillColor(ctx: CF, r: f64, g: f64, b: f64, a: f64) void; +extern "c" fn CGContextFillRect(ctx: CF, rect: CGRect) void; +extern "c" fn CGImageSourceCopyPropertiesAtIndex(src: CF, index: usize, options: ?CF) ?CF; +extern "c" fn CFDictionaryGetValue(dict: CF, key: ?*const anyopaque) ?CF; +extern "c" fn CFNumberGetValue(num: CF, kind: isize, out: *anyopaque) bool; +extern var kCGImagePropertyOrientation: ?*const anyopaque; + +const alpha_mask: u32 = 0x1f; +const order_mask: u32 = 0x7000; +const order_32_little: u32 = 0x2000; +const order_16_little: u32 = 0x1000; +const float_components: u32 = 0x100; + +/// A PNG, JPEG, GIF, WebP, HEIC or any other single-frame image ImageIO reads, as 8-bit RGB: upright by its EXIF +/// orientation (PIL's exif_transpose) and over white where it has alpha (images.py's paste onto a white canvas). +pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) Error!Rgb { + if (bytes.len == 0) return error.BadImage; + if (bytes.len > max_bytes) return error.ImageTooLarge; + const data = CFDataCreate(null, bytes.ptr, @intCast(bytes.len)) orelse return error.OutOfMemory; + defer CFRelease(data); + const src = CGImageSourceCreateWithData(data, null) orelse return error.BadImage; + defer CFRelease(src); + const frames = CGImageSourceGetCount(src); + if (frames == 0) return error.BadImage; + if (frames > 1) return error.Animated; // images.py: animated and multipage images are refused + const img = CGImageSourceCreateImageAtIndex(src, 0, null) orelse return error.BadImage; + defer CFRelease(img); + const w = CGImageGetWidth(img); + const h = CGImageGetHeight(img); + if (w == 0 or h == 0) return error.BadImage; + if (w > max_side or h > max_side or w * h > max_pixels) return error.ImageTooLarge; + const out = try gpa.alloc(u8, w * h * 3); + errdefer gpa.free(out); + if (!(try raw(img, w, h, out))) try drawn(img, w, h, out); + const rgb: Rgb = .{ .w = @intCast(w), .h = @intCast(h), .px = out }; + const o = orientation(src); + if (o <= 1 or o > 8) return rgb; + defer rgb.deinit(gpa); + return orient(gpa, rgb, o); +} + +/// The first image's EXIF orientation (1-8; 1 or 0: as stored). +fn orientation(src: CF) u32 { + const props = CGImageSourceCopyPropertiesAtIndex(src, 0, null) orelse return 1; + defer CFRelease(props); + const num = CFDictionaryGetValue(props, kCGImagePropertyOrientation) orelse return 1; + var v: i32 = 1; + if (!CFNumberGetValue(num, 9, &v)) return 1; // kCFNumberIntType + return if (v < 1) 1 else @intCast(v); +} + +/// PIL's exif_transpose: orientation 2-8 as FLIP_LEFT_RIGHT, ROTATE_180, FLIP_TOP_BOTTOM, TRANSPOSE, ROTATE_270, +/// TRANSVERSE, ROTATE_90; each output pixel read from its source pixel. +pub fn orient(gpa: std.mem.Allocator, src: Rgb, o: u32) Error!Rgb { + const w: usize = src.w; + const h: usize = src.h; + const swap = o >= 5; + const ow = if (swap) h else w; + const oh = if (swap) w else h; + const out = try gpa.alloc(u8, ow * oh * 3); + for (0..oh) |y| for (0..ow) |x| { + const s: [2]usize = switch (o) { + 2 => .{ w - 1 - x, y }, + 3 => .{ w - 1 - x, h - 1 - y }, + 4 => .{ x, h - 1 - y }, + 5 => .{ y, x }, + 6 => .{ y, h - 1 - x }, + 7 => .{ w - 1 - y, h - 1 - x }, + else => .{ w - 1 - y, x }, + }; + @memcpy(out[(y * ow + x) * 3 ..][0..3], src.px[(s[1] * w + s[0]) * 3 ..][0..3]); + }; + return .{ .w = @intCast(ow), .h = @intCast(oh), .px = out }; +} + +/// PIL's paste of a pixel with alpha `a` onto white: DIV255(255 * (255 - a) + c * a). +fn overWhite(c: u8, a: u8) u8 { + const t: u32 = 255 * (255 - @as(u32, a)) + @as(u32, c) * a + 128; + return @intCast(((t >> 8) + t) >> 8); +} + +/// The decoder's own values for 8- and 16-bit gray and RGB layouts (what PIL reads); false for any other layout. +fn raw(img: CF, w: usize, h: usize, out: []u8) Error!bool { + const info = CGImageGetBitmapInfo(img); + if (info & float_components != 0) return false; + const cs = CGImageGetColorSpace(img) orelse return false; + const model = CGColorSpaceGetModel(cs); // 0 monochrome, 1 RGB + if (model != 0 and model != 1) return false; + const bpc = CGImageGetBitsPerComponent(img); + const bpp = CGImageGetBitsPerPixel(img); + if (bpc != 8 and bpc != 16) return false; + const alpha = info & alpha_mask; // 0 none, 1/2 premultiplied last/first, 3/4 last/first, 5/6 skip last/first + if (alpha == 1 or alpha == 2 or alpha > 6) return false; + const colours: usize = if (model == 1) 3 else 1; + const comps: usize = colours + @intFromBool(alpha != 0); + if (bpp != comps * bpc) return false; + const first = alpha == 2 or alpha == 4 or alpha == 6; // the alpha (or skipped) component leads + const order = info & order_mask; + const little = (bpc == 8 and order == order_32_little) or (bpc == 16 and order == order_16_little); + if (bpc == 8 and order != 0 and order != order_32_little) return false; + if (bpc == 8 and little and comps != 4) return false; + const provider = CGImageGetDataProvider(img) orelse return false; + const data = CGDataProviderCopyData(provider) orelse return false; + defer CFRelease(data); + const base = CFDataGetBytePtr(data); + const len: usize = @intCast(CFDataGetLength(data)); + const bpr = CGImageGetBytesPerRow(img); + if (bpr * (h - 1) + w * bpp / 8 > len) return false; + const step = bpc / 8; + for (0..h) |y| { + const row = base + y * bpr; + for (0..w) |x| { + const px = row + x * comps * step; + var c: [4]u8 = undefined; + for (0..comps) |i| { + // a 32-bit little-endian pixel stores its components reversed; a 16-bit one each component's bytes + const slot = if (bpc == 8 and little) comps - 1 - i else i; + const at = px + slot * step; + c[i] = if (step == 1) at[0] else if (little) at[1] else at[0]; // 16 bits: the high byte, as PIL's 8-bit view + } + const lead: usize = @intFromBool(first and alpha != 0); + const o = out[(y * w + x) * 3 ..][0..3]; + if (colours == 3) { + o.* = .{ c[lead], c[lead + 1], c[lead + 2] }; + } else { + o.* = .{ c[lead], c[lead], c[lead] }; + } + if (alpha == 3 or alpha == 4) { // a real alpha band: over white, as images.py pastes it + const a = if (first) c[0] else c[comps - 1]; + for (o) |*v| v.* = overWhite(v.*, a); + } + } + } + return true; +} + +/// Any other layout (palette, CMYK, float, premultiplied): drawn into an RGB context over white. +fn drawn(img: CF, w: usize, h: usize, out: []u8) Error!void { + const cs = CGColorSpaceCreateDeviceRGB() orelse return error.BadImage; + defer CGColorSpaceRelease(cs); + const tmp = std.heap.page_allocator.alloc(u8, w * h * 4) catch return error.OutOfMemory; + defer std.heap.page_allocator.free(tmp); + @memset(tmp, 0); + const ctx = CGBitmapContextCreate(tmp.ptr, w, h, 8, w * 4, cs, 5) orelse return error.BadImage; // RGBX + defer CGContextRelease(ctx); + CGContextSetRGBFillColor(ctx, 1, 1, 1, 1); + CGContextFillRect(ctx, .{ .x = 0, .y = 0, .w = @floatFromInt(w), .h = @floatFromInt(h) }); + CGContextDrawImage(ctx, .{ .x = 0, .y = 0, .w = @floatFromInt(w), .h = @floatFromInt(h) }, img); + for (0..w * h) |i| @memcpy(out[i * 3 ..][0..3], tmp[i * 4 ..][0..3]); +} + +// ---- the processor's geometry ---- + +pub const Geometry = struct { target_h: u32, target_w: u32, content_h: u32, content_w: u32 }; + +fn alignUp(v: u64, f: u64) u64 { + return (v + f - 1) / f * f; +} + +/// smart_resize and _resize_geometry (num_frames = temporal_patch_size, as _process_one calls it): the padded canvas +/// under `max_tokens` (at least `min_tokens`), and the content size the image is resized to inside it. +pub fn geometry(h: u32, w: u32, min_tokens: u32, max_tokens: u32) Error!Geometry { + const factor: u64 = vision.patch * vision.merge; + const frames: u64 = vision.temporal; + const per_token = frames * factor * factor; + const min_px = @as(u64, min_tokens) * per_token; + const max_px = @as(u64, max_tokens) * per_token; + if (min_tokens == 0 or max_tokens < min_tokens) return error.ImageTooSmall; + const H: u64 = h; + const W: u64 = w; + var ah = alignUp(H, factor); + var aw = alignUp(W, factor); + var pixels = frames * ah * aw; + if (pixels < min_px) { + const scale = @sqrt(@as(f64, @floatFromInt(min_px)) / @as(f64, @floatFromInt(frames * H * W))); + ah = alignUp(@max(1, @as(u64, @intFromFloat(@ceil(@as(f64, @floatFromInt(H)) * scale)))), factor); + aw = alignUp(@max(1, @as(u64, @intFromFloat(@ceil(@as(f64, @floatFromInt(W)) * scale)))), factor); + pixels = frames * ah * aw; + } + if (pixels > max_px) { // the tallest content that fits, by bisection on its height + if (max_px < frames * factor * factor) return error.ImageTooSmall; + var best: [2]u64 = .{ factor, factor }; + var low: i64 = 1; + var high: i64 = @intCast(H); + while (low <= high) { + const ch: u64 = @intCast(@divFloor(low + high, 2)); + const cw: u64 = @max(1, W * ch / H); // math.floor(width * content_h / height) + const cand: [2]u64 = .{ alignUp(ch, factor), alignUp(cw, factor) }; + if (frames * cand[0] * cand[1] <= max_px) { + best = cand; + low = @as(i64, @intCast(ch)) + 1; + } else high = @as(i64, @intCast(ch)) - 1; + } + ah = best[0]; + aw = best[1]; + } + var scale = @min(@as(f64, @floatFromInt(ah)) / @as(f64, @floatFromInt(H)), @as(f64, @floatFromInt(aw)) / @as(f64, @floatFromInt(W))); + if (frames * H * W >= min_px) scale = @min(1.0, scale); + const chf: u64 = @intFromFloat(@floor(@as(f64, @floatFromInt(H)) * scale)); + const cwf: u64 = @intFromFloat(@floor(@as(f64, @floatFromInt(W)) * scale)); + return .{ .target_h = @intCast(ah), .target_w = @intCast(aw), .content_h = @intCast(@max(1, @min(ah, chf))), .content_w = @intCast(@max(1, @min(aw, cwf))) }; +} + +// ---- PIL's ImagingResample for 8-bit images (Resample.c), bicubic (a = -0.5) ---- + +const precision_bits = 32 - 8 - 2; + +fn bicubic(x0: f64) f64 { + const a = -0.5; + const x = @abs(x0); + if (x < 1.0) return ((a + 2.0) * x - (a + 3.0)) * x * x + 1; + if (x < 2.0) return (((x - 5) * x + 8) * x - 4) * a; + return 0; +} + +const Coeffs = struct { bounds: []u32, kk: []i32, ksize: usize }; + +/// precompute_coeffs and normalize_coeffs_8bpc: each output pixel's first input pixel, count and fixed-point weights. +fn coeffs(gpa: std.mem.Allocator, in_size: u32, out_size: u32) Error!Coeffs { + const scale = @as(f64, @floatFromInt(in_size)) / @as(f64, @floatFromInt(out_size)); + const filterscale = @max(scale, 1.0); + const support = 2.0 * filterscale; + const ksize: usize = @as(usize, @intFromFloat(@ceil(support))) * 2 + 1; + const bounds = try gpa.alloc(u32, @as(usize, out_size) * 2); + errdefer gpa.free(bounds); + const kk = try gpa.alloc(i32, @as(usize, out_size) * ksize); + errdefer gpa.free(kk); + var pre = try gpa.alloc(f64, ksize); + defer gpa.free(pre); + const ss = 1.0 / filterscale; + for (0..out_size) |xx| { + const center = (@as(f64, @floatFromInt(xx)) + 0.5) * scale; + var xmin_i: i64 = @intFromFloat(center - support + 0.5); // (int) truncates toward zero, as C does + if (xmin_i < 0) xmin_i = 0; + var xmax_i: i64 = @intFromFloat(center + support + 0.5); + if (xmax_i > in_size) xmax_i = in_size; + xmax_i -= xmin_i; + const xmin: usize = @intCast(xmin_i); + const xmax: usize = @intCast(xmax_i); + var ww: f64 = 0; + for (0..xmax) |x| { + const w = bicubic((@as(f64, @floatFromInt(x + xmin)) - center + 0.5) * ss); + pre[x] = w; + ww += w; + } + for (0..ksize) |x| { + const k = if (x < xmax) (if (ww != 0) pre[x] / ww else pre[x]) else 0; + const v = k * @as(f64, @floatFromInt(@as(i64, 1) << precision_bits)); + kk[xx * ksize + x] = @intFromFloat(if (v < 0) v - 0.5 else v + 0.5); // C's (int) of the rounded value + } + bounds[xx * 2] = @intCast(xmin); + bounds[xx * 2 + 1] = @intCast(xmax); + } + return .{ .bounds = bounds, .kk = kk, .ksize = ksize }; +} + +fn clip8(v: i64) u8 { + const s = v >> precision_bits; + return if (s < 0) 0 else if (s > 255) 255 else @intCast(s); +} + +/// Image.resize((w, h), BICUBIC) on an 8-bit RGB image: horizontal pass, then vertical, each rounded to 8 bits. +pub fn resize(gpa: std.mem.Allocator, src: Rgb, w: u32, h: u32) Error!Rgb { + var cur = src; + var owned = false; + errdefer if (owned) cur.deinit(gpa); + if (w != src.w) { // horizontal (PIL limits it to the rows the vertical pass reads: all of them here) + const c = try coeffs(gpa, src.w, w); + defer gpa.free(c.bounds); + defer gpa.free(c.kk); + const out = try gpa.alloc(u8, @as(usize, w) * cur.h * 3); + for (0..cur.h) |y| for (0..w) |xx| { + const xmin = c.bounds[xx * 2]; + const xmax = c.bounds[xx * 2 + 1]; + const k = c.kk[xx * c.ksize ..]; + for (0..3) |ch| { + var ss: i64 = 1 << (precision_bits - 1); + for (0..xmax) |x| ss += @as(i64, cur.px[(y * cur.w + x + xmin) * 3 + ch]) * k[x]; + out[(y * w + xx) * 3 + ch] = clip8(ss); + } + }; + if (owned) cur.deinit(gpa); + cur = .{ .w = w, .h = cur.h, .px = out }; + owned = true; + } + if (h != src.h) { + const c = try coeffs(gpa, src.h, h); + defer gpa.free(c.bounds); + defer gpa.free(c.kk); + const out = try gpa.alloc(u8, @as(usize, cur.w) * h * 3); + for (0..h) |yy| { + const ymin = c.bounds[yy * 2]; + const ymax = c.bounds[yy * 2 + 1]; + const k = c.kk[yy * c.ksize ..]; + for (0..cur.w) |x| for (0..3) |ch| { + var ss: i64 = 1 << (precision_bits - 1); + for (0..ymax) |y| ss += @as(i64, cur.px[((y + ymin) * cur.w + x) * 3 + ch]) * k[y]; + out[(yy * cur.w + x) * 3 + ch] = clip8(ss); + }; + } + if (owned) cur.deinit(gpa); + cur = .{ .w = cur.w, .h = h, .px = out }; + owned = true; + } + if (!owned) cur = .{ .w = src.w, .h = src.h, .px = try gpa.dupe(u8, src.px) }; + return cur; +} + +/// The content (already resized) padded with black to the canvas, scaled by 1/255, normalized by channel, cut into +/// 2x2 windows of 14x14 patches in row-major window order, each patch [channel, frame (twice), row, column]. +pub fn patchify(gpa: std.mem.Allocator, content: Rgb, g: Geometry, mean: [3]f32, sd: [3]f32) Error![]f32 { + const P = vision.patch; + const M = vision.merge; + const gh = g.target_h / P; + const gw = g.target_w / P; + const out = try gpa.alloc(f32, @as(usize, gh) * gw * vision.patch_width); + const rescale: f32 = @floatCast(@as(f64, 1.0) / 255.0); + var row: usize = 0; + for (0..gh / M) |wy| for (0..gw / M) |wx| for (0..M) |my| for (0..M) |mx| { + const py0 = (wy * M + my) * P; + const px0 = (wx * M + mx) * P; + const dst = out[row * vision.patch_width ..][0..vision.patch_width]; + for (0..3) |ch| for (0..vision.temporal) |t| for (0..P) |dy| for (0..P) |dx| { + const y = py0 + dy; + const x = px0 + dx; + const v: u8 = if (y < content.h and x < content.w) content.px[(y * content.w + x) * 3 + ch] else 0; + const f = @as(f32, @floatFromInt(v)) * rescale; + dst[((ch * vision.temporal + t) * P + dy) * P + dx] = (f - mean[ch]) / sd[ch]; + }; + row += 1; + }; + return out; +} + +/// Bytes to patches: decoded, sized for `max_tokens` (at least min(16, max_tokens)), resized, padded and cut. +pub fn prepare(gpa: std.mem.Allocator, bytes: []const u8, c: vision.Config, max_tokens: u32) Error!Prepared { + const img = try decode(gpa, bytes); + defer img.deinit(gpa); + return prepareRgb(gpa, img, std.hash.Wyhash.hash(0x1a6e, bytes), c, max_tokens); +} + +pub fn prepareRgb(gpa: std.mem.Allocator, img: Rgb, hash: u64, c: vision.Config, max_tokens: u32) Error!Prepared { + const g = try geometry(img.h, img.w, @min(c.min_tokens, max_tokens), max_tokens); + const content = try resize(gpa, img, g.content_w, g.content_h); + defer content.deinit(gpa); + const pixels = try patchify(gpa, content, g, c.mean, c.std); + const gh = g.target_h / vision.patch; + const gw = g.target_w / vision.patch; + return .{ .pixels = pixels, .gh = gh, .gw = gw, .tokens = gh * gw / vision.patches_per_token, .hash = hash }; +} + +test "geometry follows smart_resize" { + // the reference dumps' grids: 517x389 pads to 532x392 unscaled; 96x96 grows to 112; 20x15 to the 16-token floor + try std.testing.expectEqual(Geometry{ .target_h = 392, .target_w = 532, .content_h = 389, .content_w = 517 }, try geometry(389, 517, 16, 4096)); + try std.testing.expectEqual(Geometry{ .target_h = 112, .target_w = 112, .content_h = 112, .content_w = 112 }, try geometry(96, 96, 16, 4096)); + const tiny = try geometry(15, 20, 16, 4096); + try std.testing.expectEqual(@as(u32, 8 * 14), tiny.target_h); + try std.testing.expectEqual(@as(u32, 10 * 14), tiny.target_w); + // a large image under a small budget: the canvas fits it + const big = try geometry(1500, 2000, 16, 256); + try std.testing.expect(@as(u64, big.target_h) * big.target_w * 2 <= 256 * 2 * 28 * 28); + try std.testing.expect(big.content_h <= big.target_h and big.content_w <= big.target_w); +} + +test "orientations move pixels as PIL's transposes do" { + const gpa = std.testing.allocator; + // a 3x2 image of pixel indices: 0 1 2 / 3 4 5 + var px: [18]u8 = undefined; + for (0..6) |i| @memset(px[i * 3 ..][0..3], @intCast(i)); + const src: Rgb = .{ .w = 3, .h = 2, .px = &px }; + const want = [_][]const u8{ &.{ 2, 1, 0, 5, 4, 3 }, &.{ 5, 4, 3, 2, 1, 0 }, &.{ 3, 4, 5, 0, 1, 2 }, &.{ 0, 3, 1, 4, 2, 5 }, &.{ 3, 0, 4, 1, 5, 2 }, &.{ 5, 2, 4, 1, 3, 0 }, &.{ 2, 5, 1, 4, 0, 3 } }; + for (want, 2..) |w, o| { + const out = try orient(gpa, src, @intCast(o)); + defer out.deinit(gpa); + for (w, 0..) |v, i| try std.testing.expectEqual(v, out.px[i * 3]); + } +} + +test "alpha over white follows PIL's DIV255" { + try std.testing.expectEqual(@as(u8, 255), overWhite(0, 0)); + try std.testing.expectEqual(@as(u8, 10), overWhite(10, 255)); + try std.testing.expectEqual(@as(u8, 132), overWhite(10, 128)); // DIV255(255 * 127 + 10 * 128) +} + +test "resize keeps a flat image flat and its size" { + const gpa = std.testing.allocator; + const px = try gpa.alloc(u8, 7 * 5 * 3); + defer gpa.free(px); + @memset(px, 200); + const out = try resize(gpa, .{ .w = 7, .h = 5, .px = px }, 13, 3); + defer out.deinit(gpa); + try std.testing.expectEqual(@as(u32, 13), out.w); + for (out.px) |v| try std.testing.expectEqual(@as(u8, 200), v); +} diff --git a/zig/src/families/glm/mtp.zig b/zig/src/families/glm/mtp.zig index d683c2389f..109ebc91c3 100644 --- a/zig/src/families/glm/mtp.zig +++ b/zig/src/families/glm/mtp.zig @@ -35,6 +35,7 @@ pub fn absorb(x: *fwd.Ctx, e: mtl.ComputeEncoder, h: Ref, next: Ref, rows: u32, const L = &x.w.layers[c.layers]; const m = x.w.mtp.?; fwd.embedRows(x, e, next, sc.m_emb, rows); + fwd.inject(x, e, sc.m_emb, rows, pos + 1); // the head reads each row's next token: an image's rows one place on fwd.rms(x, e, sc.m_emb, m.enorm, sc.m_eh, rows, D, D, 2 * D, c.eps); fwd.rms(x, e, h, m.hnorm, sc.m_eh.at(@as(usize, D) * 2), rows, D, D, 2 * D, c.eps); fwd.qmv(x, e, x.k.qmv_kda_out, sc.m_eh, m.eh_proj, sc.m_x, rows); diff --git a/zig/src/families/glm/prompt.zig b/zig/src/families/glm/prompt.zig index e4f94f0600..007c4f779b 100644 --- a/zig/src/families/glm/prompt.zig +++ b/zig/src/families/glm/prompt.zig @@ -435,7 +435,7 @@ pub fn backbone(p: *const Prompt, x: *fwd.Ctx, e: mtl.ComputeEncoder, ids: Ref, std.debug.assert(x.sc == ss and M <= p.rows); const s = x.skip; // classes a profile leaves out const Class = fwd.Class; - if (s & Class.ends == 0) fwd.embed(x, e, ids, M); + if (s & Class.ends == 0) fwd.embed(x, e, ids, M, pos); const plane = @as(usize, M) * c.hidden * 2; // a trace's capture points: the decode backbone's fwd.snap(x, e, ss.h, plane); var pending = false; @@ -497,6 +497,7 @@ pub fn mtp(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, h: Ref, n const L = &x.w.layers[c.layers]; const m = x.w.mtp.?; fwd.embedRows(x, e, next, p.m_emb, M); + fwd.inject(x, e, p.m_emb, M, pos + 1); // the head reads each row's next token: an image's rows one place on fwd.rms(x, e, p.m_emb, m.enorm, p.m_eh, M, D, D, 2 * D, c.eps); fwd.rms(x, e, h, m.hnorm, p.m_eh.at(@as(usize, D) * 2), M, D, D, 2 * D, c.eps); qmm(p, e, p.m_eh, m.eh_proj, p.m_x, M); diff --git a/zig/src/families/glm/slot_images.zig b/zig/src/families/glm/slot_images.zig new file mode 100644 index 0000000000..f3a0697e48 --- /dev/null +++ b/zig/src/families/glm/slot_images.zig @@ -0,0 +1,37 @@ +//! A stream's images through the tower into the engine's image rows, which its prompt chunks inject over their +//! placeholders (forward.zig's `inject`); the tower remembers whose rows it holds until the pass ends. +const std = @import("std"); +const mtl = @import("metal"); +const vision_mod = @import("vision.zig"); +const Slots = @import("slots.zig").Slots; +const Image = @import("lanes").stream.Image; + +/// Slot `i`'s images through the tower into the engine's image rows, injected over their placeholders by the chunks +/// that follow until `end`. One image a command buffer: the tower's host-written scratch is shared. +pub fn encode(sl: *Slots, i: u32, imgs: []const Image) !void { + const e = sl.e; + const v = e.vision orelse return error.NoVision; + if (imgs.len > e.vision_limits.max_images) return error.TooManyImages; + if (i >= sl.slots.len or !sl.slots[i].used) return error.SlotOutOfStep; + v.spans.clearRetainingCapacity(); + try sl.flush(); + e.sync(); + var row: u32 = 0; + for (imgs) |img| { + if (row + img.tokens > e.vision_limits.image_tokens or img.gh * img.gw != img.tokens * vision_mod.patches_per_token) return error.ImageTooLarge; + if (img.at + img.tokens > sl.slots[i].prompt_len) return error.ImageOutOfPrompt; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const b = e.begin(); + try v.encode(b.enc, img.pixels, img.gh, img.gw, e.vision_rows.at(@as(usize, row) * e.c.hidden * 2), null); + try e.finish(b.cb, b.enc); + try v.spans.append(v.gpa, .{ .at = img.at, .n = img.tokens, .row = row }); + row += img.tokens; + } + v.inject = .{ .slot = i, .v = .{ .rows = e.vision_rows, .spans = v.spans.items } }; +} + +/// The stream's prompt pass is over: the chunks after it inject nothing. +pub fn end(sl: *Slots) void { + if (sl.e.vision) |v| v.inject = null; +} diff --git a/zig/src/families/glm/slots.zig b/zig/src/families/glm/slots.zig index c17d741a88..8693fbcdb3 100644 --- a/zig/src/families/glm/slots.zig +++ b/zig/src/families/glm/slots.zig @@ -330,6 +330,7 @@ pub const Slots = struct { const pool = mtl.objc.Pool.push(); defer pool.pop(); var x = sl.ctx(slot); + x.inject = if (e.vision) |v| v.injected(i) else null; // an image prompt's rows over its placeholders (slot_images.zig) const b = e.begin(); const ids = e.prompt_ids.at(@as(usize, at) * 4); const next = e.prompt_ids.at(@as(usize, at + 1) * 4); diff --git a/zig/src/families/glm/vision.zig b/zig/src/families/glm/vision.zig new file mode 100644 index 0000000000..8a5a410de3 --- /dev/null +++ b/zig/src/families/glm/vision.zig @@ -0,0 +1,541 @@ +//! GLM-5.3-Flash's image tower on the GPU: an image's patches to the rows that replace its `<|image|>` placeholders. +//! mlx-vlm's glm5_next/vision.py (what TensorFold 0.6.6's --vision serves) in bf16: a patch projection, 24 pre-norm +//! blocks (2-D rotary attention over the image's own patches, a clipped SwiGLU), a final norm, the 2x2 merge as a +//! projection of four neighbouring patches, and the merger's projection, layer norm, GELU and clipped SwiGLU. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +const frags = @import("../../core/frags.zig"); +const st = @import("../../core/safetensors.zig"); +const wts = @import("weights.zig"); +const fwd = @import("forward.zig"); +const readAll = @import("weights_fix.zig").readAll; +const Engine = @import("engine.zig").Engine; +const Ref = wts.Ref; + +// The tower this file reads; `Config.parse` refuses a checkpoint whose vision_config differs. +pub const hidden = 1024; +pub const heads = 16; +pub const head_dim = 64; +pub const depth = 24; +pub const mlp_inter = 4096; +pub const out_hidden = 4096; // the language model's width +pub const merger_inter = 10240; +pub const patch = 14; +pub const temporal = 2; +pub const merge = 2; +pub const patch_width = 3 * temporal * patch * patch; // 1176: a patch's values, channel by frame by row by column +pub const patches_per_token = merge * merge; + +/// --vision's limits: image tokens a prompt may hold in all (the tower's scratch and rows are sized for them), and images. +pub const Limits = struct { image_tokens: u32 = 4096, max_images: u32 = 4 }; + +pub const Config = struct { + eps: f32 = 1e-5, + limit: f32 = 10, // swiglu_limit + image_token: u32, + image_start: u32, + image_end: u32, + mean: [3]f32, + std: [3]f32, + min_tokens: u32, + max_tokens: u32, + + /// config.json's vision_config and image token ids, processor_config.json's image processor; null: no tower. + pub fn parse(arena: std.mem.Allocator, config_json: []const u8, processor_json: ?[]const u8) !?Config { + const doc = try std.json.parseFromSliceLeaky(std.json.Value, arena, config_json, .{}); + const vc = doc.object.get("vision_config") orelse return null; + if (vc != .object) return null; + const want = .{ .{ "depth", depth }, .{ "hidden_size", hidden }, .{ "num_heads", heads }, .{ "intermediate_size", mlp_inter }, .{ "out_hidden_size", out_hidden }, .{ "projection_intermediate_size", merger_inter }, .{ "patch_size", patch }, .{ "temporal_patch_size", temporal }, .{ "spatial_merge_size", merge }, .{ "in_channels", 3 } }; + inline for (want) |kv| { + const v = vc.object.get(kv[0]) orelse return error.VisionConfig; + if (v != .integer or v.integer != kv[1]) { + std.log.err("glm vision: vision_config.{s} is {f}; this tower reads {d}", .{ kv[0], std.json.fmt(v, .{}), kv[1] }); + return error.VisionConfig; + } + } + const act = vc.object.get("hidden_act") orelse return error.VisionConfig; + if (act != .string or !std.mem.eql(u8, act.string, "silu")) return error.VisionConfig; + var c: Config = .{ .image_token = 0, .image_start = 0, .image_end = 0, .mean = .{ 0.48145466, 0.4578275, 0.40821073 }, .std = .{ 0.26862954, 0.26130258, 0.27577711 }, .min_tokens = 16, .max_tokens = 8000 }; + if (vc.object.get("rms_norm_eps")) |v| c.eps = @floatCast(number(v) orelse return error.VisionConfig); + if (vc.object.get("swiglu_limit")) |v| c.limit = @floatCast(number(v) orelse return error.VisionConfig); + inline for (.{ .{ "image_token_id", "image_token" }, .{ "image_start_token_id", "image_start" }, .{ "image_end_token_id", "image_end" } }) |kv| { + const v = doc.object.get(kv[0]) orelse return error.VisionConfig; + if (v != .integer) return error.VisionConfig; + @field(c, kv[1]) = @intCast(v.integer); + } + const pj = processor_json orelse return c; + const pdoc = try std.json.parseFromSliceLeaky(std.json.Value, arena, pj, .{}); + const ip = pdoc.object.get("image_processor") orelse return c; + if (ip != .object) return error.VisionConfig; + inline for (.{ .{ "patch_size", patch }, .{ "temporal_patch_size", temporal }, .{ "merge_size", merge } }) |kv| { + if (ip.object.get(kv[0])) |v| if (v != .integer or v.integer != kv[1]) return error.VisionConfig; + } + if (ip.object.get("patch_expand_factor")) |v| if (v != .integer or v.integer != 1) return error.VisionConfig; + inline for (.{ "image_mean", "image_std" }, .{ &c.mean, &c.std }) |key, dst| if (ip.object.get(key)) |v| { + if (v != .array or v.array.items.len != 3) return error.VisionConfig; + for (v.array.items, 0..) |x, i| dst[i] = @floatCast(number(x) orelse return error.VisionConfig); + }; + if (ip.object.get("min_image_tokens")) |v| c.min_tokens = @intCast(v.integer); + if (ip.object.get("max_image_tokens")) |v| c.max_tokens = @intCast(v.integer); + return c; + } + + fn number(v: std.json.Value) ?f64 { + return switch (v) { + .float => |f| f, + .integer => |i| @floatFromInt(i), + else => null, + }; + } +}; + +const Kernels = struct { + lib: mtl.Library, + gemm: [3][2][2]mtl.Pipeline, // [bf16 nt, f32 nt, f32 nn][M % 64 == 0][N % 128 == 0] + bias: mtl.Pipeline, + add: mtl.Pipeline, + rms: mtl.Pipeline, + layer_norm: mtl.Pipeline, + qkv: mtl.Pipeline, + softmax: mtl.Pipeline, + heads_: mtl.Pipeline, + swiglu: mtl.Pipeline, + gelu: mtl.Pipeline, + + fn load(gpa: std.mem.Allocator, device: mtl.Device) !Kernels { + const src = try frags.source(device, gpa, sources.glm_vision); + defer gpa.free(src); + const lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); + var k: Kernels = undefined; + k.lib = lib; + const kinds = [_][]const u8{ "bf16_nt", "f32_nt", "f32_nn" }; + for (kinds, 0..) |kind, ki| for (0..2) |m| for (0..2) |n| { + var name: [64]u8 = undefined; + const full = try std.fmt.bufPrint(&name, "glmv_gemm_{s}_{d}{d}", .{ kind, m, n }); + k.gemm[ki][m][n] = try mtl.Pipeline.init(device, lib, full, false); + }; + inline for (.{ .{ "bias", "glmv_bias" }, .{ "add", "glmv_add" }, .{ "rms", "glmv_rms" }, .{ "layer_norm", "glmv_layer_norm" }, .{ "qkv", "glmv_qkv" }, .{ "softmax", "glmv_softmax" }, .{ "heads_", "glmv_heads" }, .{ "swiglu", "glmv_swiglu" }, .{ "gelu", "glmv_gelu" } }) |kv| { + @field(k, kv[0]) = try mtl.Pipeline.init(device, lib, kv[1], false); + } + return k; + } + + fn deinit(k: *Kernels) void { + for (&k.gemm) |*a| for (a) |*b| for (b) |p| p.deinit(); + inline for (.{ "bias", "add", "rms", "layer_norm", "qkv", "softmax", "heads_", "swiglu", "gelu" }) |f| @field(k, f).deinit(); + k.lib.deinit(); + } +}; + +const Block = struct { norm1: Ref, norm2: Ref, qkv_w: Ref, qkv_b: Ref, proj_w: Ref, proj_b: Ref, q_norm: Ref, k_norm: Ref, gate_w: Ref, gate_b: Ref, up_w: Ref, up_b: Ref, down_w: Ref, down_b: Ref }; + +const Weights = struct { + buf: mtl.Buffer, + patch_w: Ref, + patch_b: Ref, + blocks: [depth]Block, + post_norm: Ref, + down_w: Ref, // [4096, 2, 2, 1024]: the merge's kernel with its taps outermost, as four neighbouring patch rows read it + down_b: Ref, + m_proj: Ref, + m_norm_w: Ref, + m_norm_b: Ref, + m_gate: Ref, + m_up: Ref, + m_down: Ref, +}; + +/// The tower: kernels, weights (bf16, about 0.9 GiB) and scratch for `max_tokens` image tokens a request. +pub const Vision = struct { + gpa: std.mem.Allocator, + inject: ?struct { slot: u32, v: fwd.Inject } = null, // an image prompt's rows while its pass runs (slot_images.zig) + spans: std.ArrayList(fwd.Span) = .empty, + c: Config, + k: Kernels, + w: Weights, + scratch: mtl.Buffer, + max_patches: u32, + chunk: u32, // query rows an attention pass scores at once (bounds the fp32 score buffer) + // scratch views + patches: Ref, // [P, 1176] bf16 + cos: Ref, // [P, 64] f32 + sin: Ref, + x: Ref, // [P, 1024] bf16: the residual stream + xn: Ref, // [P, 1024]: a norm's output; the merger's first [T, 4096] + att: Ref, // [P, 1024]: heads side by side; the merger's second [T, 4096] + branch: Ref, // [P, 1024] + qkv: Ref, // [P, 3072] + q: Ref, // [16, P, 64] f32 + k_: Ref, + v: Ref, + s: Ref, // [16, chunk, P] f32 + o: Ref, // [16, chunk, 64] f32 + g: Ref, // [P, 4096] bf16 (the merger's [T, 10240] fits: T * 10240 < P * 4096) + u: Ref, + act: Ref, + bytes: usize, + + pub fn load(gpa: std.mem.Allocator, device: mtl.Device, dir: []const u8, c: Config, max_tokens: u32) !*Vision { + const v = try gpa.create(Vision); + errdefer gpa.destroy(v); + v.gpa = gpa; + v.inject = null; + v.spans = .empty; + v.c = c; + v.k = try Kernels.load(gpa, device); + errdefer v.k.deinit(); + v.w = try loadWeights(gpa, device, dir); + errdefer v.w.buf.deinit(); + const P: usize = @as(usize, max_tokens) * patches_per_token; + v.max_patches = @intCast(P); + // the scores take at most 256 MiB: 16 heads of `chunk` rows by P keys in fp32 + v.chunk = @intCast(std.math.clamp((256 << 20) / (heads * P * 4) / 64 * 64, 64, 4096)); + const parts = [_]usize{ P * patch_width * 2, P * 64 * 4, P * 64 * 4, P * hidden * 2, P * hidden * 2, P * hidden * 2, P * hidden * 2, P * 3 * hidden * 2, P * hidden * 4, P * hidden * 4, P * hidden * 4, @as(usize, heads) * v.chunk * P * 4, @as(usize, heads) * v.chunk * head_dim * 4, P * mlp_inter * 2, P * mlp_inter * 2, P * mlp_inter * 2 }; + var total: usize = 0; + for (parts) |n| total += std.mem.alignForward(usize, n, 256); + v.scratch = try device.buffer(total, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + errdefer v.scratch.deinit(); + var at: usize = 0; + const views = [_]*Ref{ &v.patches, &v.cos, &v.sin, &v.x, &v.xn, &v.att, &v.branch, &v.qkv, &v.q, &v.k_, &v.v, &v.s, &v.o, &v.g, &v.u, &v.act }; + for (views, parts) |view, n| { + view.* = .{ .buf = v.scratch, .off = at }; + at += std.mem.alignForward(usize, n, 256); + } + v.bytes = total + v.w.buf.length(); + return v; + } + + pub fn deinit(v: *Vision) void { + v.spans.deinit(v.gpa); + v.scratch.deinit(); + v.w.buf.deinit(); + v.k.deinit(); + v.gpa.destroy(v); + } + + /// Slot `i`'s image rows for its prompt pass, while its images' pass runs; null for any other slot. + pub fn injected(v: *const Vision, i: u32) ?*const fwd.Inject { + if (v.inject) |*inj| if (inj.slot == i) return &inj.v; + return null; + } + + /// Buffers to keep resident with the engine's. + pub fn buffers(v: *const Vision) [2]mtl.Buffer { + return .{ v.w.buf, v.scratch }; + } + + /// One image's patches ([gh * gw, 1176] fp32, the processor's order) into its tokens' rows `out` ([gh * gw / 4, + /// 4096] bf16). The host writes the scratch: the caller has no work of this tower in flight. `stop`: after the + /// patch projection (0) or block `stop` (1-24), the residual stream is left in `x` and nothing more runs. + pub fn encode(v: *Vision, enc: mtl.ComputeEncoder, pixels: []const f32, gh: u32, gw: u32, out: Ref, stop: ?u32) !void { + const P: u32 = gh * gw; + if (P == 0 or gh % merge != 0 or gw % merge != 0) return error.ImageGrid; + if (P > v.max_patches) return error.ImageTooLarge; + if (pixels.len != @as(usize, P) * patch_width) return error.ImageGrid; + const T: u32 = P / patches_per_token; + // host: the patches in bf16 (MLX's astype), and each patch's rotary angles + const dst: [*]u16 = @ptrCast(@alignCast(v.patches.addr())); + for (pixels, 0..) |p, i| dst[i] = bf16(p); + rotary(v, gh, gw); + + v.gemmLinear(enc, v.patches, v.w.patch_w, v.x, P, hidden, patch_width); + v.biasAdd(enc, v.x, v.w.patch_b, P, hidden); + if (stop) |s| if (s == 0) return; + for (v.w.blocks, 0..) |b, i| { + v.block(enc, b, P); + if (stop) |s| if (s == i + 1) return; + } + v.rms(enc, v.x, v.w.post_norm, v.xn, P, hidden); + // the merge: four neighbouring patches' rows are one row of xn read as [T, 4096] + const m0 = v.xn; + const m1 = v.att; + v.gemmLinear(enc, m0, v.w.down_w, m1, T, out_hidden, patches_per_token * hidden); + v.biasAdd(enc, m1, v.w.down_b, T, out_hidden); + v.gemmLinear(enc, m1, v.w.m_proj, m0, T, out_hidden, out_hidden); + v.layerNorm(enc, m0, v.w.m_norm_w, v.w.m_norm_b, m1, T, out_hidden); + enc.setPipeline(v.k.gelu); + enc.setBuffer(m1.buf, m1.off, 0); + enc.dispatchThreads(mtl.Size.of(@as(usize, T) * out_hidden, 1, 1), mtl.Size.of(256, 1, 1)); + v.gemmLinear(enc, m1, v.w.m_gate, v.g, T, merger_inter, out_hidden); + v.gemmLinear(enc, m1, v.w.m_up, v.u, T, merger_inter, out_hidden); + v.swiglu(enc, @as(usize, T) * merger_inter); + v.gemmLinear(enc, v.act, v.w.m_down, out, T, out_hidden, merger_inter); + } + + fn block(v: *Vision, enc: mtl.ComputeEncoder, b: Block, P: u32) void { + v.rms(enc, v.x, b.norm1, v.xn, P, hidden); + v.gemmLinear(enc, v.xn, b.qkv_w, v.qkv, P, 3 * hidden, hidden); + v.biasAdd(enc, v.qkv, b.qkv_b, P, 3 * hidden); + enc.setPipeline(v.k.qkv); + const bufs = [_]Ref{ v.qkv, b.q_norm, b.k_norm, v.cos, v.sin, v.q, v.k_, v.v }; + for (bufs, 0..) |r, i| enc.setBuffer(r.buf, r.off, i); + enc.setValue(extern struct { L: u32, eps: f32 }{ .L = P, .eps = v.c.eps }, 8); + enc.dispatchGroups(mtl.Size.of(@as(usize, P) * heads * 3, 1, 1), mtl.Size.of(32, 1, 1)); + var q0: u32 = 0; + while (q0 < P) : (q0 += v.chunk) { + const lc = @min(v.chunk, P - q0); + // scores of this chunk's queries against every key, each head a batch + v.gemm(enc, 1, v.q.at(@as(usize, q0) * head_dim * 4), v.k_, v.s, lc, P, head_dim, head_dim, head_dim, P, heads, @as(usize, P) * head_dim, @as(usize, P) * head_dim, @as(usize, lc) * P); + enc.setPipeline(v.k.softmax); + enc.setBuffer(v.s.buf, v.s.off, 0); + enc.setValue(P, 1); + enc.setValue(@as(f32, 0.125), 2); // head_dim ** -0.5 + enc.dispatchGroups(mtl.Size.of(@as(usize, heads) * lc, 1, 1), mtl.Size.of(256, 1, 1)); + v.gemm(enc, 2, v.s, v.v, v.o, lc, head_dim, P, P, head_dim, head_dim, heads, @as(usize, lc) * P, @as(usize, P) * head_dim, @as(usize, lc) * head_dim); + enc.setPipeline(v.k.heads_); + enc.setBuffer(v.o.buf, v.o.off, 0); + enc.setBuffer(v.att.buf, v.att.off, 1); + enc.setValue([2]u32{ lc, q0 }, 2); + enc.dispatchThreads(mtl.Size.of(hidden, lc, 1), mtl.Size.of(256, 1, 1)); + } + v.gemmLinear(enc, v.att, b.proj_w, v.branch, P, hidden, hidden); + v.biasAdd(enc, v.branch, b.proj_b, P, hidden); + v.add(enc, v.x, v.branch, @as(usize, P) * hidden); + v.rms(enc, v.x, b.norm2, v.xn, P, hidden); + v.gemmLinear(enc, v.xn, b.gate_w, v.g, P, mlp_inter, hidden); + v.biasAdd(enc, v.g, b.gate_b, P, mlp_inter); + v.gemmLinear(enc, v.xn, b.up_w, v.u, P, mlp_inter, hidden); + v.biasAdd(enc, v.u, b.up_b, P, mlp_inter); + v.swiglu(enc, @as(usize, P) * mlp_inter); + v.gemmLinear(enc, v.act, b.down_w, v.branch, P, hidden, mlp_inter); + v.biasAdd(enc, v.branch, b.down_b, P, hidden); + v.add(enc, v.x, v.branch, @as(usize, P) * hidden); + } + + /// y [M, N] = x [M, K] w^T in bf16 (w as stored, [N, K]). + fn gemmLinear(v: *Vision, enc: mtl.ComputeEncoder, x: Ref, w: Ref, y: Ref, M: u32, N: u32, K: u32) void { + v.gemm(enc, 0, x, w, y, M, N, K, K, K, N, 1, 0, 0, 0); + } + + /// tfp::gemm_nax: d [batch, M, N] = a x b (kind 0: bf16 a b^T, 1: fp32 a b^T, 2: fp32 a b), batches `s*` elements apart. + fn gemm(v: *Vision, enc: mtl.ComputeEncoder, kind: usize, a: Ref, b: Ref, d: Ref, M: u32, N: u32, K: u32, lda: u32, ldb: u32, ldd: u32, batch: u32, sa: usize, sb: usize, sd: usize) void { + const tn = (N + 127) / 128; + const tm = (M + 63) / 64; + enc.setPipeline(v.k.gemm[kind][@intFromBool(M % 64 == 0)][@intFromBool(N % 128 == 0)]); + enc.setBuffer(a.buf, a.off, 0); + enc.setBuffer(b.buf, b.off, 1); + var p: [16]i32 = @splat(0); + const vals = [_]usize{ M, N, K, lda, ldb, ldd, tn, tm, 2, K / 256, sa, sb, sd, 0, 0 }; + for (vals, 0..) |x, i| p[i] = @intCast(x); + enc.setBytes(std.mem.asBytes(&p), 2); + enc.setBuffer(d.buf, d.off, 3); + enc.dispatchThreads(mtl.Size.of(@as(usize, tn << 2) * 32, (tm + 3) / 4 * 4, @as(usize, batch) * 2), mtl.Size.of(32, 4, 2)); + } + + fn biasAdd(v: *Vision, enc: mtl.ComputeEncoder, y: Ref, b: Ref, rows: u32, width: u32) void { + enc.setPipeline(v.k.bias); + enc.setBuffer(y.buf, y.off, 0); + enc.setBuffer(b.buf, b.off, 1); + enc.setValue(width, 2); + enc.dispatchThreads(mtl.Size.of(width, rows, 1), mtl.Size.of(256, 1, 1)); + } + + fn add(v: *Vision, enc: mtl.ComputeEncoder, x: Ref, y: Ref, n: usize) void { + enc.setPipeline(v.k.add); + enc.setBuffer(x.buf, x.off, 0); + enc.setBuffer(y.buf, y.off, 1); + enc.dispatchThreads(mtl.Size.of(n, 1, 1), mtl.Size.of(256, 1, 1)); + } + + fn rms(v: *Vision, enc: mtl.ComputeEncoder, x: Ref, w: Ref, y: Ref, rows: u32, width: u32) void { + enc.setPipeline(v.k.rms); + enc.setBuffer(x.buf, x.off, 0); + enc.setBuffer(w.buf, w.off, 1); + enc.setBuffer(y.buf, y.off, 2); + enc.setValue(extern struct { rows: u32, width: u32, eps: f32 }{ .rows = rows, .width = width, .eps = v.c.eps }, 3); + enc.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + } + + fn layerNorm(v: *Vision, enc: mtl.ComputeEncoder, x: Ref, w: Ref, b: Ref, y: Ref, rows: u32, width: u32) void { + enc.setPipeline(v.k.layer_norm); + const bufs = [_]Ref{ x, w, b, y }; + for (bufs, 0..) |r, i| enc.setBuffer(r.buf, r.off, i); + enc.setValue(extern struct { rows: u32, width: u32, eps: f32 }{ .rows = rows, .width = width, .eps = 1e-5 }, 4); + enc.dispatchGroups(mtl.Size.of(rows, 1, 1), mtl.Size.of(256, 1, 1)); + } + + fn swiglu(v: *Vision, enc: mtl.ComputeEncoder, n: usize) void { + enc.setPipeline(v.k.swiglu); + enc.setBuffer(v.g.buf, v.g.off, 0); + enc.setBuffer(v.u.buf, v.u.off, 1); + enc.setBuffer(v.act.buf, v.act.off, 2); + enc.setValue(v.c.limit, 3); + enc.dispatchThreads(mtl.Size.of(n, 1, 1), mtl.Size.of(256, 1, 1)); + } +}; + +/// fp32 to bf16, round to nearest even (MLX's astype). +pub fn bf16(x: f32) u16 { + const b: u32 = @bitCast(x); + if (b & 0x7fffffff > 0x7f800000) return @truncate((b >> 16) | 0x40); // NaN stays NaN + return @truncate((b + 0x7fff + ((b >> 16) & 1)) >> 16); +} + +/// Each patch's 2-D rotary angles as vision.py builds them: the patch's row then column in the image's patch grid +/// (patches come in 2x2 merge windows, row-major windows), times the 16 frequencies 10000^(-k/16), cos and sin of +/// [h * f, w * f] twice over a head's 64 values. +fn rotary(v: *Vision, gh: u32, gw: u32) void { + var inv: [16]f32 = undefined; + for (&inv, 0..) |*f, k| f.* = 1.0 / @as(f32, @floatCast(std.math.pow(f64, 10000.0, @as(f64, @floatFromInt(2 * k)) / 32.0))); + const cs: [*]f32 = @ptrCast(@alignCast(v.cos.addr())); + const sn: [*]f32 = @ptrCast(@alignCast(v.sin.addr())); + const wx_n = gw / merge; + var i: usize = 0; + var wy: u32 = 0; + while (wy < gh / merge) : (wy += 1) { + var wx: u32 = 0; + while (wx < wx_n) : (wx += 1) { + for (0..merge) |my| for (0..merge) |mx| { + const h: f32 = @floatFromInt(wy * merge + my); + const w: f32 = @floatFromInt(wx * merge + mx); + for (0..32) |j| { + const angle: f32 = if (j < 16) h * inv[j] else w * inv[j - 16]; + const c: f32 = @floatCast(@cos(@as(f64, angle))); + const s: f32 = @floatCast(@sin(@as(f64, angle))); + cs[i * 64 + j] = c; + cs[i * 64 + j + 32] = c; + sn[i * 64 + j] = s; + sn[i * 64 + j + 32] = s; + } + i += 1; + }; + } + } +} + +/// model.visual.* from the checkpoint's shards into one buffer, the merge kernel's taps moved outermost. +fn loadWeights(gpa: std.mem.Allocator, device: mtl.Device, dir: []const u8) !Weights { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const Src = struct { path: [:0]const u8, off: u64, len: u64, dtype: st.DType, shape: []const usize }; + var names: std.StringHashMapUnmanaged(Src) = .empty; + { + const path = try std.fmt.allocPrintSentinel(arena, "{s}/model.safetensors.index.json", .{dir}, 0); + const f = try mtl.MappedFile.open(path); + defer f.deinit(); + const doc = try std.json.parseFromSliceLeaky(std.json.Value, arena, f.bytes[0..f.size], .{ .allocate = .alloc_always }); + var files: std.StringArrayHashMapUnmanaged(void) = .empty; + var it = doc.object.get("weight_map").?.object.iterator(); + while (it.next()) |kv| if (std.mem.startsWith(u8, kv.key_ptr.*, "model.visual.")) try files.put(arena, kv.value_ptr.string, {}); + if (files.count() == 0) return error.NoVisionTower; + for (files.keys()) |name| { + const full = try std.fmt.allocPrintSentinel(arena, "{s}/{s}", .{ dir, name }, 0); + const fd = std.c.open(full, .{ .ACCMODE = .RDONLY }); + if (fd < 0) return error.OpenFailed; + defer _ = std.c.close(fd); + var head: [8]u8 = undefined; + try readAll(fd, &head, 0); + const hlen = std.mem.readInt(u64, &head, .little); + const header = try arena.alloc(u8, hlen); + try readAll(fd, header, 8); + const end: u64 = @intCast(std.c.lseek(fd, 0, std.c.SEEK.END)); + // read here, not by core/safetensors.zig: the patch kernel is 5-D, past its max_rank + const doc2 = try std.json.parseFromSliceLeaky(std.json.Value, arena, header, .{}); + var eit = doc2.object.iterator(); + while (eit.next()) |kv| { + if (!std.mem.startsWith(u8, kv.key_ptr.*, "model.visual.")) continue; + const o = kv.value_ptr.object; + const dtype = st.DType.parse(o.get("dtype").?.string) orelse return error.UnsupportedDType; + const dims = o.get("shape").?.array.items; + const shape = try arena.alloc(usize, dims.len); + var n: u64 = dtype.size(); + for (dims, shape) |d, *s| { + s.* = @intCast(d.integer); + n *= s.*; + } + const offs = o.get("data_offsets").?.array.items; + const b: u64 = @intCast(offs[0].integer); + const e: u64 = @intCast(offs[1].integer); + if (e < b or e - b != n or 8 + hlen + e > end) return error.BadSafetensors; + try names.put(arena, kv.key_ptr.*, .{ .path = full, .off = 8 + hlen + b, .len = e - b, .dtype = dtype, .shape = shape }); + } + } + } + // every tensor's place in one buffer, 256-aligned + const Want = struct { name: []const u8, shape: []const usize, ref: *Ref }; + var w: Weights = undefined; + var wants: std.ArrayList(Want) = .empty; + try wants.append(arena, .{ .name = "patch_embed.proj.weight", .shape = &.{ hidden, 3, temporal, patch, patch }, .ref = &w.patch_w }); + try wants.append(arena, .{ .name = "patch_embed.proj.bias", .shape = &.{hidden}, .ref = &w.patch_b }); + for (&w.blocks, 0..) |*b, i| { + const fields = .{ .{ "norm1.weight", &b.norm1, &[_]usize{hidden} }, .{ "norm2.weight", &b.norm2, &[_]usize{hidden} }, .{ "attn.qkv.weight", &b.qkv_w, &[_]usize{ 3 * hidden, hidden } }, .{ "attn.qkv.bias", &b.qkv_b, &[_]usize{3 * hidden} }, .{ "attn.proj.weight", &b.proj_w, &[_]usize{ hidden, hidden } }, .{ "attn.proj.bias", &b.proj_b, &[_]usize{hidden} }, .{ "attn.q_norm.weight", &b.q_norm, &[_]usize{head_dim} }, .{ "attn.k_norm.weight", &b.k_norm, &[_]usize{head_dim} }, .{ "mlp.gate_proj.weight", &b.gate_w, &[_]usize{ mlp_inter, hidden } }, .{ "mlp.gate_proj.bias", &b.gate_b, &[_]usize{mlp_inter} }, .{ "mlp.up_proj.weight", &b.up_w, &[_]usize{ mlp_inter, hidden } }, .{ "mlp.up_proj.bias", &b.up_b, &[_]usize{mlp_inter} }, .{ "mlp.down_proj.weight", &b.down_w, &[_]usize{ hidden, mlp_inter } }, .{ "mlp.down_proj.bias", &b.down_b, &[_]usize{hidden} } }; + inline for (fields) |f| try wants.append(arena, .{ .name = try std.fmt.allocPrint(arena, "blocks.{d}.{s}", .{ i, f[0] }), .shape = f[2], .ref = f[1] }); + } + try wants.append(arena, .{ .name = "post_layernorm.weight", .shape = &.{hidden}, .ref = &w.post_norm }); + try wants.append(arena, .{ .name = "downsample.weight", .shape = &.{ out_hidden, hidden, merge, merge }, .ref = &w.down_w }); + try wants.append(arena, .{ .name = "downsample.bias", .shape = &.{out_hidden}, .ref = &w.down_b }); + try wants.append(arena, .{ .name = "merger.proj.weight", .shape = &.{ out_hidden, out_hidden }, .ref = &w.m_proj }); + try wants.append(arena, .{ .name = "merger.post_projection_norm.weight", .shape = &.{out_hidden}, .ref = &w.m_norm_w }); + try wants.append(arena, .{ .name = "merger.post_projection_norm.bias", .shape = &.{out_hidden}, .ref = &w.m_norm_b }); + try wants.append(arena, .{ .name = "merger.gate_proj.weight", .shape = &.{ merger_inter, out_hidden }, .ref = &w.m_gate }); + try wants.append(arena, .{ .name = "merger.up_proj.weight", .shape = &.{ merger_inter, out_hidden }, .ref = &w.m_up }); + try wants.append(arena, .{ .name = "merger.down_proj.weight", .shape = &.{ out_hidden, merger_inter }, .ref = &w.m_down }); + const srcs = try arena.alloc(Src, wants.items.len); + var total: usize = 0; + for (wants.items, srcs) |want, *s| { + const full = try std.fmt.allocPrint(arena, "model.visual.{s}", .{want.name}); + s.* = names.get(full) orelse { + std.log.err("glm vision: the checkpoint has no tensor {s}", .{full}); + return error.MissingTensor; + }; + if (s.dtype != .bf16 or !std.mem.eql(usize, s.shape, want.shape)) { + std.log.err("glm vision: {s} is {t} {any}; the tower reads bf16 {any}", .{ full, s.dtype, s.shape, want.shape }); + return error.UnexpectedTensor; + } + total = std.mem.alignForward(usize, total, 256) + s.len; + } + w.buf = try device.buffer(total, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + errdefer w.buf.deinit(); + var at: usize = 0; + for (wants.items, srcs) |want, s| { + at = std.mem.alignForward(usize, at, 256); + want.ref.* = .{ .buf = w.buf, .off = at }; + const fd = std.c.open(s.path, .{ .ACCMODE = .RDONLY }); + if (fd < 0) return error.OpenFailed; + defer _ = std.c.close(fd); + _ = std.c.fcntl(fd, 48, @as(c_int, 1)); // F_NOCACHE, as the language model's shards + const dst = w.buf.contents()[at..][0..s.len]; + try readAll(fd, dst, s.off); + at += s.len; + } + // downsample [O, C, 2, 2] -> [O, 2, 2, C]: a merge window's four patch rows, tap by tap + const dw: [*]u16 = @ptrCast(@alignCast(w.down_w.addr())); + const tmp = try gpa.alloc(u16, hidden * merge * merge); + defer gpa.free(tmp); + for (0..out_hidden) |o| { + const row = dw[o * hidden * 4 ..][0 .. hidden * 4]; + @memcpy(tmp, row); + for (0..hidden) |ch| for (0..4) |tap| { + row[tap * hidden + ch] = tmp[ch * 4 + tap]; + }; + } + return w; +} + +/// `e` reads images: the tower loaded beside its weights (about 0.9 GiB with scratch for `lim.image_tokens` image +/// tokens a prompt) and the rows a prompt's images fill; `config` is the checkpoint's config.json. +pub fn attach(e: *Engine, gpa: std.mem.Allocator, dir: []const u8, config: []const u8, lim: Limits) !void { + if (e.ep != null) return error.VisionOnPair; + const pj: ?mtl.MappedFile = blk: { + const pp = try std.fmt.allocPrintSentinel(gpa, "{s}/processor_config.json", .{dir}, 0); + defer gpa.free(pp); + break :blk mtl.MappedFile.open(pp) catch null; + }; + defer if (pj) |m| m.deinit(); + var cfg_arena = std.heap.ArenaAllocator.init(gpa); + defer cfg_arena.deinit(); + const vc = (try Config.parse(cfg_arena.allocator(), config, if (pj) |m| m.bytes[0..m.size] else null)) orelse return error.NoVisionTower; + e.vision = try Vision.load(gpa, e.device, dir, vc, lim.image_tokens); + e.vision_rows = try e.arena.buffer(@as(usize, lim.image_tokens) * e.c.hidden * 2); + e.vision_limits = lim; + std.log.info("glm: image tower loaded ({d:.2} GiB with scratch for {d} image tokens a prompt)", .{ @as(f64, @floatFromInt(e.vision.?.bytes)) / (1 << 30), lim.image_tokens }); +} + +test "bf16 rounds to nearest even" { + try std.testing.expectEqual(@as(u16, 0x3f80), bf16(1.0)); + try std.testing.expectEqual(@as(u16, 0x3f80), bf16(@bitCast(@as(u32, 0x3f808000)))); // a tie to even (down) + try std.testing.expectEqual(@as(u16, 0x3f82), bf16(@bitCast(@as(u32, 0x3f818000)))); // a tie to even (up) + try std.testing.expectEqual(@as(u16, 0x3f81), bf16(@bitCast(@as(u32, 0x3f808001)))); +} diff --git a/zig/src/native/glm_host.zig b/zig/src/native/glm_host.zig index e7e9ed8f4d..ca4ac66cad 100644 --- a/zig/src/native/glm_host.zig +++ b/zig/src/native/glm_host.zig @@ -16,6 +16,7 @@ pub const Host = struct { eng: *ge.Engine, slots: glm.slots.Slots, back: glm.backend.Backend, + markers: [3]u32 = undefined, // the image wrapper's tokens (--vision): begin, image, end cfg: lanes.Config, wall: lanes.backend.WallClock, core: lanes.Engine, @@ -79,8 +80,9 @@ fn learnedStates(gpa: Allocator, eng: *const ge.Engine, sl: *glm.slots.Slots, ro } /// A GLM-5.3-Flash checkpoint served: `window` tokens of cache a stream, warmed first (the pair: `speed_up`). -pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: ?[]const u8, streams: u32, fixed: bool, cache_gib: ?f64, learn: ?[]const u8, learn_cap: u64, learn_floor: u64) !*Host { - const eng = try ge.Engine.loadWith(gpa, dir, window + 64, speed_up, learn != null); +pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: ?[]const u8, streams: u32, fixed: bool, cache_gib: ?f64, learn: ?[]const u8, learn_cap: u64, learn_floor: u64, vision: ?api.VisionOpen) !*Host { + const limits: ?glm.vision.Limits = if (vision) |v| .{ .image_tokens = v.image_tokens, .max_images = v.max_images } else null; + const eng = try ge.Engine.loadWith(gpa, dir, window + 64, speed_up, learn != null, limits); errdefer eng.deinit(); var toks: [96]u32 = undefined; for (&toks, 0..) |*t, i| t.* = @intCast(1000 + i); @@ -103,7 +105,8 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: h.wall = .{ .io = io }; h.core = lanes.Engine.init(gpa, &h.cfg, h.back.backend(), h.wall.clock()); errdefer h.core.deinit(); - h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "glm-zig", .lanes = n, .context_window = window, .prefill_step = eng.chunk_rows, .greedy_only = true, .admit = if (h.slots.pool != null) .{ .ctx = &h.back, .fits = glm.backend.Backend.fits } else null }); + if (eng.vision) |v| h.markers = .{ v.c.image_start, v.c.image_token, v.c.image_end }; + h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "glm-zig", .lanes = n, .context_window = window, .prefill_step = eng.chunk_rows, .greedy_only = true, .admit = if (h.slots.pool != null) .{ .ctx = &h.back, .fits = glm.backend.Backend.fits } else null, .vision = if (eng.vision) |v| .{ .ctx = h, .prepare = prepareImage, .image_token = v.c.image_token, .markers = &h.markers, .image_tokens = eng.vision_limits.image_tokens, .max_images = eng.vision_limits.max_images } else null }); h.cache = null; const budget = cacheBudget(eng, cache_gib); if (!eng.followsPeer() and budget > 0) { @@ -133,6 +136,13 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: return h; } +/// Info.vision's prepare: an image's bytes to the tower's patches (families/glm/image.zig), on the HTTP thread. +fn prepareImage(ctx: *anyopaque, a: Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage { + const h: *Host = @ptrCast(@alignCast(ctx)); + const p = try glm.image.prepare(a, bytes, h.eng.vision.?.c, max_tokens); + return .{ .pixels = p.pixels, .gh = p.gh, .gw = p.gw, .tokens = p.tokens, .hash = p.hash }; +} + fn follow(h: *Host) void { glm.mirror.follow(h.eng, &h.slots) catch |err| std.log.err("speed-up mode: following rank 0 ended: {s}", .{@errorName(err)}); } diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index eb02076946..a8e0283e6c 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -107,6 +107,10 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c if (dense) return openQwen27(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "qwen4_exp")) return openFlashNext(a, gpa, io, o, problem); if (std.mem.eql(u8, o.model_type, "glm5_next")) return openGlm(a, gpa, io, o, problem); + if (o.vision != null) { + problem.* = try std.fmt.allocPrint(a, "--vision: the native engine reads images for GLM-5.3-Flash only, not {s} checkpoints", .{o.model_type}); + return null; + } if (std.mem.eql(u8, o.model_type, "qwen3_5")) return @import("qwen35.zig").open(a, gpa, io, o, problem); if (!std.mem.eql(u8, o.model_type, "nemotron_h")) { problem.* = try std.fmt.allocPrint(a, "the native engine has no backend for {s} checkpoints yet; the Python engine 0.6.6 may serve them: python -m pip install git+https://github.com/ashhart/TensorFold.git@v0.6.6", .{o.model_type}); @@ -337,7 +341,11 @@ fn openGlm(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]co } const pool = mtl.objc.Pool.push(); defer pool.pop(); - const h = glm.open(gpa, io, o.dir, @intCast(window), o.speed_up, o.lanes, o.lanes_fixed, o.prompt_cache_gib, o.learn, @intFromFloat(o.learn_gib * (1 << 30)), @intFromFloat(o.learn_min_free_gib * (1 << 30))) catch |e| { + if (o.vision != null and o.speed_up != null) { + problem.* = try std.fmt.allocPrint(a, "--vision is served on one Mac; the --speed-up pair reads text only", .{}); + return null; + } + const h = glm.open(gpa, io, o.dir, @intCast(window), o.speed_up, o.lanes, o.lanes_fixed, o.prompt_cache_gib, o.learn, @intFromFloat(o.learn_gib * (1 << 30)), @intFromFloat(o.learn_min_free_gib * (1 << 30)), o.vision) catch |e| { if (e == error.BadLoadLimit) problem.* = "GLM_LOAD_LIMIT_GB is not a load limit: give a number of GB above 0, or unset it for 70% of RAM" else problem.* = if (linkProblem(e)) |link| try std.fmt.allocPrint(a, "the native GLM-5.3-Flash engine cannot load {s}: {s}", .{ o.dir, link }) else try std.fmt.allocPrint(a, "the native GLM-5.3-Flash engine cannot load {s} ({s})", .{ o.dir, @errorName(e) }); return null; }; diff --git a/zig/src/server/anthropic.zig b/zig/src/server/anthropic.zig index 4821e0f3eb..41f7adb038 100644 --- a/zig/src/server/anthropic.zig +++ b/zig/src/server/anthropic.zig @@ -51,7 +51,7 @@ fn countTokens(srv: *Server, cx: *Cx, chat: Value) errors.Refused!usize { const thinking = try fields.thinkingFields(cx, chat, srv.effort_levels); const on = thinking.enable orelse srv.config.enable_thinking; const tools = try tool_specs.active(cx, chat.get("tools"), chat.get("tool_choice")); - const msgs = try messages_mod.normalize(cx, chat.get("messages"), "system", srv.needs_user_after_tool); + const msgs = try messages_mod.normalizeWith(cx, chat.get("messages"), "system", srv.needs_user_after_tool, srv.info.vision != null); const ids_ = prompt.renderIds(srv, cx, msgs, tools, on, srv.effortFor(thinking.effort), true) catch |e| switch (e) { error.Refused => return cx.other(cx.message), else => |x| return x, diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 6315e32991..76c65ec12c 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -193,6 +193,8 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa .decode_spans = try prompt_mod.replySpans(srv, cx, rendered.ids), // from the tokens alone, for every request: cached states are keyed by tokens .tools_json = if (input.tools.len > 0) try json.stringify(a, .{ .array = @constCast(input.tools) }, .{ .ascii = false }) else "", .decide = if (input.prompt == null and !background) prompt_mod.decideOf(srv, rendered.ids) else null, + .images = rendered.images, + .cache_key = rendered.cache_key, }; try srv.checkFeatures(cx, f, input.tools.len > 0, thinking, rendered.ids, input.tools, &request); if (thinking) { @@ -279,35 +281,6 @@ pub fn release(srv: *Server, preparing: bool) void { if (preparing) _ = srv.preparing.fetchSub(1, .acq_rel); } -/// The text a stream has sent: Python's ``streamed = visible``, grown by its delta while it only grows. -const Shown = struct { - text: std.ArrayList(u8) = .empty, - chars: usize = 0, - at: ?[*]const u8 = null, // where the last shown text lay; the decode buffer only grows, so that prefix holds - extends: bool = false, - - /// Python's ``now[len(shown):]``; ``stable``: ``now`` lies in the append-only decode buffer. - fn after(s: *Shown, now: []const u8, stable: bool) []const u8 { - const sent = s.text.items; - s.extends = (stable and s.at == now.ptr and now.len >= sent.len) or std.mem.startsWith(u8, now, sent); - if (!s.extends) return reply_text.afterChars(now, s.chars); - if (stable) s.at = now.ptr; // the buffer moved but kept its bytes: the next check is free again - return now[sent.len..]; - } - - fn set(s: *Shown, a: Allocator, now: []const u8, delta: []const u8) Allocator.Error!void { - if (s.extends) { - try s.text.appendSlice(a, delta); - s.chars += reply_text.charCount(delta); - } else { - s.text = .empty; - try s.text.appendSlice(a, now); - s.chars = reply_text.charCount(now); - } - s.at = now.ptr; - } -}; - /// The token loop and the text it streams. const Generation = struct { srv: *Server, @@ -325,8 +298,8 @@ const Generation = struct { collected: std.ArrayList(u32) = .empty, visible: reply_text.Incremental = .{}, hidden: std.ArrayList(u8) = .empty, // reused for the answer without its call blocks - streamed: Shown = .{}, // what content streamed, kept apart from the decode buffer that grows under slices - streamed_reasoning: Shown = .{}, + streamed: reply_text.Shown = .{}, // what content streamed, kept apart from the decode buffer that grows under slices + streamed_reasoning: reply_text.Shown = .{}, streaming_done: bool = false, first_ns: ?i96 = null, last_ns: ?i96 = null, diff --git a/zig/src/server/cli.zig b/zig/src/server/cli.zig index 40ee1e0ee8..c30c26a1d4 100644 --- a/zig/src/server/cli.zig +++ b/zig/src/server/cli.zig @@ -49,11 +49,11 @@ pub const flags = [_]Flag{ .{ .name = "--api-key-file", .native = true }, .{ .name = "--metrics-open", .kind = .store_true, .native = true }, .{ .name = "--dashboard", .kind = .store_true, .native = true }, - .{ .name = "--vision", .kind = .store_true }, + .{ .name = "--vision", .kind = .store_true, .native = true }, .{ .name = "--vision-urls", .kind = .store_true }, .{ .name = "--vision-offload", .kind = .store_true }, - .{ .name = "--vision-max-images" }, - .{ .name = "--vision-image-tokens" }, + .{ .name = "--vision-max-images", .native = true }, + .{ .name = "--vision-image-tokens", .native = true }, .{ .name = "--context", .native = true }, .{ .name = "--speed-up", .native = true }, .{ .name = "--max-tokens", .native = true }, @@ -167,6 +167,9 @@ pub const Args = struct { master: []const u8 = "", master_port: u16 = 29551, policy: []const u8 = "", // every --policy joined by commas + vision: bool = false, // image input (GLM-5.3-Flash): data-URL image_url parts in user messages + vision_max_images: u32 = 4, + vision_image_tokens: u32 = 4096, }; /// A usage error's message (argparse's ``error:`` line); the caller exits 2. @@ -272,7 +275,15 @@ fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usa const n = try int(u, a, name, v); if (n < 0) return fail(u, a, "argument --compact-keep: expected a token count from 0: '{s}'", .{v}); out.compact_keep = @intCast(n); - } else if (is(name, "--compact-memory")) out.compact_memory = v else if (is(name, "--slide")) out.slide = true else if (is(name, "--slide-graph")) out.slide_graph = v else if (is(name, "--parallel")) out.parallel = v else if (is(name, "--backend")) out.backend = v; + } else if (is(name, "--compact-memory")) out.compact_memory = v else if (is(name, "--slide")) out.slide = true else if (is(name, "--slide-graph")) out.slide_graph = v else if (is(name, "--parallel")) out.parallel = v else if (is(name, "--backend")) out.backend = v else if (is(name, "--vision")) out.vision = true else if (is(name, "--vision-max-images")) { + const n = try int(u, a, name, v); + if (n < 1 or n > 64) return fail(u, a, "argument --vision-max-images: expected 1 to 64 images: '{s}'", .{v}); + out.vision_max_images = @intCast(n); + } else if (is(name, "--vision-image-tokens")) { + const n = try int(u, a, name, v); + if (n < 16 or n > 16384) return fail(u, a, "argument --vision-image-tokens: expected 16 to 16384 tokens: '{s}'", .{v}); + out.vision_image_tokens = @intCast(n); + } } /// The CUDA build's --device and --segments; false for any other flag. @@ -364,6 +375,7 @@ pub fn request(a: Allocator, dir: []const u8, model_type: []const u8, args: Args .master = args.master, .master_port = args.master_port, .policy = args.policy, + .vision = if (args.vision) .{ .image_tokens = args.vision_image_tokens, .max_images = args.vision_max_images } else null, }; } diff --git a/zig/src/server/hf_text.zig b/zig/src/server/hf_text.zig index 22e4b976dc..416593c28c 100644 --- a/zig/src/server/hf_text.zig +++ b/zig/src/server/hf_text.zig @@ -209,6 +209,7 @@ pub const HfText = struct { .template_source = sourceFn, .special = specialFn, .token_bytes = tokenBytesFn, + .encode_plain = encodePlainFn, } }; } @@ -229,6 +230,10 @@ pub const HfText = struct { return std.mem.concat(a, u32, &.{ t.prefix, ids, t.suffix }); } + fn encodePlainFn(ctx: *anyopaque, a: Allocator, s: []const u8) model_text.Error![]u32 { + return self(ctx).tok.encodePlain(a, s) catch |e| if (e == error.OutOfMemory) error.OutOfMemory else error.Template; + } + fn decodeFn(ctx: *anyopaque, a: Allocator, ids: []const u32) Allocator.Error![]u8 { return self(ctx).tok.decode(a, ids, false) catch |e| if (e == error.OutOfMemory) error.OutOfMemory else a.dupe(u8, "\u{fffd}"); } diff --git a/zig/src/server/images.zig b/zig/src/server/images.zig new file mode 100644 index 0000000000..ba1253ef2c --- /dev/null +++ b/zig/src/server/images.zig @@ -0,0 +1,350 @@ +//! Image input (--vision): a request's image_url parts to the engine's tower input, and the rendered prompt's +//! placeholders expanded to each image's tokens, as TensorFold 0.6.6's vision path does for GLM-5.3-Flash. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json.zig"); +const errors = @import("errors.zig"); +const messages_mod = @import("messages.zig"); +const model_text = @import("model_text.zig"); +const Value = json.Value; +const Cx = errors.Cx; + +/// images.py's limits: an image's and a request's encoded bytes, and the visual tokens of a low-detail image. +pub const max_image_bytes = 10 << 20; +pub const max_request_bytes = 20 << 20; +const low_detail_tokens = 256; + +pub const Expanded = struct { + ids: []const u32, + history_len: usize, + images: []const api.Image, + cache_key: []const u32, +}; + +const Part = struct { url: []const u8, low: bool }; + +/// The image parts of normalized `messages`, in the order the template meets them. +fn parts(cx: *Cx, messages: Value) errors.Refused![]const Part { + var out: std.ArrayList(Part) = .empty; + if (messages != .array) return out.items; + for (messages.array) |m| { + const content = m.get("content") orelse continue; + if (content != .array) continue; + for (content.array) |p| { + const kind = p.get("type") orelse continue; + if (kind != .string or !std.mem.eql(u8, kind.string, "image_url")) continue; + const iu = p.get("image_url").?; + const detail = iu.get("detail"); + try out.append(cx.a, .{ .url = iu.get("url").?.string, .low = detail != null and std.mem.eql(u8, detail.?.string, "low") }); + } + } + return out.items; +} + +/// A data URL's bytes (base64 or percent-encoded); remote URLs are refused (the native server fetches nothing). +pub fn dataBytes(cx: *Cx, url: []const u8) errors.Refused![]const u8 { + if (std.ascii.startsWithIgnoreCase(url, "http://") or std.ascii.startsWithIgnoreCase(url, "https://")) + return cx.refuse("image URLs are not fetched by this server; send the image inline as a data: URL (data:image/png;base64,...)"); + if (!std.ascii.startsWithIgnoreCase(url, "data:")) return cx.refuse("invalid image data URL"); + const comma = std.mem.indexOfScalar(u8, url, ',') orelse return cx.refuse("invalid image data URL"); + const header = url[5..comma]; + const payload = url[comma + 1 ..]; + if (header.len > 256) return cx.refuse("invalid image data URL"); + var it = std.mem.splitScalar(u8, header, ';'); + _ = it.next(); + const enc = it.next(); + if (it.next() != null or (enc != null and !std.ascii.eqlIgnoreCase(enc.?, "base64"))) return cx.refuse("image data URL supports only optional base64 encoding"); + if (enc != null) { + if (payload.len > 4 * ((max_image_bytes + 2) / 3)) return cx.refuse("image data URL exceeds the encoded byte limit"); + const d = std.base64.standard.Decoder; + const n = d.calcSizeForSlice(payload) catch return cx.refuse("invalid image data URL encoding"); + const out = try cx.a.alloc(u8, n); + d.decode(out, payload) catch return cx.refuse("invalid image data URL encoding"); + if (out.len == 0 or out.len > max_image_bytes) return cx.refuse("image is empty or exceeds the encoded byte limit"); + return out; + } + if (payload.len > max_image_bytes * 3) return cx.refuse("image data URL exceeds the encoded byte limit"); + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < payload.len) : (i += 1) { + if (payload[i] == '%' and i + 2 < payload.len) { + const b = std.fmt.parseInt(u8, payload[i + 1 .. i + 3], 16) catch return cx.refuse("invalid image data URL encoding"); + try out.append(cx.a, b); + i += 2; + } else try out.append(cx.a, payload[i]); + } + if (out.items.len == 0 or out.items.len > max_image_bytes) return cx.refuse("image is empty or exceeds the encoded byte limit"); + return out.items; +} + +pub const Format = enum { png, jpeg, gif, webp, other }; + +/// The image's format from its first bytes, before any decoder sees it. +pub fn sniff(bytes: []const u8) Format { + if (std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n")) return .png; + if (std.mem.startsWith(u8, bytes, "\xff\xd8\xff")) return .jpeg; + if (std.mem.startsWith(u8, bytes, "GIF87a") or std.mem.startsWith(u8, bytes, "GIF89a")) return .gif; + if (bytes.len >= 12 and std.mem.eql(u8, bytes[0..4], "RIFF") and std.mem.eql(u8, bytes[8..12], "WEBP")) return .webp; + return .other; +} + +fn refusal(cx: *Cx, i: usize, err: anyerror) errors.Refused { + return switch (err) { + error.OutOfMemory => error.OutOfMemory, + error.ImageTooLarge => cx.refuse(try std.fmt.allocPrint(cx.a, "image {d} exceeds the limits: 10 MB encoded, 8192 pixels a side, 16 megapixels", .{i + 1})), + error.Animated => cx.refuse(try std.fmt.allocPrint(cx.a, "image {d}: animated and multipage images are unsupported; send a single frame", .{i + 1})), + error.ImageTooSmall => cx.refuse(try std.fmt.allocPrint(cx.a, "image {d}: the visual-token budget is too small for an image", .{i + 1})), + else => cx.refuse(try std.fmt.allocPrint(cx.a, "image {d} could not be decoded; send PNG or JPEG", .{i + 1})), + }; +} + +/// A quoted marker's stand-in while the template renders: two private-use code points, the second naming the marker. +const sentinel = "\u{F0000}"; + +/// The image markers' text (Vision.markers), longest first so one never matches inside another. +pub fn markerText(text: model_text.Text, a: std.mem.Allocator, v: api.Vision) ![]const []const u8 { + var out: std.ArrayList([]const u8) = .empty; + for (v.markers) |id| { + const s = try text.tokenString(a, id); + if (s.len > 0) try out.append(a, s); + } + std.mem.sort([]const u8, out.items, {}, struct { + fn longer(_: void, x: []const u8, y: []const u8) bool { + return x.len > y.len; + } + }.longer); + return out.items; +} + +/// `messages` with each marker the text spells (a user's words, a tool's output) replaced by its sentinel, so only +/// the template's own markers, one wrapper per image part, render as the image tokens (#511). +pub fn shield(a: std.mem.Allocator, v: Value, markers: []const []const u8) !Value { + return switch (v) { + .string => |s| .{ .string = try shieldText(a, s, markers) }, + .array => |items| blk: { + const out = try a.alloc(Value, items.len); + for (items, out) |x, *o| o.* = try shield(a, x, markers); + break :blk .{ .array = out }; + }, + .object => |o| blk: { + const out = try json.newObject(a); + var it = o.iterator(); + while (it.next()) |kv| try out.put(a, kv.key_ptr.*, try shield(a, kv.value_ptr.*, markers)); + break :blk .{ .object = out }; + }, + else => v, + }; +} + +fn shieldText(a: std.mem.Allocator, s: []const u8, markers: []const []const u8) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + var changed = false; + outer: while (i < s.len) { + for (markers, 0..) |m, k| if (std.mem.startsWith(u8, s[i..], m)) { + try out.appendSlice(a, sentinel); + try out.appendSlice(a, try std.fmt.allocPrint(a, "{u}", .{@as(u21, @intCast(0xF0001 + k))})); + i += m.len; + changed = true; + continue :outer; + }; + try out.append(a, s[i]); + i += 1; + } + return if (changed) out.items else s; +} + +/// The rendered prompt's ids: its text as the tokenizer reads it, each sentinel's marker as ordinary text tokens. +/// Added tokens split the text anyway, so a prompt without quoted markers gets exactly `encode`'s ids. +pub fn encodeShielded(text: model_text.Text, a: std.mem.Allocator, rendered: []const u8, markers: []const []const u8) model_text.Error![]u32 { + var ids: std.ArrayList(u32) = .empty; + var rest = rendered; + while (std.mem.indexOf(u8, rest, sentinel)) |at| { + const after = rest[at + sentinel.len ..]; + const cp: u21 = if (after.len >= 4) std.unicode.utf8Decode(after[0..4]) catch 0 else 0; + const k: usize = if (cp >= 0xF0001) cp - 0xF0001 else markers.len; + if (k >= markers.len) { // not one of ours: the code point is ordinary text + try ids.appendSlice(a, try text.encode(a, rest[0 .. at + sentinel.len], false)); + rest = after; + continue; + } + try ids.appendSlice(a, try text.encode(a, rest[0..at], false)); + try ids.appendSlice(a, try text.encodePlain(a, markers[k])); + rest = after[4..]; + } + try ids.appendSlice(a, try text.encode(a, rest, false)); + return ids.items; +} + +/// The prompt with each image's placeholder expanded to its tokens, the images for the engine and the prompt as the +/// cache matches it; null when the engine reads no images. Images are counted from the request's image parts; the +/// rendered placeholders are the template's alone (text that spells a marker was shielded), one per part. +pub fn expand(vision: ?api.Vision, cx: *Cx, messages: Value, ids: []const u32, history_len: usize) errors.Refused!?Expanded { + const v = vision orelse return null; + const ps = try parts(cx, messages); + var marks: usize = 0; + for (ids) |t| marks += @intFromBool(t == v.image_token); + if (marks != ps.len) return cx.fail(.server, "the chat template wrote {d} image placeholders for {d} image parts", .{ marks, ps.len }); + if (ps.len == 0) return null; + if (ps.len > v.max_images) return cx.refuse(try std.fmt.allocPrint(cx.a, "a request may hold at most {d} images (--vision-max-images); it has {d}", .{ v.max_images, ps.len })); + const budget = v.image_tokens / @as(u32, @intCast(ps.len)); + if (budget < 1) return cx.refuse("the image count exceeds the visual-token budget"); + const prepared = try cx.a.alloc(api.PreparedImage, ps.len); + var bytes_total: usize = 0; + var extra: usize = 0; + for (ps, prepared, 0..) |p, *out, i| { + const bytes = try dataBytes(cx, p.url); + bytes_total += bytes.len; + if (bytes_total > max_request_bytes) return cx.refuse("the request's images exceed 20 MB encoded"); + switch (sniff(bytes)) { // the Python frontend's formats (images.py: JPEG, PNG, WebP), WebP not yet decoded here + .png, .jpeg => {}, + .webp => return cx.refuse(try std.fmt.allocPrint(cx.a, "image {d} is WebP, which this server does not decode yet; send PNG or JPEG", .{i + 1})), + .gif, .other => return cx.refuse(try std.fmt.allocPrint(cx.a, "image {d} is not PNG or JPEG; send one of those", .{i + 1})), + } + const cap = if (p.low) @min(budget, low_detail_tokens) else budget; + out.* = v.prepare(v.ctx, cx.a, bytes, cap) catch |e| return refusal(cx, i, e); + if (out.tokens == 0 or out.tokens > cap) return cx.refuse("the image processor exceeded the per-image visual-token budget"); + extra += out.tokens - 1; + } + const n = ids.len + extra; + const out_ids = try cx.a.alloc(u32, n); + const key = try cx.a.alloc(u32, n); + const imgs = try cx.a.alloc(api.Image, ps.len); + var hist = history_len; + var at: usize = 0; + var k: usize = 0; + for (ids, 0..) |t, src| { + if (t != v.image_token) { + out_ids[at] = t; + key[at] = t; + at += 1; + continue; + } + const img = prepared[k]; + imgs[k] = .{ .pixels = img.pixels, .gh = img.gh, .gw = img.gw, .at = @intCast(at), .tokens = img.tokens }; + if (src < history_len) hist += img.tokens - 1; + for (0..img.tokens) |j| { + out_ids[at + j] = t; + // the cache's ids for this image's rows: past the vocabulary, by content and row + key[at + j] = 0x8000_0000 | @as(u32, @truncate(std.hash.Wyhash.hash(img.hash, std.mem.asBytes(&j)) & 0x7fff_ffff)); + } + at += img.tokens; + k += 1; + } + return .{ .ids = out_ids, .history_len = hist, .images = imgs, .cache_key = key }; +} + +test "data URLs decode; remote URLs are refused" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var cx: Cx = .{ .a = arena.allocator() }; + try std.testing.expectEqualStrings("hi!", try dataBytes(&cx, "data:image/png;base64,aGkh")); + try std.testing.expectEqualStrings("a b", try dataBytes(&cx, "data:text/plain,a%20b")); + try std.testing.expectError(error.Refused, dataBytes(&cx, "https://example.com/x.png")); + try std.testing.expectError(error.Refused, dataBytes(&cx, "data:image/png;base64,***")); +} + +fn fakePrepare(ctx: *anyopaque, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage { + _ = ctx; + _ = max_tokens; + const tokens: u32 = @intCast(bytes.len - 3); // the test's images: a JPEG's first bytes, then one token a byte + return .{ .pixels = try a.alloc(f32, 0), .gh = 2, .gw = 2 * tokens, .tokens = tokens, .hash = bytes[3] }; +} + +test "placeholders expand to each image's tokens, the history and cache key with them" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + var dummy: u8 = 0; + const v: api.Vision = .{ .ctx = &dummy, .prepare = fakePrepare, .image_token = 9, .image_tokens = 64, .max_images = 4 }; + const text = + \\[{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:,%FF%D8%FFab"}}, {"type": "text", "text": "x"}]}, + \\ {"role": "assistant", "content": "y"}, + \\ {"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:,%FF%D8%FFcde"}}]}] + ; + const msgs = switch (try json.parseText(a, text)) { + .ok => |m| m, + .err => return error.TestUnexpectedResult, + }; + const ids = [_]u32{ 1, 9, 2, 3, 9, 4 }; + const x = (try expand(v, &cx, msgs, &ids, 4)).?; + try std.testing.expectEqualSlices(u32, &.{ 1, 9, 9, 2, 3, 9, 9, 9, 4 }, x.ids); + try std.testing.expectEqual(@as(usize, 5), x.history_len); // the first image is in the history, the second not + try std.testing.expectEqual(@as(u32, 1), x.images[0].at); + try std.testing.expectEqual(@as(u32, 5), x.images[1].at); + try std.testing.expect(x.cache_key[1] >= 0x8000_0000 and x.cache_key[1] != x.cache_key[2]); + try std.testing.expectEqual(@as(u32, 2), x.cache_key[3]); + // a placeholder the images do not account for is refused + try std.testing.expectError(error.Refused, expand(v, &cx, msgs, &[_]u32{ 9, 9, 9 }, 0)); + _ = messages_mod; +} + +/// A test tokenizer: "<|image|>" is token 9 unless read plainly, every other byte its own id plus 100. +const MarkText = struct { + fn text() model_text.Text { + return .{ .ctx = undefined, .vtable = &.{ .encode = encode, .decode = undefined, .token_id = undefined, .token_string = tokenString, .vocab_size = undefined, .eos_ids = undefined, .render = undefined, .template_source = undefined, .encode_plain = plain } }; + } + fn encode(_: *anyopaque, a: std.mem.Allocator, s: []const u8, _: bool) model_text.Error![]u32 { + var out: std.ArrayList(u32) = .empty; + var i: usize = 0; + while (i < s.len) { + if (std.mem.startsWith(u8, s[i..], "<|image|>")) { + try out.append(a, 9); + i += 9; + } else { + try out.append(a, @as(u32, s[i]) + 100); + i += 1; + } + } + return out.items; + } + fn plain(_: *anyopaque, a: std.mem.Allocator, s: []const u8) model_text.Error![]u32 { + const out = try a.alloc(u32, s.len); + for (out, s) |*o, c| o.* = @as(u32, c) + 100; + return out; + } + fn tokenString(_: *anyopaque, a: std.mem.Allocator, id: u32) std.mem.Allocator.Error![]u8 { + return a.dupe(u8, if (id == 9) "<|image|>" else ""); + } +}; + +test "a marker the text spells stays text: only the template's markers are image tokens (#511)" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var dummy: u8 = 0; + const v: api.Vision = .{ .ctx = &dummy, .prepare = fakePrepare, .image_token = 9, .markers = &.{9}, .image_tokens = 64, .max_images = 4 }; + const markers = try markerText(MarkText.text(), a, v); + const conversation = + \\[{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:,ab"}}, {"type": "text", "text": "what is <|image|>?"}]}, + \\ {"role": "tool", "content": "source: x = '<|image|>'"}] + ; + const msgs = switch (try json.parseText(a, conversation)) { + .ok => |m| m, + .err => return error.TestUnexpectedResult, + }; + const shielded = try shield(a, msgs, markers); + // the "template": one marker per image part, then each message's text + var rendered: std.ArrayList(u8) = .empty; + try rendered.appendSlice(a, "<|image|>"); + try rendered.appendSlice(a, shielded.array[0].get("content").?.array[1].get("text").?.string); + try rendered.appendSlice(a, shielded.array[1].get("content").?.string); + const ids = try encodeShielded(MarkText.text(), a, rendered.items, markers); + var marks: usize = 0; + for (ids) |t| marks += @intFromBool(t == 9); + try std.testing.expectEqual(@as(usize, 1), marks); + // the quoted markers read as their characters, and text without one is exactly encode's + try std.testing.expectEqualSlices(u32, try MarkText.encode(undefined, a, "<|image|>what is ", false), ids[0..9]); + try std.testing.expectEqual(@as(u32, '<' + 100), ids[9]); + const plain_text = "no markers here"; + try std.testing.expectEqualSlices(u32, try MarkText.encode(undefined, a, plain_text, false), try encodeShielded(MarkText.text(), a, plain_text, markers)); +} + +test "formats from their first bytes: WebP is refused by name" { + try std.testing.expectEqual(Format.png, sniff("\x89PNG\r\n\x1a\nrest")); + try std.testing.expectEqual(Format.jpeg, sniff("\xff\xd8\xff\xe0")); + try std.testing.expectEqual(Format.gif, sniff("GIF89a...")); + try std.testing.expectEqual(Format.webp, sniff("RIFF\x10\x00\x00\x00WEBPVP8 ")); + try std.testing.expectEqual(Format.other, sniff("\x00\x00\x00\x18ftypheic")); +} diff --git a/zig/src/server/messages.zig b/zig/src/server/messages.zig index 9559ed784b..48a0d77f6c 100644 --- a/zig/src/server/messages.zig +++ b/zig/src/server/messages.zig @@ -23,6 +23,36 @@ fn withField(cx: *Cx, o: *const json.Object, key: []const u8, value: Value) !*js /// ``normalize_messages`` (text only): leading system and developer text merged, later ones as ``late_system``; a template that needs a user query gains one user turn after a trailing tool run. pub fn normalize(cx: *Cx, messages: ?Value, late_system: []const u8, needs_user_after_tool: bool) errors.Refused!Value { + return normalizeWith(cx, messages, late_system, needs_user_after_tool, false); +} + +/// One image part as the template and the image path read it: {"type": "image_url", "image_url": {"url", "detail"?}}. +fn imagePart(cx: *Cx, part: Value) errors.Refused!Value { + const iu = part.get("image_url") orelse return cx.refuse("an image_url content part must contain image_url"); + var url: []const u8 = ""; + var detail: ?Value = null; + if (iu == .string) url = iu.string else if (iu == .object) { + const u = iu.get("url") orelse return cx.refuse("image_url must contain a url string"); + if (u != .string) return cx.refuse("image_url must contain a url string"); + url = u.string; + detail = iu.get("detail"); + if (detail) |d| if (d != .string or !(std.mem.eql(u8, d.string, "auto") or std.mem.eql(u8, d.string, "low") or std.mem.eql(u8, d.string, "high"))) + return cx.refuse("image_url detail must be auto, low or high"); + } else return cx.refuse("image_url must be a url string or an object with one"); + if (url.len == 0) return cx.refuse("image_url must contain a url string"); + for ([_][]const u8{ "audio", "input_audio", "video", "video_url" }) |k| if (json.truthyField(part, k)) return cx.refuse("image_url parts cannot contain other media"); + const inner = try json.newObject(cx.a); + try inner.put(cx.a, "url", .{ .string = url }); + if (detail) |d| try inner.put(cx.a, "detail", d); + const out = try json.newObject(cx.a); + try out.put(cx.a, "type", .{ .string = "image_url" }); + try out.put(cx.a, "image_url", .{ .object = inner }); + return .{ .object = out }; +} + +/// `normalize`, and with `images` (an engine that reads them) a user or tool message's image_url parts kept beside its +/// text parts, in order, for the template's image markers; a message without image parts is joined text as before. +pub fn normalizeWith(cx: *Cx, messages: ?Value, late_system: []const u8, needs_user_after_tool: bool, images: bool) errors.Refused!Value { const list = messages orelse return cx.refuse("messages must be a non-empty list"); if (list != .array or list.array.len == 0) return cx.refuse("messages must be a non-empty list"); var out: std.ArrayList(Value) = .empty; @@ -36,14 +66,29 @@ pub fn normalize(cx: *Cx, messages: ?Value, late_system: []const u8, needs_user_ var item: *json.Object = message.object; if (content != null and content.? == .array) { var text: std.ArrayList(u8) = .empty; + var parts: std.ArrayList(Value) = .empty; // with images: text and image parts in order + var has_image = false; for (content.?.array) |part| { - const typed = part == .object and part.get("type") != null and part.get("type").? == .string and std.mem.eql(u8, part.get("type").?.string, "text"); - if (!typed or fields.hasMedia(part)) return cx.refuse("this server accepts text parts only; image, audio and video inputs are unsupported"); + const kind = if (part == .object and part.get("type") != null and part.get("type").? == .string) part.get("type").?.string else ""; + if (images and std.mem.eql(u8, kind, "image_url")) { + // a tool's result carries images as agents send screenshots; the template renders them in its response + if (!std.mem.eql(u8, role.?.string, "user") and !std.mem.eql(u8, role.?.string, "tool")) return cx.refuse("image parts are accepted in user and tool messages only"); + try parts.append(cx.a, try imagePart(cx, part)); + has_image = true; + continue; + } + if (!std.mem.eql(u8, kind, "text") or fields.hasMedia(part)) return cx.refuse(if (images) "content parts must be text or image_url; audio and video inputs are unsupported" else "this server accepts text parts only; image, audio and video inputs are unsupported"); const t = part.get("text") orelse return cx.refuse("a text content part must contain a text string"); if (t != .string) return cx.refuse("a text content part must contain a text string"); try text.appendSlice(cx.a, t.string); + if (images) { + const tp = try json.newObject(cx.a); + try tp.put(cx.a, "type", .{ .string = "text" }); + try tp.put(cx.a, "text", t); + try parts.append(cx.a, .{ .object = tp }); + } } - item = try withField(cx, message.object, "content", .{ .string = text.items }); + item = try withField(cx, message.object, "content", if (has_image) Value{ .array = parts.items } else Value{ .string = text.items }); } else if (content == null or content.? == .null) { item = try withField(cx, message.object, "content", .{ .string = "" }); } else if (content.? != .string) { diff --git a/zig/src/server/model_text.zig b/zig/src/server/model_text.zig index 0b36055a7f..33b5baa78c 100644 --- a/zig/src/server/model_text.zig +++ b/zig/src/server/model_text.zig @@ -36,6 +36,8 @@ pub const Text = struct { template_source: *const fn (ctx: *anyopaque) []const u8, /// Whether an id is a special token (an added token flagged special); null: none are known. special: ?*const fn (ctx: *anyopaque, id: u32) bool = null, + /// Ids of ``text`` with no added token matched (text that spells a special token is ordinary text); null: ``encode``. + encode_plain: ?*const fn (ctx: *anyopaque, a: Allocator, text: []const u8) Error![]u32 = null, /// A token's own bytes (a partial UTF-8 sequence kept whole) for logprob rows; null: the tokenizer can't say. token_bytes: ?*const fn (ctx: *anyopaque, a: Allocator, id: u32) Allocator.Error!?[]u8 = null, }; @@ -44,6 +46,11 @@ pub const Text = struct { return t.vtable.encode(t.ctx, a, text, add_special); } + pub fn encodePlain(t: Text, a: Allocator, text: []const u8) Error![]u32 { + const f = t.vtable.encode_plain orelse return t.encode(a, text, false); + return f(t.ctx, a, text); + } + pub fn decode(t: Text, a: Allocator, ids: []const u32) Allocator.Error![]u8 { return t.vtable.decode(t.ctx, a, ids); } diff --git a/zig/src/server/openai.zig b/zig/src/server/openai.zig index 91d02cceb8..793dea3cdf 100644 --- a/zig/src/server/openai.zig +++ b/zig/src/server/openai.zig @@ -125,10 +125,10 @@ fn plan(srv: *Server, cx: *Cx, is_chat: bool, raw: Value) errors.Refused!Plan { if (srv.config.request_log) |path| request_log.append(cx.a, path, body); var input: chat.Input = .{ .fields = undefined }; if (is_chat) { - input.messages = try messages.normalize(cx, body.get("messages"), "system", srv.needs_user_after_tool); + input.messages = try messages.normalizeWith(cx, body.get("messages"), "system", srv.needs_user_after_tool, srv.info.vision != null); input.tools = try tool_specs.active(cx, body.get("tools"), body.get("tool_choice")); } else if (body.get("messages")) |m| if (m == .array and m.array.len > 0) { - input.messages = try messages.normalize(cx, m, "system", srv.needs_user_after_tool); + input.messages = try messages.normalizeWith(cx, m, "system", srv.needs_user_after_tool, srv.info.vision != null); }; if (!is_chat and input.messages.array.len == 0) input.prompt = try legacyPrompt(srv, cx, body.get("prompt")); // ``body.get("max_tokens") or body.get("max_completion_tokens")``: both are ints or None by now diff --git a/zig/src/server/prompt.zig b/zig/src/server/prompt.zig index e68363bfe7..5500803b68 100644 --- a/zig/src/server/prompt.zig +++ b/zig/src/server/prompt.zig @@ -1,15 +1,19 @@ //! Prompt ids from a request, as ``prepare_prompt`` and ``render_prompt_ids`` make them. const std = @import("std"); +const api = @import("engine_api"); const json = @import("json.zig"); const errors = @import("errors.zig"); const messages_mod = @import("messages.zig"); const model_text = @import("model_text.zig"); const chat = @import("chat.zig"); +const images = @import("images.zig"); const Server = @import("server.zig").Server; const Value = json.Value; const Cx = errors.Cx; -pub const Rendered = struct { ids: []const u32, history_len: usize = 0, rewind_len: usize = 0 }; +/// With image input, `ids` holds each image's tokens in place of its placeholder, `images` are theirs in order and +/// `cache_key` is the prompt as the cache matches it (engine_api.Request). +pub const Rendered = struct { ids: []const u32, history_len: usize = 0, rewind_len: usize = 0, images: []const api.Image = &.{}, cache_key: []const u32 = &.{} }; /// Where lessons decide to act on a reply: the row before the generation prompt's ``, else before its last. pub fn decideOf(srv: *const Server, ids: []const u32) u32 { @@ -27,7 +31,7 @@ pub const isTitle = messages_mod.isTitleRequest; /// ``render_prompt_ids``: messages normalized for this template, rendered, and a dangling ```` closed. pub fn renderIds(srv: *Server, cx: *Cx, messages: Value, tools: []const Value, thinking: bool, effort: ?[]const u8, generation: bool) errors.Refused![]const u32 { - const normalized = try messages_mod.toolArguments(cx, try messages_mod.normalize(cx, messages, srv.late_system, srv.needs_user_after_tool)); + const normalized = try messages_mod.toolArguments(cx, try messages_mod.normalizeWith(cx, messages, srv.late_system, srv.needs_user_after_tool, srv.info.vision != null)); var problem: []const u8 = ""; const options: model_text.RenderOptions = .{ .tools = if (tools.len > 0) Value{ .array = @constCast(tools) } else null, @@ -35,7 +39,7 @@ pub fn renderIds(srv: *Server, cx: *Cx, messages: Value, tools: []const Value, t .enable_thinking = thinking, .reasoning_effort = if (thinking) effort else null, }; - var ids = srv.text.renderIds(cx.a, normalized, options, &problem) catch |e| switch (e) { + var ids = render(srv, cx.a, normalized, options, &problem) catch |e| switch (e) { error.OutOfMemory => return error.OutOfMemory, error.Template => return cx.fail(.server, "{s}", .{problem}), }; @@ -52,6 +56,14 @@ pub fn renderIds(srv: *Server, cx: *Cx, messages: Value, tools: []const Value, t return ids; } +/// The template's ids for `messages`; with image input, a marker the messages' text spells is ordinary text (images.zig). +fn render(srv: *Server, a: std.mem.Allocator, messages: Value, options: model_text.RenderOptions, problem: *[]const u8) model_text.Error![]u32 { + const v = srv.info.vision orelse return srv.text.renderIds(a, messages, options, problem); + const markers = try images.markerText(srv.text, a, v); + const text = try srv.text.render(a, try images.shield(a, messages, markers), options, problem); + return images.encodeShielded(srv.text, a, text, markers); +} + /// The template's generation prompt (thinking on or off): what a probe conversation renders past its history. fn generationPrompt(srv: *Server, cx: *Cx, thinking: bool) errors.Refused![]const u32 { const user = try json.newObject(cx.a); @@ -101,6 +113,9 @@ pub fn prepare(srv: *Server, cx: *Cx, input: chat.Input, thinking: bool, effort: var history_len: usize = 0; if (history.len > 0 and history.len < prompt.len and std.mem.eql(u32, prompt[0..history.len], history)) history_len = history.len; if (history_len == 0 and prompt.len > 1 and std.mem.eql(u32, history, prompt)) history_len = prompt.len - 1; // a template with no generation suffix + // --vision: each image's placeholder expanded to its tokens before the window, chunks and cache see the prompt; + // such a prompt keeps no rewind, which the expansion does not translate + if (try images.expand(srv.info.vision, cx, input.messages, prompt, history_len)) |x| return .{ .ids = x.ids, .history_len = x.history_len, .images = x.images, .cache_key = x.cache_key }; const count = if (input.messages == .array) input.messages.array.len else 0; const rewind_len = if (srv.info.prompt_cache) rewindLen(srv, cx, input.messages, count, input.tools, prompt, thinking, effort) else 0; // one more render return .{ .ids = prompt, .history_len = history_len, .rewind_len = rewind_len }; diff --git a/zig/src/server/reply_text.zig b/zig/src/server/reply_text.zig index 648a1d8cd2..991ae959ce 100644 --- a/zig/src/server/reply_text.zig +++ b/zig/src/server/reply_text.zig @@ -292,6 +292,35 @@ pub const Stops = struct { } }; +/// The text a stream has sent: Python's ``streamed = visible``, grown by its delta while it only grows. +pub const Shown = struct { + text: std.ArrayList(u8) = .empty, + chars: usize = 0, + at: ?[*]const u8 = null, // where the last shown text lay; the decode buffer only grows, so that prefix holds + extends: bool = false, + + /// Python's ``now[len(shown):]``; ``stable``: ``now`` lies in the append-only decode buffer. + pub fn after(s: *Shown, now: []const u8, stable: bool) []const u8 { + const sent = s.text.items; + s.extends = (stable and s.at == now.ptr and now.len >= sent.len) or std.mem.startsWith(u8, now, sent); + if (!s.extends) return afterChars(now, s.chars); + if (stable) s.at = now.ptr; // the buffer moved but kept its bytes: the next check is free again + return now[sent.len..]; + } + + pub fn set(s: *Shown, a: Allocator, now: []const u8, delta: []const u8) Allocator.Error!void { + if (s.extends) { + try s.text.appendSlice(a, delta); + s.chars += charCount(delta); + } else { + s.text = .empty; + try s.text.appendSlice(a, now); + s.chars = charCount(now); + } + s.at = now.ptr; + } +}; + /// Decodes only new tokens with the previous chunk as context, so characters split across tokens stay whole. pub const Incremental = struct { tokens: std.ArrayList(u32) = .empty, diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index ecc81c575a..b669d55c3a 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -38,6 +38,7 @@ test { _ = @import("process_memory.zig"); _ = @import("log.zig"); _ = @import("messages.zig"); + _ = @import("images.zig"); _ = @import("stream_preflight_test.zig"); _ = @import("logprobs_test.zig"); _ = @import("late_system_test.zig"); diff --git a/zig/tests/glm_vision.zig b/zig/tests/glm_vision.zig new file mode 100644 index 0000000000..7df41b512c --- /dev/null +++ b/zig/tests/glm_vision.zig @@ -0,0 +1,148 @@ +//! GLM-5.3-Flash's image tower against a reference dump (tools/zig/glm_vision_fixtures.py: mlx-vlm's tower). +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const vision = tf.glm.vision; + +const usage = + \\tf-glm-vision MODEL_DIR REF_DIR [STAGE] [IMAGE] + \\REF_DIR holds meta.json (grid_thw), patches.f32 and the stage's reference: embed.f32 (STAGE embed, after the patch + \\projection), block0.f32 (STAGE block0, after the first block), blocks.f32 (STAGE blocks, after the last) or + \\features.f32 (STAGE features, the default: the tower's output rows). Writes native_STAGE.f32 there and prints the + \\largest and mean absolute differences, the reference's mean magnitude and the rows' cosine similarity. + \\IMAGE: prepare the patches from this file natively (decode, resize, pad, normalize), compare them with + \\patches.f32 value by value, and run the tower on them instead (meta.json's max_tokens is the budget). +; + +fn readFile(a: std.mem.Allocator, dir: []const u8, name: []const u8) ![]u8 { + const path = try std.fmt.allocPrintSentinel(a, "{s}/{s}", .{ dir, name }, 0); + const f = try mtl.MappedFile.open(path); + defer f.deinit(); + return a.dupe(u8, f.bytes[0..f.size]); +} + +fn bf16ToF32(x: u16) f32 { + return @bitCast(@as(u32, x) << 16); +} + +pub fn main(init: std.process.Init) !void { + const a = init.arena.allocator(); + const args = try init.minimal.args.toSlice(a); + if (args.len < 3) { + std.debug.print("{s}\n", .{usage}); + return error.Usage; + } + const dir = args[1]; + const ref = args[2]; + const stage = if (args.len > 3) args[3] else "features"; + const stop: ?u32 = if (std.mem.eql(u8, stage, "embed")) 0 else if (std.mem.eql(u8, stage, "block0")) 1 else if (std.mem.eql(u8, stage, "blocks")) vision.depth else if (std.mem.eql(u8, stage, "features")) null else return error.Usage; + + const meta = try std.json.parseFromSliceLeaky(std.json.Value, a, try readFile(a, ref, "meta.json"), .{}); + const grid = meta.object.get("grid_thw").?.array.items; + const gh: u32 = @intCast(grid[1].integer); + const gw: u32 = @intCast(grid[2].integer); + const raw = try readFile(a, ref, "patches.f32"); + var pixels = try a.alloc(f32, raw.len / 4); + @memcpy(std.mem.sliceAsBytes(pixels), raw[0 .. pixels.len * 4]); + const P = gh * gw; + const T = P / vision.patches_per_token; + + const device = try mtl.Device.init(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const queue = try device.queue(); + const cfg_text = try readFile(a, dir, "config.json"); + const proc_text = readFile(a, dir, "processor_config.json") catch null; + const c = (try vision.Config.parse(a, cfg_text, proc_text)) orelse return error.NoVisionConfig; + if (args.len > 4) { + const img_path = try std.fmt.allocPrintSentinel(a, "{s}", .{args[4]}, 0); + const f = try mtl.MappedFile.open(img_path); + defer f.deinit(); + const max_tokens: u32 = @intCast(meta.object.get("max_tokens").?.integer); + const t0i = std.Io.Clock.awake.now(init.io).toNanoseconds(); + const prep = try tf.glm.image.prepare(a, f.bytes[0..f.size], c, max_tokens); + const t1i = std.Io.Clock.awake.now(init.io).toNanoseconds(); + std.debug.print("prepared {s}: grid {d}x{d}, {d} tokens in {d:.1} ms\n", .{ args[4], prep.gh, prep.gw, prep.tokens, @as(f64, @floatFromInt(t1i - t0i)) / 1e6 }); + if (prep.gh != gh or prep.gw != gw) { + std.debug.print("grid differs from the reference's {d}x{d}\n", .{ gh, gw }); + return error.GridMismatch; + } + var differ: usize = 0; + var max_p: f32 = 0; + for (prep.pixels, pixels) |x, y| { + if (x != y) differ += 1; + max_p = @max(max_p, @abs(x - y)); + } + std.debug.print("patches: {d} of {d} values differ from the reference (largest {d:.6})\n", .{ differ, pixels.len, max_p }); + pixels = prep.pixels; + } + var t0 = std.Io.Clock.awake.now(init.io).toNanoseconds(); + const v = try vision.Vision.load(std.heap.page_allocator, device, dir, c, @max(T, 1024)); + defer v.deinit(); + var t1 = std.Io.Clock.awake.now(init.io).toNanoseconds(); + std.debug.print("tower loaded in {d:.2} s ({d:.2} GiB with scratch for {d} patches, attention chunks of {d} rows)\n", .{ @as(f64, @floatFromInt(t1 - t0)) / 1e9, @as(f64, @floatFromInt(v.bytes)) / (1 << 30), v.max_patches, v.chunk }); + const out_buf = try device.buffer(@as(usize, T) * vision.out_hidden * 2, mtl.ResourceOptions.shared); + defer out_buf.deinit(); + + for (0..2) |run| { // the second run is the timed one (the first compiles pipelines' state on the GPU) + const cb = queue.commandBuffer(); + const enc = cb.compute(.serial); + t0 = std.Io.Clock.awake.now(init.io).toNanoseconds(); + try v.encode(enc, pixels, gh, gw, .{ .buf = out_buf }, stop); + enc.end(); + cb.commit(); + cb.wait(); + t1 = std.Io.Clock.awake.now(init.io).toNanoseconds(); + if (cb.failure()) |msg| { + std.debug.print("command buffer failed: {s}\n", .{msg}); + return error.GpuFailed; + } + if (run == 1) std.debug.print("encode: {d} patches -> {d} tokens in {d:.1} ms\n", .{ P, T, @as(f64, @floatFromInt(t1 - t0)) / 1e6 }); + } + // the stage's rows: the residual stream for a stop, else the output rows + const width: usize = if (stop != null) vision.hidden else vision.out_hidden; + const rows: usize = if (stop != null) P else T; + const src: [*]const u16 = if (stop != null) @ptrCast(@alignCast(v.x.addr())) else @ptrCast(@alignCast(out_buf.contents())); + const got = try a.alloc(f32, rows * width); + for (got, 0..) |*g, i| g.* = bf16ToF32(src[i]); + const name = try std.fmt.allocPrint(a, "native_{s}.f32", .{stage}); + { + const path = try std.fmt.allocPrint(a, "{s}/{s}", .{ ref, name }); + const f = try std.Io.Dir.cwd().createFile(init.io, path, .{}); + defer f.close(init.io); + try f.writeStreamingAll(init.io, std.mem.sliceAsBytes(got)); + } + const want_raw = try readFile(a, ref, try std.fmt.allocPrint(a, "{s}.f32", .{stage})); + const want = try a.alloc(f32, want_raw.len / 4); + @memcpy(std.mem.sliceAsBytes(want), want_raw[0 .. want.len * 4]); + if (want.len != got.len) { + std.debug.print("size: native {d} values, reference {d}\n", .{ got.len, want.len }); + return error.SizeMismatch; + } + var max_d: f64 = 0; + var sum_d: f64 = 0; + var sum_m: f64 = 0; + var worst_cos: f64 = 1; + var mean_cos: f64 = 0; + for (0..rows) |r| { + var dot: f64 = 0; + var ng: f64 = 0; + var nw: f64 = 0; + for (0..width) |j| { + const g: f64 = got[r * width + j]; + const w: f64 = want[r * width + j]; + const d = @abs(g - w); + max_d = @max(max_d, d); + sum_d += d; + sum_m += @abs(w); + dot += g * w; + ng += g * g; + nw += w * w; + } + const cs = dot / (@sqrt(ng * nw) + 1e-30); + worst_cos = @min(worst_cos, cs); + mean_cos += cs; + } + const n: f64 = @floatFromInt(got.len); + std.debug.print("{s}: max |d| {d:.4}, mean |d| {d:.5}, mean |ref| {d:.4}, cosine mean {d:.6} worst {d:.6} ({d} rows of {d})\n", .{ stage, max_d, sum_d / n, sum_m / n, mean_cos / @as(f64, @floatFromInt(rows)), worst_cos, rows, width }); +} From 47c40985ce6a766150a25bddf0999753703101d1 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Sat, 10 Oct 2026 10:02:35 -0500 Subject: [PATCH 05/17] Native image input: --vision-urls fetches public HTTPS image URLs as 0.6.6 did media_fetch.zig follows images_http.py: an https URL on port 443 without credentials, a fragment, a backslash or controls; every address the host resolves to public (Python's is_global less 192.0.0.0/24 and 168.63.129.16; IPv6 global unicast only, no 6to4 or Teredo); TLS verified for the host on the address that was checked; GET with identity encoding; up to 3 redirects, each checked again; the declared media type JPEG, PNG or WebP (WebP is then refused by its bytes, as with data URLs); the bytes within what the request has left of 10 MB an image and 20 MB in all; 10 s a download and 30 s for a request's downloads. std's connect has no timeout yet: a nonblocking connect and poll bound it, the socket's send and receive timeouts bound the rest. The HTTP exchange reads from any reader, so the response rules (redirects joined and rechecked, status, types, lengths, chunking, encodings, the deadline) are tested against canned responses; the URL and address rules are tested directly. Without --vision-urls an https part is refused with the flag's name, other schemes as 0.6.6 refused them; --vision-urls needs --vision. tools/zig/vision_urls_served.py checks a served model against public hosts. --- docs/api.md | 3 +- docs/vision.md | 12 +- tools/zig/vision_served.py | 6 +- tools/zig/vision_urls_served.py | 109 +++++++ zig/src/server/cli.zig | 10 +- zig/src/server/images.zig | 104 ++++++- zig/src/server/media_fetch.zig | 497 ++++++++++++++++++++++++++++++++ zig/src/server/prompt.zig | 2 +- zig/src/server/root.zig | 1 + zig/src/server/serve.zig | 1 + zig/src/server/server.zig | 2 + 11 files changed, 730 insertions(+), 17 deletions(-) create mode 100644 tools/zig/vision_urls_served.py create mode 100644 zig/src/server/media_fetch.zig diff --git a/docs/api.md b/docs/api.md index 76a950230b..c716b914a0 100644 --- a/docs/api.md +++ b/docs/api.md @@ -68,7 +68,8 @@ chat fields that shape the prompt (`tools`, `reasoning_effort`, `chat_template_k request, images expanded. `/detokenize` takes `tokens` and returns `prompt`. With `--vision`, supported Qwen3.5/3.8 dense checkpoints accept `image_url` content parts alongside text in user messages and in tool results (`role: "tool"`), such as an agent's screenshots. The native server does the same for -GLM-5.3-Flash on Metal, with data URLs only ([image input](vision.md#the-native-server)). +GLM-5.3-Flash on Metal, with data URLs, and public HTTPS URLs under `--vision-urls` +([image input](vision.md#the-native-server)). See [image input](vision.md) for data URLs, public image URLs, limits and cache behavior. Unsupported image input, audio, video and non-text output requests receive HTTP 400. diff --git a/docs/vision.md b/docs/vision.md index 75a37c1c58..1f12dbb43c 100644 --- a/docs/vision.md +++ b/docs/vision.md @@ -135,8 +135,16 @@ For Qwen, each image request carries its own multimodal rotary positions and con 4,096) for engines that read images; GLM-5.3-Flash on one Mac reads them so far, and other native engines refuse the flag at startup. -- Images arrive as `image_url` data URLs in user messages and tool results. Remote URLs are refused, since - `--vision-urls` isn't on the native server yet. +- Images arrive as `image_url` data URLs in user messages and tool results. With `--vision-urls` (it needs + `--vision`), a part may name a public HTTPS URL instead, fetched as 0.6.6 fetched it: port 443 without credentials + or a fragment; every address the host resolves to public (no private, loopback, link-local, carrier-grade NAT, + documentation, multicast or metadata address, and for IPv6 global unicast only, without 6to4 or Teredo); TLS + verified for the host against the system's certificates, on the address that was checked; up to 3 redirects, + each checked again; a declared `image/jpeg`, `image/png` or `image/webp`, uncompressed; 10 MB an image and 20 MB + a request across data URLs and downloads; 10 s a download and 30 s a request's downloads. The refusals are + 0.6.6's words; a TLS failure, like any other failed connection, is "image download failed or timed out". Host + names that aren't ASCII and IPv6 address literals are refused. Without the flag, an HTTPS URL is refused with the + flag's name. - PNG and JPEG are decoded by the platform's decoder (ImageIO on macOS). WebP is refused by name until a decoder exists; other formats are refused. - The limits and the processing are 0.6.6's: EXIF orientation, alpha composited over white, the GLM5-Next processor's diff --git a/tools/zig/vision_served.py b/tools/zig/vision_served.py index 49bd56bca6..c58a4b5bf6 100644 --- a/tools/zig/vision_served.py +++ b/tools/zig/vision_served.py @@ -6,7 +6,8 @@ model's image marker beside a real image is ordinary text (images come from the request's image parts, #511); drafted equals ``"draft": false`` and concurrent equals alone with images; an image conversation's next turn resumes past its image, and another image under the same placeholders resumes none of the first one's rows; and the refusals (WebP by name, other formats, an image outside a -user or tool message, too many images, remote URLs, bad data URLs, a bad detail). +user or tool message, too many images, remote URLs without --vision-urls, bad data URLs, a bad detail); tools/zig/vision_urls_served.py +checks a server started with --vision-urls. """ from __future__ import annotations @@ -151,7 +152,8 @@ def turns(url: str) -> tuple[list, list]: ("GIF", [user(image_part(data_url(gif, "image/gif")), text("hi"))], "not PNG or JPEG"), ("an image in an assistant message", [user(text("hi")), {"role": "assistant", "content": [image_part(url_a)]}, user(text("ok"))], "user and tool messages only"), ("too many images", [user(*[image_part(url_a)] * 5, text("hi"))], "at most"), - ("a remote URL", [user(image_part("https://example.com/cat.png"), text("hi"))], "data: URL"), + ("a remote URL without --vision-urls", [user(image_part("https://example.com/cat.png"), text("hi"))], "--vision-urls"), + ("a URL that is neither data nor https", [user(image_part("http://example.com/cat.png"), text("hi"))], "data URLs or public HTTPS URLs"), ("bad base64", [user(image_part("data:image/png;base64,@@@@"), text("hi"))], "encoding"), ("a bad detail", [user(image_part(url_a, "medium"), text("hi"))], "detail"), ("bytes that decode as nothing", [user(image_part(data_url(b"\x89PNG\r\n\x1a\n" + bytes(32), "image/png")), text("hi"))], "could not be decoded"), diff --git a/tools/zig/vision_urls_served.py b/tools/zig/vision_urls_served.py new file mode 100644 index 0000000000..f383eabbf6 --- /dev/null +++ b/tools/zig/vision_urls_served.py @@ -0,0 +1,109 @@ +"""Image URLs served end to end on a running ``tensorfold-native --vision --vision-urls`` (#565's URL checks). + + python tools/zig/vision_urls_served.py --url http://127.0.0.1:8000 + +Checks, against public hosts: an HTTPS image URL answers exactly as the same bytes sent as a data URL (the prompt's +tokens and the greedy reply), and so does a URL that redirects to it; a URL and a data URL in one request; and the +refusals images_http.py gave, before any token (HTTP status, content type, a host that resolves to a private +address, a name that is never public, an address literal that isn't public, TLS that doesn't verify, a scheme, port, +credentials or fragment the URL rules refuse, an unresolvable host). The fetch's own rules (redirect limits, +lengths, chunking, encodings, deadlines) are the unit tests in zig/src/server/media_fetch.zig. +""" + +from __future__ import annotations + +import argparse +import base64 +import json +import ssl +import sys +import urllib.error +import urllib.request + +IMAGE = "https://raw.githubusercontent.com/ashhart/TensorFold/main/assets/tensorfold-hero.png" +REDIRECT = "https://github.com/ashhart/TensorFold/raw/main/assets/tensorfold-hero.png" # 302 to IMAGE's host +OTHER = "https://raw.githubusercontent.com/ashhart/TensorFold/main/assets/tensorfold-cuda-banner.png" + + +def post(url: str, body: dict) -> tuple[int, dict]: + req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=1800) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + return e.code, json.loads(e.read() or b"{}") + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--url", default="http://127.0.0.1:8000") + ap.add_argument("--tokens", type=int, default=48) + args = ap.parse_args() + with urllib.request.urlopen(args.url + "/v1/models") as r: + model = json.loads(r.read())["data"][0]["id"] + try: # python.org's macOS builds ship no CA store until "Install Certificates" runs + import certifi + tls = ssl.create_default_context(cafile=certifi.where()) + except ImportError: + tls = ssl.create_default_context() + with urllib.request.urlopen(IMAGE, timeout=30, context=tls) as r: + inline = "data:image/png;base64," + base64.b64encode(r.read()).decode() + failures = 0 + + def ask(*parts) -> tuple[int, dict]: + return post(args.url, {"model": model, "messages": [{"role": "user", "content": list(parts)}], "max_tokens": args.tokens, + "temperature": 0, "chat_template_kwargs": {"enable_thinking": False}}) + + def image(url: str) -> dict: + return {"type": "image_url", "image_url": {"url": url}} + + def text(t: str) -> dict: + return {"type": "text", "text": t} + + def check(label: str, ok: bool, detail: str = "") -> None: + nonlocal failures + failures += not ok + print(f"{'ok ' if ok else 'FAIL'} {label}{': ' + detail if detail else ''}") + + def same(label: str, a: tuple[int, dict], b: tuple[int, dict]) -> None: + ok = a[0] == 200 and b[0] == 200 and a[1]["usage"]["prompt_tokens"] == b[1]["usage"]["prompt_tokens"] and \ + a[1]["choices"][0]["message"]["content"] == b[1]["choices"][0]["message"]["content"] + detail = f"HTTP {a[0]}/{b[0]}" if a[0] != 200 or b[0] != 200 else \ + f"{a[1]['usage']['prompt_tokens']} prompt tokens, {a[1]['choices'][0]['message']['content'][:60]!r}" + if a[0] != 200 or b[0] != 200: + detail += " " + json.dumps(a[1].get("error") or b[1].get("error"))[:120] + check(label, ok, detail) + + q = text("Describe this image in one sentence.") + by_data = ask(image(inline), q) + same("an HTTPS image URL answers as its bytes in a data URL", ask(image(IMAGE), q), by_data) + same("a URL that redirects to the image answers the same", ask(image(REDIRECT), q), by_data) + two = ask(image(OTHER), image(inline), text("How do these two images differ?")) + check("a URL and a data URL in one request answer", two[0] == 200, f"HTTP {two[0]} {json.dumps(two[1].get('error', ''))[:100]}") + + refusals = [ + ("an HTTP error", "https://raw.githubusercontent.com/ashhart/TensorFold/main/assets/no-such-image.png", "image download returned HTTP 404"), + ("a page that isn't an image", "https://example.com/", "image URL content type must be JPEG, PNG or WebP"), + ("a host that resolves to a private address", "https://localtest.me/x.png", "image URLs must resolve only to public internet addresses"), + ("a private address literal", "https://169.254.169.254/latest/meta-data", "image URLs must resolve only to public internet addresses"), + ("localhost", "https://localhost/x.png", "image URLs must use public internet hosts"), + ("cloud metadata by name", "https://metadata.google.internal/x.png", "image URLs must use public internet hosts"), + ("an expired certificate", "https://expired.badssl.com/", "image download failed or timed out"), + ("a certificate for another host", "https://wrong.host.badssl.com/", "image download failed or timed out"), + ("a self-signed certificate", "https://self-signed.badssl.com/", "image download failed or timed out"), + ("plain HTTP", "http://example.com/x.png", "images require data URLs or public HTTPS URLs"), + ("another port", "https://example.com:8443/x.png", "image URL must be HTTPS on port 443, without credentials or a fragment"), + ("credentials", "https://user:pw@example.com/x.png", "image URL must be HTTPS on port 443, without credentials or a fragment"), + ("a fragment", "https://example.com/x.png#a", "image URL must be HTTPS on port 443, without credentials or a fragment"), + ("a host that never resolves", "https://no-such-host.invalid/x.png", "image host could not be resolved"), + ] + for label, url, words in refusals: + code, r = ask(image(url), text("hi")) + message = r.get("error", {}).get("message", json.dumps(r)) + check(f"refused {label}", code == 400 and message == words, f"HTTP {code} {message[:100]!r}") + print("PASS" if failures == 0 else f"FAIL: {failures}") + return 0 if failures == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/zig/src/server/cli.zig b/zig/src/server/cli.zig index c30c26a1d4..02f7578161 100644 --- a/zig/src/server/cli.zig +++ b/zig/src/server/cli.zig @@ -50,7 +50,7 @@ pub const flags = [_]Flag{ .{ .name = "--metrics-open", .kind = .store_true, .native = true }, .{ .name = "--dashboard", .kind = .store_true, .native = true }, .{ .name = "--vision", .kind = .store_true, .native = true }, - .{ .name = "--vision-urls", .kind = .store_true }, + .{ .name = "--vision-urls", .kind = .store_true, .native = true }, .{ .name = "--vision-offload", .kind = .store_true }, .{ .name = "--vision-max-images", .native = true }, .{ .name = "--vision-image-tokens", .native = true }, @@ -168,6 +168,7 @@ pub const Args = struct { master_port: u16 = 29551, policy: []const u8 = "", // every --policy joined by commas vision: bool = false, // image input (GLM-5.3-Flash): data-URL image_url parts in user messages + vision_urls: bool = false, // with --vision, public HTTPS image URLs too (media_fetch.zig) vision_max_images: u32 = 4, vision_image_tokens: u32 = 4096, }; @@ -221,6 +222,7 @@ pub fn parse(a: Allocator, argv: []const []const u8, u: *Usage) error{ Usage, Ou } out.model = model orelse return fail(u, a, "the following arguments are required: model", .{}); try ranks(u, a, out); + if (out.vision_urls and !out.vision) return fail(u, a, "--vision-urls needs --vision", .{}); out.alias = alias.items; out.api_key = keys.items; return out; @@ -275,7 +277,7 @@ fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usa const n = try int(u, a, name, v); if (n < 0) return fail(u, a, "argument --compact-keep: expected a token count from 0: '{s}'", .{v}); out.compact_keep = @intCast(n); - } else if (is(name, "--compact-memory")) out.compact_memory = v else if (is(name, "--slide")) out.slide = true else if (is(name, "--slide-graph")) out.slide_graph = v else if (is(name, "--parallel")) out.parallel = v else if (is(name, "--backend")) out.backend = v else if (is(name, "--vision")) out.vision = true else if (is(name, "--vision-max-images")) { + } else if (is(name, "--compact-memory")) out.compact_memory = v else if (is(name, "--slide")) out.slide = true else if (is(name, "--slide-graph")) out.slide_graph = v else if (is(name, "--parallel")) out.parallel = v else if (is(name, "--backend")) out.backend = v else if (is(name, "--vision")) out.vision = true else if (is(name, "--vision-urls")) out.vision_urls = true else if (is(name, "--vision-max-images")) { const n = try int(u, a, name, v); if (n < 1 or n > 64) return fail(u, a, "argument --vision-max-images: expected 1 to 64 images: '{s}'", .{v}); out.vision_max_images = @intCast(n); @@ -458,6 +460,10 @@ test "parse and capabilities share the table" { try std.testing.expectError(error.Usage, parse(a, &.{ "m", "--compact-at", "0" }, &u)); try std.testing.expectError(error.Usage, parse(a, &.{ "m", "--compact-at", "2" }, &u)); try std.testing.expectError(error.Usage, parse(a, &.{ "m", "--compact-keep", "-1" }, &u)); + const urls = try parse(a, &.{ "m", "--vision", "--vision-urls" }, &u); + try std.testing.expect(urls.vision and urls.vision_urls); + try std.testing.expectError(error.Usage, parse(a, &.{ "m", "--vision-urls" }, &u)); + try std.testing.expectEqualStrings("--vision-urls needs --vision", u.message); } test "--device and --segments: CUDA builds serve them, values checked" { diff --git a/zig/src/server/images.zig b/zig/src/server/images.zig index ba1253ef2c..d99b121300 100644 --- a/zig/src/server/images.zig +++ b/zig/src/server/images.zig @@ -6,6 +6,7 @@ const json = @import("json.zig"); const errors = @import("errors.zig"); const messages_mod = @import("messages.zig"); const model_text = @import("model_text.zig"); +const media_fetch = @import("media_fetch.zig"); const Value = json.Value; const Cx = errors.Cx; @@ -41,10 +42,44 @@ fn parts(cx: *Cx, messages: Value) errors.Refused![]const Part { return out.items; } -/// A data URL's bytes (base64 or percent-encoded); remote URLs are refused (the native server fetches nothing). +/// --vision-urls: how a public HTTPS image's bytes are fetched (media_fetch.zig, or a test's fixtures). +pub const Fetch = struct { + ctx: ?*anyopaque = null, + io: std.Io, + get: *const fn (ctx: ?*anyopaque, a: std.mem.Allocator, io: std.Io, url: []const u8, max_bytes: usize, deadline: std.Io.Timestamp, f: *media_fetch.Failure) media_fetch.Error![]const u8, + + /// The network, as media_fetch checks it. + pub fn network(io: std.Io) Fetch { + return .{ .io = io, .get = struct { + fn get(_: ?*anyopaque, a: std.mem.Allocator, i: std.Io, url: []const u8, max_bytes: usize, deadline: std.Io.Timestamp, f: *media_fetch.Failure) media_fetch.Error![]const u8 { + return (try media_fetch.fetch(a, i, url, max_bytes, deadline, &media_fetch.image_media, f)).data; + } + }.get }; + } +}; + +/// An image part's bytes, at most `limit`: a data URL's, or with --vision-urls (`fetch`) a public HTTPS URL's, fetched +/// before `deadline` (images.py _check_source and load_images). +pub fn sourceBytes(cx: *Cx, fetch: ?Fetch, url: []const u8, limit: usize, deadline: std.Io.Timestamp) errors.Refused![]const u8 { + if (std.ascii.startsWithIgnoreCase(url, "data:")) { + const bytes = try dataBytes(cx, url); + if (bytes.len > limit) return cx.refuse("the request's images exceed 20 MB encoded"); + return bytes; + } + if (!std.mem.startsWith(u8, url, "https://")) return cx.refuse("images require data URLs or public HTTPS URLs"); + const f = fetch orelse return cx.refuse("image URLs are off on this server; send the image as a data URL, or start the server with --vision-urls"); + if (url.len > media_fetch.max_url_chars) return cx.refuse("image URL is too long"); + var failure: media_fetch.Failure = .{}; + const bytes = f.get(f.ctx, cx.a, f.io, url, limit, deadline, &failure) catch |e| switch (e) { + error.OutOfMemory => return error.OutOfMemory, + error.Media => return cx.refuse(failure.text), + }; + if (bytes.len == 0) return cx.refuse("image is empty or exceeds the encoded byte limit"); + return bytes; +} + +/// A data URL's bytes (base64 or percent-encoded). pub fn dataBytes(cx: *Cx, url: []const u8) errors.Refused![]const u8 { - if (std.ascii.startsWithIgnoreCase(url, "http://") or std.ascii.startsWithIgnoreCase(url, "https://")) - return cx.refuse("image URLs are not fetched by this server; send the image inline as a data: URL (data:image/png;base64,...)"); if (!std.ascii.startsWithIgnoreCase(url, "data:")) return cx.refuse("invalid image data URL"); const comma = std.mem.indexOfScalar(u8, url, ',') orelse return cx.refuse("invalid image data URL"); const header = url[5..comma]; @@ -179,7 +214,7 @@ pub fn encodeShielded(text: model_text.Text, a: std.mem.Allocator, rendered: []c /// The prompt with each image's placeholder expanded to its tokens, the images for the engine and the prompt as the /// cache matches it; null when the engine reads no images. Images are counted from the request's image parts; the /// rendered placeholders are the template's alone (text that spells a marker was shielded), one per part. -pub fn expand(vision: ?api.Vision, cx: *Cx, messages: Value, ids: []const u32, history_len: usize) errors.Refused!?Expanded { +pub fn expand(vision: ?api.Vision, fetch: ?Fetch, cx: *Cx, messages: Value, ids: []const u32, history_len: usize) errors.Refused!?Expanded { const v = vision orelse return null; const ps = try parts(cx, messages); var marks: usize = 0; @@ -192,10 +227,11 @@ pub fn expand(vision: ?api.Vision, cx: *Cx, messages: Value, ids: []const u32, h const prepared = try cx.a.alloc(api.PreparedImage, ps.len); var bytes_total: usize = 0; var extra: usize = 0; + // every URL's download inside one request's seconds (images.py total_timeout_seconds) + const deadline: std.Io.Timestamp = if (fetch) |f| std.Io.Clock.awake.now(f.io).addDuration(.fromSeconds(media_fetch.total_s)) else .{ .nanoseconds = 0 }; for (ps, prepared, 0..) |p, *out, i| { - const bytes = try dataBytes(cx, p.url); + const bytes = try sourceBytes(cx, fetch, p.url, @min(max_image_bytes, max_request_bytes - bytes_total), deadline); bytes_total += bytes.len; - if (bytes_total > max_request_bytes) return cx.refuse("the request's images exceed 20 MB encoded"); switch (sniff(bytes)) { // the Python frontend's formats (images.py: JPEG, PNG, WebP), WebP not yet decoded here .png, .jpeg => {}, .webp => return cx.refuse(try std.fmt.allocPrint(cx.a, "image {d} is WebP, which this server does not decode yet; send PNG or JPEG", .{i + 1})), @@ -240,8 +276,16 @@ test "data URLs decode; remote URLs are refused" { var cx: Cx = .{ .a = arena.allocator() }; try std.testing.expectEqualStrings("hi!", try dataBytes(&cx, "data:image/png;base64,aGkh")); try std.testing.expectEqualStrings("a b", try dataBytes(&cx, "data:text/plain,a%20b")); - try std.testing.expectError(error.Refused, dataBytes(&cx, "https://example.com/x.png")); try std.testing.expectError(error.Refused, dataBytes(&cx, "data:image/png;base64,***")); + // without --vision-urls an https URL is refused with the flag's name; other schemes always + const never: std.Io.Timestamp = .{ .nanoseconds = 0 }; + try std.testing.expectError(error.Refused, sourceBytes(&cx, null, "https://example.com/x.png", max_image_bytes, never)); + try std.testing.expectEqualStrings("image URLs are off on this server; send the image as a data URL, or start the server with --vision-urls", cx.message); + for ([_][]const u8{ "http://example.com/x.png", "ftp://example.com/x.png", "HTTPS://example.com/x.png", "file:///etc/passwd" }) |u| { + try std.testing.expectError(error.Refused, sourceBytes(&cx, null, u, max_image_bytes, never)); + try std.testing.expectEqualStrings("images require data URLs or public HTTPS URLs", cx.message); + } + try std.testing.expectError(error.Refused, sourceBytes(&cx, null, "data:,abc", 2, never)); } fn fakePrepare(ctx: *anyopaque, a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage { @@ -268,7 +312,7 @@ test "placeholders expand to each image's tokens, the history and cache key with .err => return error.TestUnexpectedResult, }; const ids = [_]u32{ 1, 9, 2, 3, 9, 4 }; - const x = (try expand(v, &cx, msgs, &ids, 4)).?; + const x = (try expand(v, null, &cx, msgs, &ids, 4)).?; try std.testing.expectEqualSlices(u32, &.{ 1, 9, 9, 2, 3, 9, 9, 9, 4 }, x.ids); try std.testing.expectEqual(@as(usize, 5), x.history_len); // the first image is in the history, the second not try std.testing.expectEqual(@as(u32, 1), x.images[0].at); @@ -276,10 +320,52 @@ test "placeholders expand to each image's tokens, the history and cache key with try std.testing.expect(x.cache_key[1] >= 0x8000_0000 and x.cache_key[1] != x.cache_key[2]); try std.testing.expectEqual(@as(u32, 2), x.cache_key[3]); // a placeholder the images do not account for is refused - try std.testing.expectError(error.Refused, expand(v, &cx, msgs, &[_]u32{ 9, 9, 9 }, 0)); + try std.testing.expectError(error.Refused, expand(v, null, &cx, msgs, &[_]u32{ 9, 9, 9 }, 0)); _ = messages_mod; } +test "--vision-urls: an https part's bytes come from the fetch, within what the request has left" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var cx: Cx = .{ .a = a }; + var dummy: u8 = 0; + const v: api.Vision = .{ .ctx = &dummy, .prepare = fakePrepare, .image_token = 9, .image_tokens = 64, .max_images = 4 }; + const Pages = struct { + var limits: [4]usize = undefined; + var n: usize = 0; + fn get(_: ?*anyopaque, al: std.mem.Allocator, _: std.Io, url: []const u8, max_bytes: usize, _: std.Io.Timestamp, f: *media_fetch.Failure) media_fetch.Error![]const u8 { + limits[n] = max_bytes; + n += 1; + if (std.mem.eql(u8, url, "https://e.com/a.jpg")) return al.dupe(u8, "\xff\xd8\xffxyz"); + f.text = "image download returned HTTP 404"; + return error.Media; + } + }; + const fetch: Fetch = .{ .io = std.testing.io, .get = Pages.get }; + const text = + \\[{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:,%FF%D8%FFab"}}, + \\ {"type": "image_url", "image_url": {"url": "https://e.com/a.jpg"}}]}] + ; + const msgs = switch (try json.parseText(a, text)) { + .ok => |m| m, + .err => return error.TestUnexpectedResult, + }; + const x = (try expand(v, fetch, &cx, msgs, &[_]u32{ 1, 9, 9, 2 }, 0)).?; + try std.testing.expectEqualSlices(u32, &.{ 1, 9, 9, 9, 9, 9, 2 }, x.ids); // 2 tokens, then the fetched image's 3 + try std.testing.expectEqual(@as(u32, 3), x.images[1].at); + try std.testing.expectEqual(@as(usize, max_image_bytes), Pages.limits[0]); // 5 bytes used of 20 MB: 10 MB left + // the fetch's refusal is the request's; without the fetch the URL is refused by the flag's name + const missing = switch (try json.parseText(a, "[{\"role\": \"user\", \"content\": [{\"type\": \"image_url\", \"image_url\": {\"url\": \"https://e.com/gone.png\"}}]}]")) { + .ok => |m| m, + .err => return error.TestUnexpectedResult, + }; + try std.testing.expectError(error.Refused, expand(v, fetch, &cx, missing, &[_]u32{9}, 0)); + try std.testing.expectEqualStrings("image download returned HTTP 404", cx.message); + try std.testing.expectError(error.Refused, expand(v, null, &cx, missing, &[_]u32{9}, 0)); + try std.testing.expectEqualStrings("image URLs are off on this server; send the image as a data URL, or start the server with --vision-urls", cx.message); +} + /// A test tokenizer: "<|image|>" is token 9 unless read plainly, every other byte its own id plus 100. const MarkText = struct { fn text() model_text.Text { diff --git a/zig/src/server/media_fetch.zig b/zig/src/server/media_fetch.zig new file mode 100644 index 0000000000..d642ce0b2e --- /dev/null +++ b/zig/src/server/media_fetch.zig @@ -0,0 +1,497 @@ +//! Public HTTPS images for --vision-urls, as TensorFold 0.6.6's server fetched them (vision/images_http.py): an https +//! URL on port 443 without credentials or a fragment, its host resolved and every address checked public, a TLS +//! connection verified for the host on an address that was checked, GET with identity encoding, up to 3 redirects +//! (each checked the same way), a declared media type the caller accepts, the bytes within the caller's limit, all +//! inside a deadline. +const std = @import("std"); +const Io = std.Io; +const net = std.Io.net; + +pub const Error = error{ OutOfMemory, Media }; + +/// The failure's words for the client (the request is refused with them). +pub const Failure = struct { text: []const u8 = "" }; + +/// images.py's ImageLimits: a URL's characters, the redirects followed, one download's seconds and a request's. +pub const max_url_chars = 4096; +pub const max_redirects = 3; +pub const timeout_s = 10; +pub const total_s = 30; + +/// images_http.MEDIA_TYPES: the declared types an image URL may answer with (WebP is refused after, by its bytes). +pub const image_media = [_][]const u8{ "image/jpeg", "image/png", "image/webp" }; + +fn fail(f: *Failure, text: []const u8) Error { + f.text = text; + return error.Media; +} + +/// Python ipaddress: is_global and not multicast or reserved, nor 192.0.0.0/24 or 168.63.129.16; no IPv6 address +/// that embeds an IPv4 one (mapped, 6to4, Teredo). +pub fn publicIp(a: net.IpAddress) bool { + switch (a) { + .ip4 => |v| { + const x = std.mem.readInt(u32, &v.bytes, .big); + const blocked = [_]struct { [4]u8, u5 }{ + .{ .{ 0, 0, 0, 0 }, 8 }, .{ .{ 10, 0, 0, 0 }, 8 }, .{ .{ 100, 64, 0, 0 }, 10 }, .{ .{ 127, 0, 0, 0 }, 8 }, + .{ .{ 169, 254, 0, 0 }, 16 }, .{ .{ 172, 16, 0, 0 }, 12 }, .{ .{ 192, 0, 0, 0 }, 24 }, .{ .{ 192, 0, 2, 0 }, 24 }, + .{ .{ 192, 168, 0, 0 }, 16 }, .{ .{ 198, 18, 0, 0 }, 15 }, .{ .{ 198, 51, 100, 0 }, 24 }, .{ .{ 203, 0, 113, 0 }, 24 }, + .{ .{ 224, 0, 0, 0 }, 4 }, .{ .{ 240, 0, 0, 0 }, 4 }, + }; + for (blocked) |blk| { + const mask = ~@as(u32, 0) << @intCast(32 - @as(u6, blk[1])); + if (x & mask == std.mem.readInt(u32, &blk[0], .big) & mask) return false; + } + return !std.mem.eql(u8, &v.bytes, &.{ 168, 63, 129, 16 }); + }, + .ip6 => |v| { + const b = v.bytes; + // global unicast 2000::/3 only, less documentation (2001:db8::/32), the 2001::/23 IETF block (Teredo + // 2001::/32 among it) and 6to4 (2002::/16) + if (b[0] & 0xe0 != 0x20) return false; + if (b[0] == 0x20 and b[1] == 0x01 and b[2] == 0x0d and b[3] == 0xb8) return false; + if (b[0] == 0x20 and b[1] == 0x01 and b[2] < 0x02) return false; + return !(b[0] == 0x20 and b[1] == 0x02); + }, + } +} + +/// A URL as a request takes it: the lowercased host and the percent-quoted path and query. +pub const Url = struct { host: []const u8, target: []const u8 }; + +/// images_http._url: https, a host, port 443, no credentials, fragment, backslash, whitespace or controls. A host +/// that isn't ASCII (an IDNA name) or is an IPv6 literal is refused: std has no IDNA encoder, and TLS here verifies +/// names. +pub fn parseUrl(a: std.mem.Allocator, value: []const u8, f: *Failure) Error!Url { + if (value.len > max_url_chars) return fail(f, "image URL is too long or contains whitespace/control characters"); + for (value) |c| if (c <= 32 or c == 127) return fail(f, "image URL is too long or contains whitespace/control characters"); + const bad = "image URL must be HTTPS on port 443, without credentials or a fragment"; + if (!std.ascii.startsWithIgnoreCase(value, "https://")) return fail(f, bad); + if (std.mem.indexOfAny(u8, value, "\\#") != null) return fail(f, bad); + const rest = value["https://".len..]; + const end = std.mem.indexOfAny(u8, rest, "/?") orelse rest.len; + const authority = rest[0..end]; + if (std.mem.indexOfScalar(u8, authority, '@') != null or std.mem.startsWith(u8, authority, "[")) return fail(f, bad); + var host = authority; + if (std.mem.lastIndexOfScalar(u8, authority, ':')) |c| { + const port = authority[c + 1 ..]; + if (port.len > 0 and !std.mem.eql(u8, port, "443")) return fail(f, bad); + host = authority[0..c]; + } + if (host.len == 0 or std.mem.indexOfScalar(u8, host, '%') != null) return fail(f, bad); + for (host) |c| if (c >= 128) return fail(f, bad); + const lower = try std.ascii.allocLowerString(a, host); + const name = std.mem.trimEnd(u8, lower, "."); + for ([_][]const u8{ "localhost", "metadata.google.internal", "instance-data" }) |n| if (std.mem.eql(u8, name, n)) return fail(f, "image URLs must use public internet hosts"); + // the path and query, percent-quoted as urllib.parse.quote(safe=...) leaves them + var t: std.ArrayList(u8) = .empty; + const tail = rest[end..]; + if (tail.len == 0 or tail[0] == '?') try t.append(a, '/'); + var in_query = false; + var query_at: usize = 0; + for (tail) |c| { + if (c == '?' and !in_query) { + in_query = true; + try t.append(a, '?'); + query_at = t.items.len; + continue; + } + const safe = std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "/%:@!$&'()*+,;=-._~", c) != null or (in_query and c == '?'); + if (safe) try t.append(a, c) else try t.print(a, "%{X:0>2}", .{c}); + } + if (in_query and t.items.len == query_at) t.items.len -= 1; // an empty query, as urlsplit drops it + return .{ .host = lower, .target = t.items }; +} + +/// The location a redirect names, resolved against `base` (urljoin's absolute, scheme-relative, absolute-path and +/// relative forms). +pub fn join(a: std.mem.Allocator, base: []const u8, location: []const u8) ![]const u8 { + if (std.ascii.startsWithIgnoreCase(location, "https://") or std.ascii.startsWithIgnoreCase(location, "http://")) return a.dupe(u8, location); + if (std.mem.startsWith(u8, location, "//")) return std.fmt.allocPrint(a, "https:{s}", .{location}); + const rest = base["https://".len..]; + const end = std.mem.indexOfAny(u8, rest, "/?") orelse rest.len; + const origin = base[0 .. "https://".len + end]; + if (std.mem.startsWith(u8, location, "/")) return std.fmt.allocPrint(a, "{s}{s}", .{ origin, location }); + const path = rest[end..][0 .. std.mem.indexOfScalar(u8, rest[end..], '?') orelse rest.len - end]; + const dir = if (std.mem.lastIndexOfScalar(u8, path, '/')) |s| path[0 .. s + 1] else "/"; + return std.fmt.allocPrint(a, "{s}{s}{s}", .{ origin, dir, location }); +} + +fn remaining(io: Io, deadline: Io.Timestamp, f: *Failure) Error!i64 { + const left = Io.Clock.awake.now(io).durationTo(deadline).toMilliseconds(); + if (left <= 0) return fail(f, "image download timed out"); + return left; +} + +/// A fetched body and its declared media type. +pub const Body = struct { data: []u8, media: []const u8 }; + +/// What one request gave: the body, or a redirect's location. +pub const Got = union(enum) { body: Body, redirect: []const u8 }; + +/// The bytes of `url` and its media type (one of `media_types`), at most `max_bytes`, before `deadline` and within +/// one download's seconds, redirects followed and each checked again. +pub fn fetch(a: std.mem.Allocator, io: Io, url: []const u8, max_bytes: usize, deadline: Io.Timestamp, media_types: []const []const u8, f: *Failure) Error!Body { + return fetchVia(a, io, url, max_bytes, deadline, media_types, f, Network{}); +} + +/// fetch over `via`, whose request(a, io, url, max_bytes, deadline, media_types, f) answers one checked URL. +pub fn fetchVia(a: std.mem.Allocator, io: Io, url_in: []const u8, max_bytes: usize, deadline_in: Io.Timestamp, media_types: []const []const u8, f: *Failure, via: anytype) Error!Body { + const one = Io.Clock.awake.now(io).addDuration(.fromSeconds(timeout_s)); + const deadline = if (one.nanoseconds < deadline_in.nanoseconds) one else deadline_in; + var url = url_in; + var hop: usize = 0; + while (true) : (hop += 1) { + const u = try parseUrl(a, url, f); + switch (try via.request(a, io, u, max_bytes, deadline, media_types, f)) { + .body => |b| return b, + .redirect => |location| { + if (hop == max_redirects) return fail(f, "image download has too many redirects"); + url = try join(a, url, location); + }, + } + } +} + +/// The GET a checked URL is asked with. +pub fn ask(w: *Io.Writer, u: Url, accept: []const u8) Io.Writer.Error!void { + try w.print("GET {s} HTTP/1.1\r\nHost: {s}\r\nAccept: {s}\r\nAccept-Encoding: identity\r\nUser-Agent: TensorFold-native\r\nConnection: close\r\n\r\n", .{ u.target, u.host, accept }); + try w.flush(); +} + +/// The response read from `r`: a redirect's location, or a 200's body when its encoding, declared type and length +/// pass (Content-Length or chunked, else to the end of the stream). +pub fn answer(a: std.mem.Allocator, io: Io, r: *Io.Reader, max_bytes: usize, deadline: Io.Timestamp, media_types: []const []const u8, f: *Failure) Error!Got { + const broke = "image download failed or timed out"; + const too_big = "image response exceeds the encoded byte limit"; + const status_line = r.takeDelimiterInclusive('\n') catch return fail(f, broke); + if (status_line.len < 12 or !std.mem.startsWith(u8, status_line, "HTTP/1.")) return fail(f, broke); + const status = std.fmt.parseInt(u16, status_line[9..12], 10) catch return fail(f, broke); + var location: ?[]const u8 = null; + var media: []const u8 = ""; + var length: ?usize = null; + var chunked = false; + var encoded = false; + var header_bytes: usize = 0; + while (true) { + const line = r.takeDelimiterInclusive('\n') catch return fail(f, broke); + header_bytes += line.len; + if (header_bytes > 64 * 1024) return fail(f, broke); + const l = std.mem.trimEnd(u8, line, "\r\n"); + if (l.len == 0) break; + const colon = std.mem.indexOfScalar(u8, l, ':') orelse continue; + const key = std.mem.trim(u8, l[0..colon], " \t"); + const val = std.mem.trim(u8, l[colon + 1 ..], " \t"); + if (std.ascii.eqlIgnoreCase(key, "location")) { + location = try a.dupe(u8, val); + } else if (std.ascii.eqlIgnoreCase(key, "content-type")) { + media = try std.ascii.allocLowerString(a, std.mem.trim(u8, val[0 .. std.mem.indexOfScalar(u8, val, ';') orelse val.len], " \t")); + } else if (std.ascii.eqlIgnoreCase(key, "content-length")) { + if (val.len == 0) return fail(f, too_big); + for (val) |c| if (!std.ascii.isDigit(c)) return fail(f, too_big); + length = std.fmt.parseInt(usize, val, 10) catch return fail(f, too_big); + } else if (std.ascii.eqlIgnoreCase(key, "transfer-encoding")) { + chunked = std.ascii.findIgnoreCase(val, "chunked") != null; + } else if (std.ascii.eqlIgnoreCase(key, "content-encoding") and !std.ascii.eqlIgnoreCase(val, "identity")) encoded = true; + } + _ = try remaining(io, deadline, f); + switch (status) { + 301, 302, 303, 307, 308 => return .{ .redirect = location orelse return fail(f, "image redirect has no destination") }, + 200 => {}, + else => return fail(f, try std.fmt.allocPrint(a, "image download returned HTTP {d}", .{status})), + } + if (encoded) return fail(f, "compressed HTTP image responses are unsupported"); + for (media_types) |m| { + if (std.mem.eql(u8, m, media)) break; + } else return fail(f, "image URL content type must be JPEG, PNG or WebP"); + if (length) |n| if (n > max_bytes) return fail(f, too_big); + var data: std.ArrayList(u8) = .empty; + if (chunked) { + while (true) { + _ = try remaining(io, deadline, f); + const size_line = r.takeDelimiterInclusive('\n') catch return fail(f, broke); + const hex = std.mem.trim(u8, size_line[0 .. std.mem.indexOfScalar(u8, size_line, ';') orelse size_line.len], " \t\r\n"); + const n = std.fmt.parseInt(usize, hex, 16) catch return fail(f, broke); + if (n == 0) break; + if (n > max_bytes - data.items.len) return fail(f, too_big); + try readInto(a, io, r, &data, n, deadline, f); + const crlf = r.takeDelimiterInclusive('\n') catch return fail(f, broke); + if (std.mem.trimEnd(u8, crlf, "\r\n").len != 0) return fail(f, broke); + } + } else if (length) |n| { + try readInto(a, io, r, &data, n, deadline, f); + } else while (true) { // no length: to the end of the stream (Connection: close) + _ = try remaining(io, deadline, f); + const piece = r.peekGreedy(1) catch |e| switch (e) { + error.EndOfStream => break, + else => return fail(f, broke), + }; + if (piece.len > max_bytes - data.items.len) return fail(f, too_big); + try data.appendSlice(a, piece); + r.toss(piece.len); + } + _ = try remaining(io, deadline, f); + return .{ .body = .{ .data = data.items, .media = media } }; +} + +/// Exactly `n` more bytes from `r` onto `data`, in whatever pieces the reader's buffer holds. +fn readInto(a: std.mem.Allocator, io: Io, r: *Io.Reader, data: *std.ArrayList(u8), n: usize, deadline: Io.Timestamp, f: *Failure) Error!void { + var left = n; + while (left > 0) { + _ = try remaining(io, deadline, f); + const piece = r.peekGreedy(1) catch return fail(f, "image download failed or timed out"); + const take = @min(piece.len, left); + try data.appendSlice(a, piece[0..take]); + r.toss(take); + left -= take; + } +} + +/// A TCP connection to the checked address on port 443, its connect bounded by `ms` (std's connect has no timeout +/// yet: a nonblocking connect and poll) and its sends and reads by the socket's timeouts. +fn connect(addr: net.IpAddress, ms: i64, f: *Failure) Error!net.Stream { + const c = std.c; + const failed = "image download failed or timed out"; + var storage: c.sockaddr.storage = undefined; + var len: c.socklen_t = undefined; + switch (addr) { + .ip4 => |v| { + const sa: *c.sockaddr.in = @ptrCast(@alignCast(&storage)); + sa.* = std.mem.zeroes(c.sockaddr.in); + sa.family = c.AF.INET; + sa.port = std.mem.nativeToBig(u16, 443); + sa.addr = @bitCast(v.bytes); + len = @sizeOf(c.sockaddr.in); + }, + .ip6 => |v| { + const sa: *c.sockaddr.in6 = @ptrCast(@alignCast(&storage)); + sa.* = std.mem.zeroes(c.sockaddr.in6); + sa.family = c.AF.INET6; + sa.port = std.mem.nativeToBig(u16, 443); + sa.addr = v.bytes; + len = @sizeOf(c.sockaddr.in6); + }, + } + const fd = c.socket(@as(c_uint, storage.family), c.SOCK.STREAM, 0); + if (fd < 0) return fail(f, failed); + errdefer _ = c.close(fd); + _ = c.fcntl(fd, c.F.SETFD, @as(c_int, c.FD_CLOEXEC)); + const flags = c.fcntl(fd, c.F.GETFL); + const nonblock: c_int = @bitCast(@as(u32, @bitCast(c.O{ .NONBLOCK = true }))); + if (flags < 0 or c.fcntl(fd, c.F.SETFL, flags | nonblock) < 0) return fail(f, failed); + if (c.connect(fd, @ptrCast(&storage), len) != 0) { + if (c.errno(@as(c_int, -1)) != .INPROGRESS) return fail(f, failed); + var pfd = [_]c.pollfd{.{ .fd = fd, .events = c.POLL.OUT, .revents = 0 }}; + if (c.poll(&pfd, 1, @intCast(@min(ms, std.math.maxInt(c_int)))) != 1) return fail(f, failed); + var err: c_int = 0; + var err_len: c.socklen_t = @sizeOf(c_int); + if (c.getsockopt(fd, c.SOL.SOCKET, c.SO.ERROR, &err, &err_len) != 0 or err != 0) return fail(f, failed); + } + if (c.fcntl(fd, c.F.SETFL, flags) < 0) return fail(f, failed); + const tv: c.timeval = .{ .sec = @intCast(@divTrunc(ms, 1000)), .usec = @intCast(@mod(ms, 1000) * 1000) }; + _ = c.setsockopt(fd, c.SOL.SOCKET, c.SO.RCVTIMEO, &tv, @sizeOf(c.timeval)); + _ = c.setsockopt(fd, c.SOL.SOCKET, c.SO.SNDTIMEO, &tv, @sizeOf(c.timeval)); + return .{ .socket = .{ .handle = fd, .address = addr } }; +} + +var bundle_lock: Io.RwLock = .init; +var bundle: std.crypto.Certificate.Bundle = .empty; +var bundle_loaded = false; + +/// The network: every address the host resolves to checked public, then TLS verified for the host on the first. +const Network = struct { + fn request(_: Network, a: std.mem.Allocator, io: Io, u: Url, max_bytes: usize, deadline: Io.Timestamp, media_types: []const []const u8, f: *Failure) Error!Got { + const unresolved = "image host could not be resolved"; + var first: ?net.IpAddress = null; + if (net.IpAddress.parseIp4(u.host, 443)) |literal| { + if (!publicIp(literal)) return fail(f, "image URLs must resolve only to public internet addresses"); + first = literal; + } else |_| { + const name = net.HostName.init(std.mem.trimEnd(u8, u.host, ".")) catch return fail(f, unresolved); + var results: [32]net.HostName.LookupResult = undefined; + var q: Io.Queue(net.HostName.LookupResult) = .init(&results); + name.lookup(io, &q, .{ .port = 443 }) catch return fail(f, unresolved); + while (q.getOneUncancelable(io)) |r| switch (r) { + .address => |addr| { + if (!publicIp(addr)) return fail(f, "image URLs must resolve only to public internet addresses"); + if (first == null) first = addr; + }, + .canonical_name => {}, + } else |_| {} + } + const addr = first orelse return fail(f, unresolved); + { + bundle_lock.lockUncancelable(io); + defer bundle_lock.unlock(io); + if (!bundle_loaded) { + bundle.rescan(std.heap.page_allocator, io, Io.Clock.real.now(io)) catch return fail(f, "image download failed: no CA certificates on the server"); + bundle_loaded = true; + } + } + const stream = try connect(addr, try remaining(io, deadline, f), f); + defer stream.close(io); + const tls_len = std.crypto.tls.Client.min_buffer_len; + const bufs = try a.alloc(u8, 4 * tls_len); + var sr = stream.reader(io, bufs[0..tls_len]); + var sw = stream.writer(io, bufs[tls_len .. 2 * tls_len]); + var entropy: [std.crypto.tls.Client.Options.entropy_len]u8 = undefined; + io.random(&entropy); + var tls = std.crypto.tls.Client.init(&sr.interface, &sw.interface, .{ + .host = .{ .explicit = std.mem.trimEnd(u8, u.host, ".") }, + .ca = .{ .bundle = .{ .gpa = std.heap.page_allocator, .io = io, .lock = &bundle_lock, .bundle = &bundle } }, + .read_buffer = bufs[2 * tls_len .. 3 * tls_len], + .write_buffer = bufs[3 * tls_len ..], + .entropy = &entropy, + .realtime_now = Io.Clock.real.now(io), + .allow_truncation_attacks = true, // HTTP's own length and chunk framing end the body + }) catch return fail(f, "image download failed or timed out"); // images_http.py: an ssl.SSLError is an OSError + const accept = try std.mem.join(a, ", ", media_types); + ask(&tls.writer, u, accept) catch return fail(f, "image download failed or timed out"); + sw.interface.flush() catch return fail(f, "image download failed or timed out"); + return answer(a, io, &tls.reader, max_bytes, deadline, media_types, f); + } +}; + +test "public addresses as Python's ipaddress checks them" { + const ip4 = struct { + fn of(b: [4]u8) net.IpAddress { + return .{ .ip4 = .{ .bytes = b, .port = 443 } }; + } + }.of; + const ip6 = struct { + fn of(text: []const u8) net.IpAddress { + return net.IpAddress.parseIp6(text, 443) catch unreachable; + } + }.of; + for ([_][4]u8{ .{ 8, 8, 8, 8 }, .{ 151, 101, 1, 69 }, .{ 1, 1, 1, 1 } }) |b| try std.testing.expect(publicIp(ip4(b))); + for ([_][4]u8{ .{ 10, 1, 2, 3 }, .{ 127, 0, 0, 1 }, .{ 169, 254, 169, 254 }, .{ 172, 20, 0, 1 }, .{ 192, 168, 1, 1 }, .{ 100, 100, 0, 1 }, .{ 0, 0, 0, 0 }, .{ 224, 0, 0, 1 }, .{ 255, 255, 255, 255 }, .{ 168, 63, 129, 16 }, .{ 192, 0, 0, 9 }, .{ 198, 18, 0, 1 }, .{ 203, 0, 113, 5 } }) |b| + try std.testing.expect(!publicIp(ip4(b))); + try std.testing.expect(publicIp(ip6("2606:4700::1111"))); + for ([_][]const u8{ "::1", "::", "fe80::1", "fc00::1", "ff02::1", "::ffff:8.8.8.8", "2002:808:808::1", "2001::1", "2001:db8::1", "64:ff9b::808:808" }) |t| + try std.testing.expect(!publicIp(ip6(t))); +} + +test "URLs as images_http._url takes them" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f: Failure = .{}; + const ok = try parseUrl(a, "https://Example.COM:443/img/c.png?x=%20&y=\xc3\xa4?z", &f); + try std.testing.expectEqualStrings("example.com", ok.host); + try std.testing.expectEqualStrings("/img/c.png?x=%20&y=%C3%A4?z", ok.target); + try std.testing.expectEqualStrings("/", (try parseUrl(a, "https://example.com", &f)).target); + try std.testing.expectEqualStrings("/", (try parseUrl(a, "https://example.com?", &f)).target); + try std.testing.expectEqualStrings("/a??", (try parseUrl(a, "https://example.com/a??", &f)).target); + try std.testing.expectEqualStrings("/%5Ba%5D%22%3C", (try parseUrl(a, "https://example.com/[a]\"<", &f)).target); + const cases = [_]struct { []const u8, []const u8 }{ + .{ "https://example.com/a b.png", "image URL is too long or contains whitespace/control characters" }, + .{ "http://example.com/x.png", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://user:pw@example.com/x", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://example.com:8443/x", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://example.com/x#frag", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://example.com\\@evil/x", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https:///x", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://[::1]/x", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://localhost/x", "image URLs must use public internet hosts" }, + .{ "https://LOCALHOST./x", "image URLs must use public internet hosts" }, + .{ "https://metadata.google.internal/x", "image URLs must use public internet hosts" }, + }; + for (cases) |c| { + try std.testing.expectError(error.Media, parseUrl(a, c[0], &f)); + try std.testing.expectEqualStrings(c[1], f.text); + } + const long = try a.alloc(u8, max_url_chars + 1); + @memcpy(long[0.."https://e.com/".len], "https://e.com/"); + @memset(long["https://e.com/".len..], 'a'); + try std.testing.expectError(error.Media, parseUrl(a, long, &f)); + try std.testing.expectEqualStrings("https://e.com/b/c.png", try join(a, "https://e.com/b/a.png?q", "c.png")); + try std.testing.expectEqualStrings("https://e.com/z", try join(a, "https://e.com/b/a.png", "/z")); + try std.testing.expectEqualStrings("https://cdn.e.com/z", try join(a, "https://e.com/b/a.png", "//cdn.e.com/z")); + try std.testing.expectEqualStrings("http://e.com/z", try join(a, "https://e.com/b", "http://e.com/z")); +} + +/// Canned responses by host and path, for the HTTP rules without a network. +const Fixtures = struct { + pages: []const struct { []const u8, []const u8 }, + asked: *std.ArrayList(u8), + + fn request(self: Fixtures, a: std.mem.Allocator, io: Io, u: Url, max_bytes: usize, deadline: Io.Timestamp, media_types: []const []const u8, f: *Failure) Error!Got { + var w: Io.Writer.Allocating = .init(a); + ask(&w.writer, u, try std.mem.join(a, ", ", media_types)) catch return error.OutOfMemory; + try self.asked.appendSlice(a, w.written()); + const key = try std.fmt.allocPrint(a, "{s}{s}", .{ u.host, u.target }); + for (self.pages) |p| if (std.mem.eql(u8, p[0], key)) { + var r: Io.Reader = .fixed(p[1]); + return answer(a, io, &r, max_bytes, deadline, media_types, f); + }; + return fail(f, "image host could not be resolved"); + } +}; + +test "responses as images_http._request reads them: redirects, types, lengths, encodings" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const io = std.testing.io; + var asked: std.ArrayList(u8) = .empty; + const png = "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Length: 5\r\n\r\n\x89PNG!"; + const fx: Fixtures = .{ .asked = &asked, .pages = &.{ + .{ "e.com/a.png", png }, + .{ "e.com/chunked", "HTTP/1.1 200 OK\r\ncontent-type: Image/JPEG; q=1\r\nTransfer-Encoding: chunked\r\n\r\n3;x\r\n\xff\xd8\xff\r\n2\r\nab\r\n0\r\n\r\n" }, + .{ "e.com/eof", "HTTP/1.0 200 OK\r\nContent-Type: image/jpeg\r\n\r\n\xff\xd8\xffxyz" }, + .{ "e.com/r1", "HTTP/1.1 302 Found\r\nLocation: /r2\r\n\r\n" }, + .{ "e.com/r2", "HTTP/1.1 301 Moved\r\nLocation: https://cdn.e.com/b/x\r\n\r\n" }, + .{ "cdn.e.com/b/x", "HTTP/1.1 307 Temporary\r\nLocation: y.png\r\n\r\n" }, + .{ "cdn.e.com/b/y.png", png }, + .{ "e.com/loop", "HTTP/1.1 302 Found\r\nLocation: /loop\r\n\r\n" }, + .{ "e.com/plain", "HTTP/1.1 302 Found\r\nLocation: http://e.com/a.png\r\n\r\n" }, + .{ "e.com/inner", "HTTP/1.1 302 Found\r\nLocation: https://localhost/a.png\r\n\r\n" }, + .{ "e.com/nowhere", "HTTP/1.1 302 Found\r\n\r\n" }, + .{ "e.com/404", "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n" }, + .{ "e.com/gz", "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Encoding: gzip\r\nContent-Length: 1\r\n\r\nx" }, + .{ "e.com/html", "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 1\r\n\r\nx" }, + .{ "e.com/big", "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Length: 11\r\n\r\n01234567890" }, + .{ "e.com/bigchunk", "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nTransfer-Encoding: chunked\r\n\r\n6\r\n012345\r\n6\r\n678901\r\n0\r\n\r\n" }, + .{ "e.com/bigeof", "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\n\r\n01234567890" }, + .{ "e.com/badlen", "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Length: +5\r\n\r\n12345" }, + .{ "e.com/short", "HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Length: 9\r\n\r\n12345" }, + .{ "e.com/junk", "SSH-2.0-OpenSSH\r\n\r\n" }, + } }; + const far = Io.Clock.awake.now(io).addDuration(.fromSeconds(60)); + var f: Failure = .{}; + const one = try fetchVia(a, io, "https://e.com/a.png", 10, far, &image_media, &f, fx); + try std.testing.expectEqualStrings("\x89PNG!", one.data); + try std.testing.expectEqualStrings("image/png", one.media); + try std.testing.expectEqualStrings("GET /a.png HTTP/1.1\r\nHost: e.com\r\nAccept: image/jpeg, image/png, image/webp\r\nAccept-Encoding: identity\r\nUser-Agent: TensorFold-native\r\nConnection: close\r\n\r\n", asked.items); + const ch = try fetchVia(a, io, "https://e.com/chunked", 10, far, &image_media, &f, fx); + try std.testing.expectEqualStrings("\xff\xd8\xffab", ch.data); + try std.testing.expectEqualStrings("image/jpeg", ch.media); + try std.testing.expectEqualStrings("\xff\xd8\xffxyz", (try fetchVia(a, io, "https://e.com/eof", 10, far, &image_media, &f, fx)).data); + // three redirects, each joined and checked again, reach the image; a fourth is refused + asked.clearRetainingCapacity(); + try std.testing.expectEqualStrings("\x89PNG!", (try fetchVia(a, io, "https://e.com/r1", 10, far, &image_media, &f, fx)).data); + try std.testing.expectEqual(@as(usize, 4), std.mem.count(u8, asked.items, "GET ")); + try std.testing.expect(std.mem.indexOf(u8, asked.items, "GET /b/y.png HTTP/1.1\r\nHost: cdn.e.com\r\n") != null); + const refusals = [_]struct { []const u8, []const u8 }{ + .{ "https://e.com/loop", "image download has too many redirects" }, + .{ "https://e.com/plain", "image URL must be HTTPS on port 443, without credentials or a fragment" }, + .{ "https://e.com/inner", "image URLs must use public internet hosts" }, + .{ "https://e.com/nowhere", "image redirect has no destination" }, + .{ "https://e.com/404", "image download returned HTTP 404" }, + .{ "https://e.com/gz", "compressed HTTP image responses are unsupported" }, + .{ "https://e.com/html", "image URL content type must be JPEG, PNG or WebP" }, + .{ "https://e.com/big", "image response exceeds the encoded byte limit" }, + .{ "https://e.com/bigchunk", "image response exceeds the encoded byte limit" }, + .{ "https://e.com/bigeof", "image response exceeds the encoded byte limit" }, + .{ "https://e.com/badlen", "image response exceeds the encoded byte limit" }, + .{ "https://e.com/short", "image download failed or timed out" }, + .{ "https://e.com/junk", "image download failed or timed out" }, + }; + for (refusals) |c| { + try std.testing.expectError(error.Media, fetchVia(a, io, c[0], 10, far, &image_media, &f, fx)); + try std.testing.expectEqualStrings(c[1], f.text); + } + // a deadline already passed refuses before the body + try std.testing.expectError(error.Media, fetchVia(a, io, "https://e.com/a.png", 10, Io.Clock.awake.now(io), &image_media, &f, fx)); + try std.testing.expectEqualStrings("image download timed out", f.text); +} diff --git a/zig/src/server/prompt.zig b/zig/src/server/prompt.zig index 5500803b68..df2a7024c6 100644 --- a/zig/src/server/prompt.zig +++ b/zig/src/server/prompt.zig @@ -115,7 +115,7 @@ pub fn prepare(srv: *Server, cx: *Cx, input: chat.Input, thinking: bool, effort: if (history_len == 0 and prompt.len > 1 and std.mem.eql(u32, history, prompt)) history_len = prompt.len - 1; // a template with no generation suffix // --vision: each image's placeholder expanded to its tokens before the window, chunks and cache see the prompt; // such a prompt keeps no rewind, which the expansion does not translate - if (try images.expand(srv.info.vision, cx, input.messages, prompt, history_len)) |x| return .{ .ids = x.ids, .history_len = x.history_len, .images = x.images, .cache_key = x.cache_key }; + if (try images.expand(srv.info.vision, if (srv.config.vision_urls) images.Fetch.network(srv.io) else null, cx, input.messages, prompt, history_len)) |x| return .{ .ids = x.ids, .history_len = x.history_len, .images = x.images, .cache_key = x.cache_key }; const count = if (input.messages == .array) input.messages.array.len else 0; const rewind_len = if (srv.info.prompt_cache) rewindLen(srv, cx, input.messages, count, input.tools, prompt, thinking, effort) else 0; // one more render return .{ .ids = prompt, .history_len = history_len, .rewind_len = rewind_len }; diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index b669d55c3a..36186aea81 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -39,6 +39,7 @@ test { _ = @import("log.zig"); _ = @import("messages.zig"); _ = @import("images.zig"); + _ = @import("media_fetch.zig"); _ = @import("stream_preflight_test.zig"); _ = @import("logprobs_test.zig"); _ = @import("late_system_test.zig"); diff --git a/zig/src/server/serve.zig b/zig/src/server/serve.zig index 967c0979b1..31aa5bed83 100644 --- a/zig/src/server/serve.zig +++ b/zig/src/server/serve.zig @@ -116,6 +116,7 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { .keep_warm_s = args.keep_warm, .default_sampling = s.sampling, .use_drafts = !args.no_drafts, + .vision_urls = args.vision_urls, .seed_salt = salt, .request_log = env(s, "TENSORFOLD_REQUEST_LOG"), .dashboard = args.dashboard, diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index 255b02a2b6..a8dd67e581 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -45,6 +45,8 @@ pub const Config = struct { /// Sampling when a request names none (generation_config.json and the serve flags), or null for greedy. default_sampling: ?Value = null, use_drafts: bool = true, + /// --vision-urls: image parts may name public HTTPS URLs, fetched before admission (media_fetch.zig). + vision_urls: bool = false, seed_salt: i64 = 0, /// TENSORFOLD_REQUEST_LOG: where chat and completion bodies are appended; null: nowhere. request_log: ?[]const u8 = null, From fa22819fb1557ddd8adf73543dc4efe1a6475a90 Mon Sep 17 00:00:00 2001 From: BobClawblaw Date: Mon, 12 Oct 2026 02:33:44 +0000 Subject: [PATCH 06/17] Qwen3.5 vision tower on CUDA: qwen_vision.cu kernels, the Tower, and its check against 0.6.6 Row cosine against 0.6.6's flash-attention tower on nine fixture images: mean 0.9997-0.99998, min 0.981-0.99998; 0.6.6's own math-vs-flash attention gives min 0.9895 on the same shapes image. --- tools/zig/qwen_vision_fixtures.py | 103 ++++++ zig/build/cuda.zig | 1 + zig/kernels/cuda/qwen_vision.cu | 208 +++++++++++++ zig/src/cli/qwen27_cuda.zig | 73 +++++ zig/src/cuda/kernels.zig | 1 + zig/src/families/qwen27/cuda.zig | 2 + zig/src/families/qwen27/cuda/vision.zig | 397 ++++++++++++++++++++++++ 7 files changed, 785 insertions(+) create mode 100644 tools/zig/qwen_vision_fixtures.py create mode 100644 zig/kernels/cuda/qwen_vision.cu create mode 100644 zig/src/families/qwen27/cuda/vision.zig diff --git a/tools/zig/qwen_vision_fixtures.py b/tools/zig/qwen_vision_fixtures.py new file mode 100644 index 0000000000..5f989a42ef --- /dev/null +++ b/tools/zig/qwen_vision_fixtures.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Fixtures for the native Qwen vision path, from TensorFold 0.6.6's --vision frontend and tower on CUDA. + +For a fixed image set: each image's file, its decoded RGB (images.py), its patches and grid (QwenImageProcessor's +processor at 0.6.6's per-image cap), and the tower's merged rows (QwenCudaVision, bf16, flash attention). The Zig +checks compare their own decode, patches and rows against these: ``tf-qwen27-cuda vision MODEL --fixtures DIR``. +""" + +from __future__ import annotations + +import argparse +import io +import json +from pathlib import Path + +import numpy as np + + +def images(): + """(name, encoded bytes) for the set: PNG layouts, sizes from tiny to large, an EXIF-rotated JPEG.""" + from PIL import Image, ImageDraw + + out = [] + shapes = Image.new("RGB", (517, 389), "white") + d = ImageDraw.Draw(shapes) + d.ellipse((30, 40, 230, 240), fill=(220, 20, 20)) + d.rectangle((280, 60, 490, 260), fill=(20, 60, 220)) + d.text((60, 300), "ORANGE 7351", fill="black") + rng = np.random.default_rng(7) + y, x = np.mgrid[0:768, 0:1024] + photo = np.stack([(x / 4) % 256, (y / 3) % 256, ((x + y) / 7) % 256], -1) + rng.normal(0, 12, (768, 1024, 3)) + photo = Image.fromarray(np.clip(photo, 0, 255).astype(np.uint8)) + large = photo.resize((2000, 1500)) + tiny = shapes.resize((20, 15)) + logo = Image.new("RGBA", (96, 96), (0, 0, 0, 0)) + ImageDraw.Draw(logo).ellipse((8, 8, 88, 88), fill=(30, 160, 90, 200)) + palette = shapes.convert("P", palette=Image.Palette.ADAPTIVE, colors=16) + palette.info["transparency"] = 0 + gray = photo.convert("L") + + def png(img, **kw): + b = io.BytesIO() + img.save(b, "PNG", **kw) + return b.getvalue() + + def jpeg(img, exif=None): + b = io.BytesIO() + img.save(b, "JPEG", quality=90, **({"exif": exif} if exif else {})) + return b.getvalue() + + exif = Image.Exif() + exif[0x0112] = 6 # rotate 90 on display + out += [("shapes.png", png(shapes)), ("photo.png", png(photo)), ("large.png", png(large)), + ("tiny.png", png(tiny)), ("logo.png", png(logo)), ("palette.png", png(palette)), ("gray.png", png(gray)), + ("photo.jpg", jpeg(photo)), ("rotated.jpg", jpeg(shapes, exif.tobytes()))] + return out + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--model", required=True) + ap.add_argument("--out", required=True) + a = ap.parse_args() + import torch + from torch.nn.attention import SDPBackend, sdpa_kernel + from tensorfold.vision.images import _decode, DEFAULT_LIMITS + from tensorfold.vision.qwen_cuda import QwenCudaVision, TOKENS_PER_IMAGE + + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + vision = QwenCudaVision(a.model, torch.device("cuda:0")) + proc = vision.frontend.processor + factor = vision.config["patch_size"] * vision.config["spatial_merge_size"] + cap = min(int(getattr(proc, "max_pixels", TOKENS_PER_IMAGE * factor**2)), TOKENS_PER_IMAGE * factor**2) + floor = min(int(getattr(proc, "min_pixels", factor**2)), cap) + entries = [] + for name, data in images(): + stem = name.replace(".", "_") + (out / name).write_bytes(data) + decoded = _decode(data, "auto", DEFAULT_LIMITS, DEFAULT_LIMITS.max_pixels) + pil = decoded.to_pil() + rgb = np.asarray(pil, dtype=np.uint8) + (out / f"{stem}.rgb").write_bytes(rgb.tobytes()) + result = proc(images=[pil], max_pixels=cap, min_pixels=floor) + pixels = np.asarray(result["pixel_values"], dtype=np.float32) + t, h, w = (int(v) for v in np.asarray(result["image_grid_thw"])[0]) + (out / f"{stem}.f32").write_bytes(pixels.tobytes()) + with torch.inference_mode(), sdpa_kernel([SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION]): + feats = vision.tower(torch.tensor(pixels, dtype=torch.bfloat16, device="cuda:0"), + grid_thw=torch.tensor([[t, h, w]], device="cuda:0"), return_dict=True).pooler_output + feats = feats.to(torch.bfloat16).contiguous().cpu() + (out / f"{stem}.bf16").write_bytes(feats.view(torch.int16).numpy().tobytes()) + entries.append({"name": name, "file": name, "rgb": f"{stem}.rgb", "size": [rgb.shape[1], rgb.shape[0]], + "grid": [h, w], "pixels": f"{stem}.f32", "features": f"{stem}.bf16", + "tokens": h * w // 4}) + print(f"{name}: {rgb.shape[1]}x{rgb.shape[0]} -> grid {h}x{w}, {h * w // 4} tokens", flush=True) + (out / "manifest.json").write_text(json.dumps({"images": entries, "cap_pixels": cap, "min_pixels": floor}, + indent=1) + "\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index bac51ae59f..188de6ea75 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -30,6 +30,7 @@ const kernels = [_]Kernel{ .{ .name = "sample", .flags = &.{ "-O3", "--fmad=false", "--ftz=false" } }, // ours: the Metal engine's keyed draws .{ .name = "train", .flags = &.{"-O3"} }, // ours: Sliding Weights' learning step (train.metal's kernels) .{ .name = "qwen_ops", .flags = &.{"-O3"} }, // ours: the 27B's batched state copies, taps, drafter norms and rotary + .{ .name = "qwen_vision", .flags = &.{ "-O3", "--fmad=false" } }, // ours: the Qwen3.5 vision tower's glue and attention .{ .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 }, diff --git a/zig/kernels/cuda/qwen_vision.cu b/zig/kernels/cuda/qwen_vision.cu new file mode 100644 index 0000000000..9b1a73db9d --- /dev/null +++ b/zig/kernels/cuda/qwen_vision.cu @@ -0,0 +1,208 @@ +// The Qwen3.5 vision tower's kernels (transformers' Qwen3_5VisionModel, as 0.6.6's --vision runs it in bf16). +// The tower's Linears run on cuBLASLt with fp32 output; each epilogue here adds the bias and rounds to bf16 once, +// where torch's bf16 Linear rounds, before the op that follows. +#include +#include + +__device__ __forceinline__ float bf(__nv_bfloat16 v) { return __bfloat162float(v); } +__device__ __forceinline__ float rnd(float v) { return __bfloat162float(__float2bfloat16_rn(v)); } + +// Patch embedding plus the resampled position grid: x = bf16(acc + b) + bf16(sum_t pos[idx_t] * w_t). +extern "C" __global__ void __launch_bounds__(256) tf_qv_embed(const float* __restrict__ acc, + const __nv_bfloat16* __restrict__ bias, + const __nv_bfloat16* __restrict__ pos, + const int* __restrict__ idx, + const float* __restrict__ wts, + __nv_bfloat16* __restrict__ out, int D) { + const long long row = blockIdx.x; + const int* ri = idx + row * 4; + const float* rw = wts + row * 4; + for (int i = threadIdx.x; i < D; i += blockDim.x) { + const float h = rnd(acc[row * D + i] + bf(bias[i])); + float p = 0.0f; + for (int t = 0; t < 4; ++t) p += bf(pos[(long long)ri[t] * D + i]) * rw[t]; + out[row * D + i] = __float2bfloat16_rn(h + rnd(p)); + } +} + +// LayerNorm of bf16 rows in fp32 (mean, then the biased variance about it), bf16 out; a block a row. +extern "C" __global__ void __launch_bounds__(256) tf_qv_layernorm(const __nv_bfloat16* __restrict__ x, + const __nv_bfloat16* __restrict__ w, + const __nv_bfloat16* __restrict__ b, + __nv_bfloat16* __restrict__ y, int D, float eps) { + __shared__ float part[32]; + __shared__ float stat; + const long long row = blockIdx.x; + const __nv_bfloat16* xr = x + row * D; + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5, warps = blockDim.x >> 5; + float s = 0.0f; + for (int i = threadIdx.x; i < D; i += blockDim.x) s += bf(xr[i]); + for (int o = 16; o; o >>= 1) s += __shfl_xor_sync(0xffffffffu, s, o); + if (lane == 0) part[warp] = s; + __syncthreads(); + if (threadIdx.x == 0) { + float t = 0.0f; + for (int i = 0; i < warps; ++i) t += part[i]; + stat = t / D; + } + __syncthreads(); + const float mean = stat; + float v = 0.0f; + for (int i = threadIdx.x; i < D; i += blockDim.x) { + const float d = bf(xr[i]) - mean; + v += d * d; + } + for (int o = 16; o; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + __syncthreads(); + if (lane == 0) part[warp] = v; + __syncthreads(); + if (threadIdx.x == 0) { + float t = 0.0f; + for (int i = 0; i < warps; ++i) t += part[i]; + stat = rsqrtf(t / D + eps); + } + __syncthreads(); + const float r = stat; + for (int i = threadIdx.x; i < D; i += blockDim.x) + y[row * D + i] = __float2bfloat16_rn((bf(xr[i]) - mean) * r * bf(w[i]) + bf(b[i])); +} + +// qkv = bf16(acc + b) split into q, k, v [heads][rows][hd]; q and k rotated by the axial 2-D rotary in fp32 +// (apply_rotary_pos_emb_vision): angle j of a head is h * inv[j % half'] for the first quarter's frequencies and +// w * inv[...] for the second, repeated over both halves; rotate_half pairs j with j +- hd/2. +extern "C" __global__ void __launch_bounds__(128) tf_qv_qkv_rope(const float* __restrict__ acc, + const __nv_bfloat16* __restrict__ bias, + const int* __restrict__ hw, + const float* __restrict__ inv, + __nv_bfloat16* __restrict__ q, + __nv_bfloat16* __restrict__ k, + __nv_bfloat16* __restrict__ v, int rows, int heads, + int hd) { + const long long row = blockIdx.x; + const int head = blockIdx.y; + const int D = heads * hd; + const int half = hd / 2, quarter = hd / 4; + const float ph = static_cast(hw[row * 2]), pw = static_cast(hw[row * 2 + 1]); + const float* a = acc + row * 3 * D; + const long long o = (static_cast(head) * rows + row) * hd; + for (int j = threadIdx.x; j < hd; j += blockDim.x) { + const int c = head * hd + j; + const int pj = j < half ? j + half : j - half; + const int pc = head * hd + pj; + const int jj = j % half; + const float ang = jj < quarter ? ph * inv[jj] : pw * inv[jj - quarter]; + const float cs = cosf(ang), sn = sinf(ang); + const float sign = j < half ? -1.0f : 1.0f; + const float qx = rnd(a[c] + bf(bias[c])), qp = rnd(a[pc] + bf(bias[pc])); + const float kx = rnd(a[D + c] + bf(bias[D + c])), kp = rnd(a[D + pc] + bf(bias[D + pc])); + q[o + j] = __float2bfloat16_rn(qx * cs + sign * qp * sn); + k[o + j] = __float2bfloat16_rn(kx * cs + sign * kp * sn); + v[o + j] = __float2bfloat16_rn(a[2 * D + c] + bf(bias[2 * D + c])); + } +} + +// Bidirectional attention within one image: rows [s0, s0 + n) of q, k, v [heads][rows][HD] attend to each other; +// out [rows][heads * HD]. A thread a query row with an online softmax in fp32; keys and values in 64-row tiles. +template +__device__ void qv_attention(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ k, + const __nv_bfloat16* __restrict__ v, __nv_bfloat16* __restrict__ out, int rows, + int heads, int s0, int n, float scale) { + constexpr int T = 64; + __shared__ float ks[T][HD]; + __shared__ float vs[T][HD]; + const int head = blockIdx.y; + const int qi = blockIdx.x * T + threadIdx.x; + const bool live = qi < n; + const long long base = static_cast(head) * rows + s0; + float qr[HD], acc[HD]; + float m = -INFINITY, l = 0.0f; + if (live) { + const __nv_bfloat16* qp = q + (base + qi) * HD; + for (int d = 0; d < HD; ++d) { + qr[d] = bf(qp[d]) * scale; + acc[d] = 0.0f; + } + } + for (int t0 = 0; t0 < n; t0 += T) { + const int count = min(T, n - t0); + __syncthreads(); + for (int i = threadIdx.x; i < count * HD; i += blockDim.x) { + const int r = i / HD, d = i % HD; + ks[r][d] = bf(k[(base + t0 + r) * HD + d]); + vs[r][d] = bf(v[(base + t0 + r) * HD + d]); + } + __syncthreads(); + if (!live) continue; + for (int r = 0; r < count; ++r) { + float s = 0.0f; +#pragma unroll + for (int d = 0; d < HD; ++d) s += qr[d] * ks[r][d]; + const float mn = fmaxf(m, s); + const float corr = __expf(m - mn); + const float p = __expf(s - mn); + l = l * corr + p; +#pragma unroll + for (int d = 0; d < HD; ++d) acc[d] = acc[d] * corr + p * vs[r][d]; + m = mn; + } + } + if (!live) return; + const float il = 1.0f / l; + __nv_bfloat16* op = out + static_cast(s0 + qi) * heads * HD + head * HD; + for (int d = 0; d < HD; ++d) op[d] = __float2bfloat16_rn(acc[d] * il); +} + +extern "C" __global__ void __launch_bounds__(64) tf_qv_attention72(const __nv_bfloat16* __restrict__ q, + const __nv_bfloat16* __restrict__ k, + const __nv_bfloat16* __restrict__ v, + __nv_bfloat16* __restrict__ out, int rows, + int heads, int s0, int n, float scale) { + qv_attention<72>(q, k, v, out, rows, heads, s0, n, scale); +} + +// y = gelu(bf16(acc + b)), the tanh form (gelu_pytorch_tanh) or the erf form (nn.GELU), computed in fp32, bf16 out. +extern "C" __global__ void __launch_bounds__(256) tf_qv_bias_gelu(const float* __restrict__ acc, + const __nv_bfloat16* __restrict__ bias, + __nv_bfloat16* __restrict__ y, int D, int tanh_form) { + const long long row = blockIdx.x; + for (int i = threadIdx.x; i < D; i += blockDim.x) { + const float x = rnd(acc[row * D + i] + bf(bias[i])); + float g; + if (tanh_form) { + const float kBeta = 0.7978845608028654f; // sqrt(2 / pi) + g = 0.5f * x * (1.0f + tanhf(kBeta * (x + 0.044715f * x * x * x))); + } else { + g = 0.5f * x * (1.0f + erff(x * 0.7071067811865476f)); + } + y[row * D + i] = __float2bfloat16_rn(g); + } +} + +// x += bf16(acc + b), the residual add in bf16 (both operands bf16, the sum rounded). +extern "C" __global__ void __launch_bounds__(256) tf_qv_bias_residual(const float* __restrict__ acc, + const __nv_bfloat16* __restrict__ bias, + __nv_bfloat16* __restrict__ x, int D) { + const long long row = blockIdx.x; + for (int i = threadIdx.x; i < D; i += blockDim.x) { + const float y = rnd(acc[row * D + i] + bf(bias[i])); + x[row * D + i] = __float2bfloat16_rn(bf(x[row * D + i]) + y); + } +} + +// y = bf16(acc + b): the merger's last Linear. +extern "C" __global__ void __launch_bounds__(256) tf_qv_bias_cast(const float* __restrict__ acc, + const __nv_bfloat16* __restrict__ bias, + __nv_bfloat16* __restrict__ y, int D) { + const long long row = blockIdx.x; + for (int i = threadIdx.x; i < D; i += blockDim.x) y[row * D + i] = __float2bfloat16_rn(acc[row * D + i] + bf(bias[i])); +} + +// Image rows into a prompt chunk's embeddings: row r of `x` (stride D) takes feature row src[r] where src[r] >= 0. +extern "C" __global__ void __launch_bounds__(256) tf_qv_splice(__nv_bfloat16* __restrict__ x, + const __nv_bfloat16* __restrict__ features, + const int* __restrict__ src, int D) { + const long long row = blockIdx.x; + const int s = src[row]; + if (s < 0) return; + for (int i = threadIdx.x; i < D; i += blockDim.x) x[row * D + i] = features[static_cast(s) * D + i]; +} diff --git a/zig/src/cli/qwen27_cuda.zig b/zig/src/cli/qwen27_cuda.zig index a92416ce7b..dfdfe785f9 100644 --- a/zig/src/cli/qwen27_cuda.zig +++ b/zig/src/cli/qwen27_cuda.zig @@ -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 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). \\ ; @@ -40,6 +42,8 @@ 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"); + 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)) { std.debug.print("{s}", .{usage}); return 2; @@ -457,3 +461,72 @@ fn runMulti(gpa: std.mem.Allocator, a: std.mem.Allocator, io: std.Io, e: *qwen.E std.debug.print("{d} rounds (python {d}), {d} windows differ from Python's, {d} replies differ; {d:.1} tok/s\n", .{ round, want_rounds.len, differ, bad, @as(f64, @floatFromInt(produced)) / secs }); return if (bad == 0 and round == want_rounds.len) 0 else 1; } + +/// The tower against qwen_vision_fixtures.py's manifest: per image, the features' row cosines and largest error. +fn checkVision(gpa: std.mem.Allocator, arena: std.mem.Allocator, io: std.Io, model: []const u8, dir: []const u8) !u8 { + const V = qwen.vision; + const manifest = try readJson(arena, io, try std.fs.path.join(arena, &.{ dir, "manifest.json" })); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + const gpu: V.Gpu = .{ .d = &driver, .s = stream, .discrete = try ctx.attribute(.integrated) == 0 }; + const clock = std.Io.Clock.awake; + var t0 = clock.now(io).toNanoseconds(); + const tower = try V.Tower.load(gpa, io, gpu, model); + defer tower.deinit(); + std.debug.print("tower loaded in {d:.1}s, {d:.2} GiB\n", .{ @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e9, @as(f64, @floatFromInt(tower.weight_bytes)) / (1 << 30) }); + var worst: f64 = 1; + for (manifest.object.get("images").?.array.items) |img| { + const name = img.object.get("name").?.string; + const grid = img.object.get("grid").?.array.items; + const g: V.Grid = .{ .h = @intCast(grid[0].integer), .w = @intCast(grid[1].integer) }; + const px_bytes = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("pixels").?.string }), arena, .limited(1 << 30)); + const want_bytes = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("features").?.string }), arena, .limited(1 << 30)); + const px = try arena.alloc(f32, px_bytes.len / 4); + @memcpy(std.mem.sliceAsBytes(px), px_bytes[0 .. px.len * 4]); + const rows = @as(usize, g.h) * g.w / 4; + var out = try cuda.DeviceBuffer.alloc(&driver, rows * V.out_hidden * 2); + defer out.free(); + t0 = clock.now(io).toNanoseconds(); + try tower.encode(gpu, px, &.{g}, out.ptr); + const ms = @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e6; + const got = try arena.alloc(u16, rows * V.out_hidden); + try driver.check(driver.api.cuMemcpyDtoH_v2(@ptrCast(got.ptr), out.ptr, got.len * 2), "cuMemcpyDtoH"); + const want: []align(1) const u16 = std.mem.bytesAsSlice(u16, want_bytes); + if (want.len != got.len) { + std.debug.print("{s}: {d} features, 0.6.6 has {d}\n", .{ name, got.len, want.len }); + return 1; + } + var min_cos: f64 = 1; + var sum_cos: f64 = 0; + var max_err: f64 = 0; + var equal: usize = 0; + for (0..rows) |r| { + var dot: f64 = 0; + var na: f64 = 0; + var nb: f64 = 0; + for (0..V.out_hidden) |c| { + const a = bf(got[r * V.out_hidden + c]); + const b = bf(want[r * V.out_hidden + c]); + if (got[r * V.out_hidden + c] == want[r * V.out_hidden + c]) equal += 1; + dot += a * b; + na += a * a; + nb += b * b; + max_err = @max(max_err, @abs(a - b)); + } + const cs = dot / @sqrt(na * nb); + min_cos = @min(min_cos, cs); + sum_cos += cs; + } + worst = @min(worst, min_cos); + std.debug.print("{s}: grid {d}x{d}, {d} rows in {d:.1} ms; row cosine min {d:.5} mean {d:.5}; max error {d:.4}; {d:.1}% values equal\n", .{ name, g.h, g.w, rows, ms, min_cos, sum_cos / @as(f64, @floatFromInt(rows)), max_err, 100 * @as(f64, @floatFromInt(equal)) / @as(f64, @floatFromInt(got.len)) }); + } + return if (worst > 0.98) 0 else 1; +} + +fn bf(v: u16) f64 { + return @as(f32, @bitCast(@as(u32, v) << 16)); +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 2e93589095..56dc43cf2e 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -28,6 +28,7 @@ pub const affine4_pack: []const u8 = if (available) &Blob("fatbin_affine4_pack") pub const fp8_experts: []const u8 = if (available) &Blob("fatbin_fp8_experts").bytes else &.{}; pub const nvfp4_experts: []const u8 = if (available) &Blob("fatbin_nvfp4_experts").bytes else &.{}; pub const qwen_ops: []const u8 = if (available) &Blob("fatbin_qwen_ops").bytes else &.{}; +pub const qwen_vision: []const u8 = if (available) &Blob("fatbin_qwen_vision").bytes else &.{}; 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 qmmf: []const u8 = if (available) &Blob("fatbin_qmmf").bytes else &.{}; diff --git a/zig/src/families/qwen27/cuda.zig b/zig/src/families/qwen27/cuda.zig index 3532c69cde..746c12d658 100644 --- a/zig/src/families/qwen27/cuda.zig +++ b/zig/src/families/qwen27/cuda.zig @@ -14,6 +14,7 @@ pub const native = @import("cuda/native.zig"); pub const draft = @import("cuda/draft.zig"); pub const lone = @import("cuda/lone.zig"); pub const drafts = @import("cuda/drafts.zig"); +pub const vision = @import("cuda/vision.zig"); test { _ = config; @@ -30,4 +31,5 @@ test { _ = draft; _ = lone; _ = native; + _ = vision; } diff --git a/zig/src/families/qwen27/cuda/vision.zig b/zig/src/families/qwen27/cuda/vision.zig new file mode 100644 index 0000000000..1305d9b3d6 --- /dev/null +++ b/zig/src/families/qwen27/cuda/vision.zig @@ -0,0 +1,397 @@ +//! The Qwen3.5 vision tower on CUDA (transformers' Qwen3_5VisionModel, as 0.6.6's --vision runs it in bf16): patch +//! embedding, the learned position grid resampled bilinearly to each image, 27 pre-norm blocks of axial 2-D rotary +//! attention within each image, and the 2x2 merger to the language model's width. Linears on cuBLASLt (fp32 out), +//! the rest in qwen_vision.cu. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const nemotron = @import("nemotron"); +const source = nemotron.source; + +const lt = cuda.cublaslt; +const prefix = "vision_tower."; + +/// vision_config as the 27B's checkpoint gives it; another tower is refused. +pub const hidden = 1152; +pub const heads = 16; +pub const head_dim = hidden / heads; // 72 +pub const depth = 27; +pub const intermediate = 4304; +pub const out_hidden = 5120; +pub const patch = 16; +pub const temporal = 2; +pub const merge = 2; +pub const channels = 3; +pub const patch_width = channels * temporal * patch * patch; // 1536 +pub const grid_side = 48; // sqrt(num_position_embeddings 2304) +pub const merged = hidden * merge * merge; // 4608 +pub const eps: f32 = 1e-6; +/// One tower call's patches: a 4,096-token image's (0.6.6's MAX_PATCHES). +pub const max_patches = 16384; +const workspace_bytes = 32 << 20; + +/// The device, stream and memory kind the tower runs on (the engine's, or a checker's own). +pub const Gpu = struct { + d: *const cuda.Driver, + s: cuda.Stream, + discrete: bool, + + fn upload(g: Gpu, dst: u64, bytes: []const u8) !void { + if (bytes.len == 0) return; + try g.d.check(g.d.api.cuMemcpyHtoDAsync_v2(dst, bytes.ptr, bytes.len, g.s.handle), "cuMemcpyHtoDAsync"); + } +}; + +/// One image's patch grid (rows and columns of 16x16 patches, both even). +pub const Grid = struct { h: u32, w: u32 }; + +const Block = struct { norm1_w: u64, norm1_b: u64, qkv_w: u64, qkv_b: u64, proj_w: u64, proj_b: u64, norm2_w: u64, norm2_b: u64, fc1_w: u64, fc1_b: u64, fc2_w: u64, fc2_b: u64 }; + +const Fns = struct { + embed: cuda.Function, + layernorm: cuda.Function, + qkv_rope: cuda.Function, + attention: cuda.Function, + bias_gelu: cuda.Function, + bias_residual: cuda.Function, + bias_cast: cuda.Function, + splice: cuda.Function, +}; + +/// The image tower's weights on the GPU and its kernels; `encode` turns patches into language-width rows. +pub const Tower = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + mod: cuda.Module, + f: Fns, + lib: lt.Library, + buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + patch_w: u64 = 0, + patch_b: u64 = 0, + pos: u64 = 0, + blocks: [depth]Block = undefined, + merger_norm_w: u64 = 0, + merger_norm_b: u64 = 0, + fc1_w: u64 = 0, + fc1_b: u64 = 0, + fc2_w: u64 = 0, + fc2_b: u64 = 0, + inv: u64 = 0, + weight_bytes: usize = 0, + + /// The checkpoint's vision_tower tensors (bf16), every one used; the patch convolution's weight as rows of + /// [channel, frame, y, x], the order the patches come in. + pub fn load(gpa: std.mem.Allocator, io: std.Io, ops: Gpu, dir: []const u8) !*Tower { + const t = try gpa.create(Tower); + errdefer gpa.destroy(t); + t.* = .{ .gpa = gpa, .d = ops.d, .mod = undefined, .f = undefined, .lib = undefined }; + t.lib = try lt.Library.open(); + errdefer t.lib.close(); + t.mod = try cuda.Module.load(ops.d, cuda.kernels.qwen_vision); + errdefer t.mod.unload(); + t.f = .{ + .embed = try t.mod.function("tf_qv_embed"), + .layernorm = try t.mod.function("tf_qv_layernorm"), + .qkv_rope = try t.mod.function("tf_qv_qkv_rope"), + .attention = try t.mod.function("tf_qv_attention72"), + .bias_gelu = try t.mod.function("tf_qv_bias_gelu"), + .bias_residual = try t.mod.function("tf_qv_bias_residual"), + .bias_cast = try t.mod.function("tf_qv_bias_cast"), + .splice = try t.mod.function("tf_qv_splice"), + }; + errdefer t.freeBuffers(); + var src = try source.Source.init(gpa, .{ .d = ops.d, .s = ops.s, .discrete = ops.discrete }); + defer src.deinit(); + var ck = try core.Checkpoint.openModelPrefix(gpa, io, dir, prefix); + defer ck.close(); + try src.add(&ck); + const L = struct { + t: *Tower, + ck: *core.Checkpoint, + src: *source.Source, + fn get(l: @This(), name: []const u8, shape: []const usize) !u64 { + var buf: [96]u8 = undefined; + const tn = try l.ck.expect(try std.fmt.bufPrint(&buf, prefix ++ "{s}", .{name}), .bf16, shape); + const ptr = try l.t.alloc(tn.bytes.len); + try l.src.upload(ptr, tn.bytes); + return ptr; + } + }; + const l: L = .{ .t = t, .ck = &ck, .src = &src }; + { // [hidden, T, P, P, C] as stored (MLX) to [hidden, C, T, P, P] + const tn = try ck.expect(prefix ++ "patch_embed.proj.weight", .bf16, &.{ hidden, temporal, patch, patch, channels }); + const host = try gpa.alloc(u16, hidden * patch_width); + defer gpa.free(host); + const raw = try gpa.alloc(u8, tn.bytes.len); + defer gpa.free(raw); + try src.read(raw, tn.bytes); + const stored: []align(1) const u16 = std.mem.bytesAsSlice(u16, raw); + for (0..hidden) |o| for (0..channels) |ch| for (0..temporal) |tt| for (0..patch) |y| for (0..patch) |x| { + host[o * patch_width + ((ch * temporal + tt) * patch + y) * patch + x] = stored[(((o * temporal + tt) * patch + y) * patch + x) * channels + ch]; + }; + t.patch_w = try t.alloc(host.len * 2); + try src.upload(t.patch_w, std.mem.sliceAsBytes(host)); + try ops.s.synchronize(); + } + t.patch_b = try l.get("patch_embed.proj.bias", &.{hidden}); + t.pos = try l.get("pos_embed.weight", &.{ grid_side * grid_side, hidden }); + for (&t.blocks, 0..) |*b, i| { + var pb: [32]u8 = undefined; + const p = try std.fmt.bufPrint(&pb, "blocks.{d}.", .{i}); + var nb: [96]u8 = undefined; + const n = struct { + fn f(buf: []u8, a: []const u8, s: []const u8) ![]const u8 { + return std.fmt.bufPrint(buf, "{s}{s}", .{ a, s }); + } + }.f; + b.norm1_w = try l.get(try n(&nb, p, "norm1.weight"), &.{hidden}); + b.norm1_b = try l.get(try n(&nb, p, "norm1.bias"), &.{hidden}); + b.qkv_w = try l.get(try n(&nb, p, "attn.qkv.weight"), &.{ 3 * hidden, hidden }); + b.qkv_b = try l.get(try n(&nb, p, "attn.qkv.bias"), &.{3 * hidden}); + b.proj_w = try l.get(try n(&nb, p, "attn.proj.weight"), &.{ hidden, hidden }); + b.proj_b = try l.get(try n(&nb, p, "attn.proj.bias"), &.{hidden}); + b.norm2_w = try l.get(try n(&nb, p, "norm2.weight"), &.{hidden}); + b.norm2_b = try l.get(try n(&nb, p, "norm2.bias"), &.{hidden}); + b.fc1_w = try l.get(try n(&nb, p, "mlp.linear_fc1.weight"), &.{ intermediate, hidden }); + b.fc1_b = try l.get(try n(&nb, p, "mlp.linear_fc1.bias"), &.{intermediate}); + b.fc2_w = try l.get(try n(&nb, p, "mlp.linear_fc2.weight"), &.{ hidden, intermediate }); + b.fc2_b = try l.get(try n(&nb, p, "mlp.linear_fc2.bias"), &.{hidden}); + } + t.merger_norm_w = try l.get("merger.norm.weight", &.{hidden}); + t.merger_norm_b = try l.get("merger.norm.bias", &.{hidden}); + t.fc1_w = try l.get("merger.linear_fc1.weight", &.{ merged, merged }); + t.fc1_b = try l.get("merger.linear_fc1.bias", &.{merged}); + t.fc2_w = try l.get("merger.linear_fc2.weight", &.{ out_hidden, merged }); + t.fc2_b = try l.get("merger.linear_fc2.bias", &.{out_hidden}); + if (ck.unused() != 0) return error.UnusedVisionTensors; + var inv: [head_dim / 4]f32 = undefined; + invFreq(&inv); + t.inv = try t.alloc(@sizeOf(@TypeOf(inv))); + try src.flush(); + try ops.upload(t.inv, std.mem.asBytes(&inv)); + try ops.s.synchronize(); + return t; + } + + pub fn deinit(t: *Tower) void { + t.freeBuffers(); + t.mod.unload(); + t.lib.close(); + t.gpa.destroy(t); + } + + fn freeBuffers(t: *Tower) void { + for (t.buffers.items) |*b| b.free(); + t.buffers.deinit(t.gpa); + } + + fn alloc(t: *Tower, len: usize) !u64 { + const b = try cuda.DeviceBuffer.alloc(t.d, len); + try t.buffers.append(t.gpa, b); + t.weight_bytes += len; + return b.ptr; + } + + /// The scratch one tower call of `n` patches needs, in bytes (the patches' bf16 copy included). + pub fn scratchBytes(n: usize) usize { + return n * patch_width * 2 + // patches + 2 * n * hidden * 2 + // x, h + n * @max(3 * hidden, intermediate) * 4 + // fp32 Linear out + 3 * n * hidden * 2 + // q, k, v + n * hidden * 2 + // attention out + n * @max(intermediate, hidden) * 2 + // gelu rows + n * (2 + 4) * 4 + n * 4 * 4 + // hw, idx, weights + workspace_bytes; + } + + /// Images' patches (fp32 rows of `patch_width`, each image's in its grid's merge order) to their merged rows + /// (bf16 [sum(h * w) / 4, out_hidden]) at `out`; every image attends only to itself. + pub fn encode(t: *Tower, ops: Gpu, pixels: []const f32, grids: []const Grid, out: u64) !void { + var n: usize = 0; + for (grids) |g| { + if (g.h == 0 or g.w == 0 or g.h % merge != 0 or g.w % merge != 0) return error.BadImageGrid; + n += @as(usize, g.h) * g.w; + } + if (n == 0 or n > max_patches or pixels.len != n * patch_width) return error.BadImagePatches; + const gpa = t.gpa; + // host side: bf16 patches, each patch's (row, column) and its 4 position-grid taps + const px16 = try gpa.alloc(u16, n * patch_width); + defer gpa.free(px16); + for (px16, pixels) |*o, v| o.* = bf16(v); + const hw = try gpa.alloc(i32, n * 2); + defer gpa.free(hw); + const idx = try gpa.alloc(i32, n * 4); + defer gpa.free(idx); + const wts = try gpa.alloc(f32, n * 4); + defer gpa.free(wts); + var at: usize = 0; + for (grids) |g| { + positions(g, hw[at * 2 ..][0 .. @as(usize, g.h) * g.w * 2], idx[at * 4 ..][0 .. @as(usize, g.h) * g.w * 4], wts[at * 4 ..][0 .. @as(usize, g.h) * g.w * 4]); + at += @as(usize, g.h) * g.w; + } + var scratch = try cuda.DeviceBuffer.alloc(t.d, scratchBytes(n)); + defer scratch.free(); + var cur: u64 = scratch.ptr; + const take = struct { + fn f(p: *u64, len: usize) u64 { + const r = p.*; + p.* += std.mem.alignForward(usize, len, 256); + return r; + } + }.f; + const d_px = take(&cur, n * patch_width * 2); + const x = take(&cur, n * hidden * 2); + const h = take(&cur, n * hidden * 2); + const acc = take(&cur, n * @max(3 * hidden, intermediate) * 4); + const q = take(&cur, n * hidden * 2); + const k = take(&cur, n * hidden * 2); + const v = take(&cur, n * hidden * 2); + const att = take(&cur, n * hidden * 2); + const mid = take(&cur, n * @max(intermediate, hidden) * 2); + const d_hw = take(&cur, n * 2 * 4); + const d_idx = take(&cur, n * 4 * 4); + const d_wts = take(&cur, n * 4 * 4); + const ws = cur; + const ws_len = scratch.ptr + scratch.len - cur; + try ops.upload(d_px, std.mem.sliceAsBytes(px16)); + try ops.upload(d_hw, std.mem.sliceAsBytes(hw)); + try ops.upload(d_idx, std.mem.sliceAsBytes(idx)); + try ops.upload(d_wts, std.mem.sliceAsBytes(wts)); + + var mm: Gemms = .{ .lib = &t.lib }; + defer mm.deinit(); + const m4 = n / (merge * merge); + try mm.run(n, hidden, patch_width, d_px, t.patch_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.embed, n, 1, 256, .{ acc, t.patch_b, t.pos, d_idx, d_wts, x, int(hidden) }); + const scale: f32 = 1.0 / @sqrt(@as(f32, head_dim)); + for (t.blocks) |b| { + try t.go(ops, t.f.layernorm, n, 1, 256, .{ x, b.norm1_w, b.norm1_b, h, int(hidden), eps }); + try mm.run(n, 3 * hidden, hidden, h, b.qkv_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.qkv_rope, n, heads, 128, .{ acc, b.qkv_b, d_hw, t.inv, q, k, v, int(n), int(heads), int(head_dim) }); + var s0: usize = 0; + for (grids) |g| { + const len = @as(usize, g.h) * g.w; + try t.go(ops, t.f.attention, (len + 63) / 64, heads, 64, .{ q, k, v, att, int(n), int(heads), int(s0), int(len), scale }); + s0 += len; + } + try mm.run(n, hidden, hidden, att, b.proj_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.bias_residual, n, 1, 256, .{ acc, b.proj_b, x, int(hidden) }); + try t.go(ops, t.f.layernorm, n, 1, 256, .{ x, b.norm2_w, b.norm2_b, h, int(hidden), eps }); + try mm.run(n, intermediate, hidden, h, b.fc1_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.bias_gelu, n, 1, 256, .{ acc, b.fc1_b, mid, int(intermediate), int(1) }); + try mm.run(n, hidden, intermediate, mid, b.fc2_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.bias_residual, n, 1, 256, .{ acc, b.fc2_b, x, int(hidden) }); + } + // merger: LayerNorm over 1152, four merge-ordered rows read as one of 4608 + try t.go(ops, t.f.layernorm, n, 1, 256, .{ x, t.merger_norm_w, t.merger_norm_b, h, int(hidden), eps }); + try mm.run(m4, merged, merged, h, t.fc1_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.bias_gelu, m4, 1, 256, .{ acc, t.fc1_b, mid, int(merged), int(0) }); + try mm.run(m4, out_hidden, merged, mid, t.fc2_w, acc, ws, ws_len, ops.s); + try t.go(ops, t.f.bias_cast, m4, 1, 256, .{ acc, t.fc2_b, out, int(out_hidden) }); + try ops.s.synchronize(); + } + + /// A prompt chunk's embeddings `x` (rows bf16 of the language width) take image rows: row r takes `features` + /// row src[r] (device int32) where src[r] >= 0. + pub fn splice(t: *Tower, ops: Gpu, x: u64, features: u64, src: u64, rows: usize) !void { + try t.go(ops, t.f.splice, rows, 1, 256, .{ x, features, src, int(out_hidden) }); + } + + fn go(t: *Tower, ops: Gpu, f: cuda.Function, gx: usize, gy: usize, block: u32, args: anytype) !void { + _ = t; + var a: cuda.Args = .{}; + inline for (args) |v| a.add(v); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(gx), .y = @intCast(gy) }, .block = .{ .x = block } }, ops.s, &a); + } +}; + +/// cuBLASLt plans for the shapes one tower call runs, made on first use. +const Gemms = struct { + lib: *const lt.Library, + plans: [8]?struct { m: usize, n: usize, k: usize, lin: lt.Linear } = @splat(null), + + fn run(g: *Gemms, m: usize, n: usize, k: usize, x: u64, w: u64, out: u64, ws: u64, ws_len: usize, s: cuda.Stream) !void { + for (&g.plans) |*p| { + if (p.*) |*have| { + if (have.m == m and have.n == n and have.k == k) return have.lin.run(x, w, out, ws, ws_len, s.handle); + continue; + } + p.* = .{ .m = m, .n = n, .k = k, .lin = try lt.Linear.init(g.lib, m, n, k, .f32, ws_len) }; + return p.*.?.lin.run(x, w, out, ws, ws_len, s.handle); + } + return error.TooManyShapes; + } + + fn deinit(g: *Gemms) void { + for (&g.plans) |*p| if (p.*) |*have| have.lin.deinit(); + } +}; + +fn int(x: usize) c_int { + return @intCast(x); +} + +/// fp32 to bf16, round to nearest even (torch's .to(bfloat16)). +fn bf16(v: f32) u16 { + const b: u32 = @bitCast(v); + if (std.math.isNan(v)) return 0x7fc0; + return @intCast((b + 0x7fff + ((b >> 16) & 1)) >> 16); +} + +/// The axial rotary's frequencies: 1 / 10000 ** (i / (head_dim / 2)) for even i, in fp32 as torch computes them. +pub fn invFreq(out: []f32) void { + const dim: f32 = @floatFromInt(head_dim / 2); + for (out, 0..) |*f, j| { + const e: f32 = @as(f32, @floatFromInt(2 * j)) / dim; + f.* = 1.0 / std.math.pow(f32, 10000.0, e); + } +} + +/// One image's patches in merge order: each patch's (row, column) for the rotary, and its 4 bilinear taps (with +/// align_corners) into the 48x48 learned grid with their fp32 weights, as transformers' vision_utils computes them. +pub fn positions(g: Grid, hw: []i32, idx: []i32, wts: []f32) void { + const bw = g.w / merge; + const n = @as(usize, g.h) * g.w; + for (0..n) |i| { + const in_col: u32 = @intCast(i % merge); + const in_row: u32 = @intCast((i / merge) % merge); + const block_col: u32 = @intCast((i / (merge * merge)) % bw); + const block_row: u32 = @intCast(i / (merge * merge * bw)); + const r = block_row * merge + in_row; + const c = block_col * merge + in_col; + hw[i * 2] = @intCast(r); + hw[i * 2 + 1] = @intCast(c); + const ht = taps(r, g.h); + const wt = taps(c, g.w); + for (0..2) |a| for (0..2) |b| { + idx[i * 4 + a * 2 + b] = ht.i[a] * grid_side + wt.i[b]; + wts[i * 4 + a * 2 + b] = ht.w[a] * wt.w[b]; + }; + } +} + +const Taps = struct { i: [2]i32, w: [2]f32 }; + +fn taps(index: u32, size: u32) Taps { + const side_m1: f32 = grid_side - 1; + const denom: f32 = @floatFromInt(@max(size, 2) - 1); + const src = @as(f32, @floatFromInt(index)) * side_m1 / denom; + const fl = @floor(src); + var out: Taps = undefined; + for (0..2) |o| { + const raw: i32 = @as(i32, @intFromFloat(fl)) + @as(i32, @intCast(o)); + out.i[o] = std.math.clamp(raw, 0, grid_side - 1); + const dist = @abs(src - fl - @as(f32, @floatFromInt(o))); + out.w[o] = @max(1.0 - dist, 0.0); + } + return out; +} + +test "bilinear taps match align_corners resampling at the ends and middle" { + const a = taps(0, 10); + try std.testing.expectEqual(@as(i32, 0), a.i[0]); + try std.testing.expectEqual(@as(f32, 1), a.w[0]); + const b = taps(9, 10); + try std.testing.expectEqual(@as(i32, 47), b.i[0]); + try std.testing.expectEqual(@as(f32, 1), b.w[0]); +} From 407cb2847de6c312dd7477ef626a153df4025f2d Mon Sep 17 00:00:00 2001 From: BobClawblaw Date: Mon, 12 Oct 2026 02:37:38 +0000 Subject: [PATCH 07/17] Qwen image preprocessing on Linux: stb_image decode, EXIF, alpha, smart_resize, PIL bicubic, patches PNG decode and patches equal 0.6.6's bit for bit on seven fixtures; JPEGs differ in 1-6% of bytes (stb's IDCT against libjpeg-turbo's). --- zig/build/cuda.zig | 3 + zig/src/cli/qwen27_cuda.zig | 17 + zig/src/families/qwen27/cuda.zig | 2 + zig/src/families/qwen27/cuda/image.zig | 354 ++ zig/vendor/stb/COMMIT | 1 + zig/vendor/stb/stb_image.c | 9 + zig/vendor/stb/stb_image.h | 7988 ++++++++++++++++++++++++ 7 files changed, 8374 insertions(+) create mode 100644 zig/src/families/qwen27/cuda/image.zig create mode 100644 zig/vendor/stb/COMMIT create mode 100644 zig/vendor/stb/stb_image.c create mode 100644 zig/vendor/stb/stb_image.h diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 188de6ea75..50e669ae28 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -94,6 +94,9 @@ fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin qwen27.addImport("core", core); qwen27.addImport("lanes", lanes); qwen27.addImport("nemotron", nemotron); // the checkpoint Source and torch ops the CUDA families share + // images' PNG and JPEG decoding on Linux (stb_image, vendored) + qwen27.addCSourceFile(.{ .file = b.path("zig/vendor/stb/stb_image.c"), .flags = &.{ "-O2", "-fno-sanitize=undefined" } }); + qwen27.addIncludePath(b.path("zig/vendor/stb")); return .{ .core = core, .lanes = lanes, .nemotron = nemotron, .qwen27 = qwen27, .tokenizer = tokenizer, .heat = heat }; } diff --git a/zig/src/cli/qwen27_cuda.zig b/zig/src/cli/qwen27_cuda.zig index dfdfe785f9..d1d0e879ad 100644 --- a/zig/src/cli/qwen27_cuda.zig +++ b/zig/src/cli/qwen27_cuda.zig @@ -487,6 +487,23 @@ fn checkVision(gpa: std.mem.Allocator, arena: std.mem.Allocator, io: std.Io, mod const want_bytes = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("features").?.string }), arena, .limited(1 << 30)); const px = try arena.alloc(f32, px_bytes.len / 4); @memcpy(std.mem.sliceAsBytes(px), px_bytes[0 .. px.len * 4]); + { // our decode and patches from the image's file, against 0.6.6's + const file = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("file").?.string }), arena, .limited(1 << 30)); + const want_rgb = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("rgb").?.string }), arena, .limited(1 << 30)); + const rgb = try qwen.image.decode(gpa, file); + defer rgb.deinit(gpa); + var px_diff: usize = 0; + if (rgb.px.len == want_rgb.len) { + for (rgb.px, want_rgb) |a, b| px_diff += @intFromBool(a != b); + } else px_diff = std.math.maxInt(usize); + const prep = try qwen.image.prepare(gpa, file, 4096); + defer gpa.free(prep.pixels); + var patch_diff: usize = 0; + if (prep.gh == g.h and prep.gw == g.w and prep.pixels.len == px.len) { + for (prep.pixels, px) |a, b| patch_diff += @intFromBool(@as(u32, @bitCast(a)) != @as(u32, @bitCast(b))); + } else patch_diff = std.math.maxInt(usize); + std.debug.print("{s}: decode {d}x{d}, {d} of {d} bytes differ from PIL's; patches grid {d}x{d}, {d} of {d} values differ\n", .{ name, rgb.w, rgb.h, px_diff, want_rgb.len, prep.gh, prep.gw, patch_diff, px.len }); + } const rows = @as(usize, g.h) * g.w / 4; var out = try cuda.DeviceBuffer.alloc(&driver, rows * V.out_hidden * 2); defer out.free(); diff --git a/zig/src/families/qwen27/cuda.zig b/zig/src/families/qwen27/cuda.zig index 746c12d658..650f1748ef 100644 --- a/zig/src/families/qwen27/cuda.zig +++ b/zig/src/families/qwen27/cuda.zig @@ -15,6 +15,7 @@ pub const draft = @import("cuda/draft.zig"); pub const lone = @import("cuda/lone.zig"); pub const drafts = @import("cuda/drafts.zig"); pub const vision = @import("cuda/vision.zig"); +pub const image = @import("cuda/image.zig"); test { _ = config; @@ -32,4 +33,5 @@ test { _ = lone; _ = native; _ = vision; + _ = image; } diff --git a/zig/src/families/qwen27/cuda/image.zig b/zig/src/families/qwen27/cuda/image.zig new file mode 100644 index 0000000000..0546e66e8c --- /dev/null +++ b/zig/src/families/qwen27/cuda/image.zig @@ -0,0 +1,354 @@ +//! An image's bytes to Qwen3.5 vision patches as TensorFold 0.6.6's --vision makes them on CUDA: decoded as its +//! vision/images.py does with PIL (stb_image here: the stored values, no colour management; EXIF orientation applied; +//! alpha composited over white with PIL's integer blend), then transformers' Qwen2VLImageProcessorPil at the caps +//! 0.6.6 passes it: smart_resize to multiples of 32 within [32^2, tokens * 32^2] pixels, PIL's 8-bit bicubic +//! resampler, x / 255 in float64 rounded to float32, (x - 0.5) / 0.5, and 16x16 patches in 2x2 merge order with each +//! patch's frame given twice. PNG patches equal 0.6.6's bit for bit; JPEG decoders may differ by a level. +const std = @import("std"); +const vision = @import("vision.zig"); + +extern fn stbi_load_from_memory(buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, comp: *c_int, req_comp: c_int) ?[*]u8; +extern fn stbi_load_16_from_memory(buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, comp: *c_int, req_comp: c_int) ?[*]u16; +extern fn stbi_is_16_bit_from_memory(buffer: [*]const u8, len: c_int) c_int; +extern fn stbi_info_from_memory(buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, comp: *c_int) c_int; +extern fn stbi_image_free(p: ?*anyopaque) void; + +pub const Rgb = struct { + w: u32, + h: u32, + px: []u8, // row-major RGB, 3 bytes a pixel + + pub fn deinit(r: Rgb, gpa: std.mem.Allocator) void { + gpa.free(r.px); + } +}; + +/// One image ready for the tower: its patches [gh * gw, 1536] in merge order, its grid and its tokens (gh * gw / 4). +pub const Prepared = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 }; + +pub const Error = error{ BadImage, ImageTooLarge, Animated, ImageTooSmall, OutOfMemory }; + +/// images.py's ImageLimits: sides and decoded pixels (the server bounds the encoded bytes). +pub const max_side = 8192; +pub const max_pixels = 16 << 20; +const factor = vision.patch * vision.merge; // 32 + +/// Bytes to patches for at most `max_tokens` tokens (0.6.6's per-image cap: the request's budget shared, 4096 at most). +pub fn prepare(gpa: std.mem.Allocator, bytes: []const u8, max_tokens: u32) Error!Prepared { + const img = try decode(gpa, bytes); + defer img.deinit(gpa); + return prepareRgb(gpa, img, std.hash.Wyhash.hash(0x51e7, bytes), max_tokens); +} + +pub fn prepareRgb(gpa: std.mem.Allocator, img: Rgb, hash: u64, max_tokens: u32) Error!Prepared { + const tokens = @min(max_tokens, vision.max_patches / (vision.merge * vision.merge)); + if (tokens == 0) return error.ImageTooSmall; + const size = try smartResize(img.h, img.w, factor * factor, @as(u64, tokens) * factor * factor); + const resized = try resize(gpa, img, size.w, size.h); + defer resized.deinit(gpa); + const gh = size.h / vision.patch; + const gw = size.w / vision.patch; + return .{ .pixels = try patchify(gpa, resized), .gh = gh, .gw = gw, .tokens = gh * gw / (vision.merge * vision.merge), .hash = hash }; +} + +pub const Size = struct { h: u32, w: u32 }; + +/// transformers' smart_resize: both sides multiples of `factor` (Python's round, half to even), the pixels within +/// [min_pixels, max_pixels], the aspect ratio kept as well as that allows. +pub fn smartResize(height: u32, width: u32, min_pixels: u64, max_pixels_: u64) Error!Size { + const h: f64 = @floatFromInt(height); + const w: f64 = @floatFromInt(width); + if (@max(h, w) / @min(h, w) > 200) return error.BadImage; + const f: f64 = factor; + var hb: f64 = roundEven(h / f) * f; + var wb: f64 = roundEven(w / f) * f; + if (hb * wb > @as(f64, @floatFromInt(max_pixels_))) { + const beta = @sqrt(h * w / @as(f64, @floatFromInt(max_pixels_))); + hb = @max(f, @floor(h / beta / f) * f); + wb = @max(f, @floor(w / beta / f) * f); + } else if (hb * wb < @as(f64, @floatFromInt(min_pixels))) { + const beta = @sqrt(@as(f64, @floatFromInt(min_pixels)) / (h * w)); + hb = @ceil(h * beta / f) * f; + wb = @ceil(w * beta / f) * f; + } + return .{ .h = @intFromFloat(hb), .w = @intFromFloat(wb) }; +} + +fn roundEven(x: f64) f64 { + const r = @round(x); + return if (@abs(x - @trunc(x)) == 0.5 and @mod(r, 2) != 0) r - std.math.sign(x) else r; +} + +/// The resized image scaled by 1/255 (in float64, then float32), normalized by mean 0.5 and std 0.5, cut into +/// 16x16 patches in 2x2 merge order, each patch [channel, frame (twice), row, column]. +pub fn patchify(gpa: std.mem.Allocator, img: Rgb) Error![]f32 { + const P = vision.patch; + const M = vision.merge; + const T = vision.temporal; + const gh = img.h / P; + const gw = img.w / P; + const out = try gpa.alloc(f32, @as(usize, gh) * gw * vision.patch_width); + var lut: [256]f32 = undefined; + for (&lut, 0..) |*v, i| { + const scaled: f32 = @floatCast(@as(f64, @floatFromInt(i)) * (1.0 / 255.0)); + v.* = (scaled - 0.5) / 0.5; + } + var row: usize = 0; + for (0..gh / M) |by| for (0..gw / M) |bx| for (0..M) |my| for (0..M) |mx| { + const y0 = (by * M + my) * P; + const x0 = (bx * M + mx) * P; + const dst = out[row * vision.patch_width ..][0..vision.patch_width]; + for (0..3) |ch| for (0..T) |t| for (0..P) |dy| for (0..P) |dx| { + dst[((ch * T + t) * P + dy) * P + dx] = lut[img.px[((y0 + dy) * img.w + x0 + dx) * 3 + ch]]; + }; + row += 1; + }; + return out; +} + +// ---- decoding (stb_image), EXIF orientation and alpha, as PIL gives images.py its RGB ---- + +/// A single-frame PNG or JPEG as 8-bit RGB: upright by its EXIF orientation, alpha composited over white, 16-bit +/// gray clipped to 255 and other 16-bit layouts cut to their high byte (what PIL's convert("RGB") gives). +pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) Error!Rgb { + if (bytes.len < 8 or bytes.len > std.math.maxInt(c_int)) return error.BadImage; + const n: c_int = @intCast(bytes.len); + if (std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n") and pngAnimated(bytes)) return error.Animated; + var w: c_int = 0; + var h: c_int = 0; + var comp: c_int = 0; + if (stbi_info_from_memory(bytes.ptr, n, &w, &h, &comp) == 0) return error.BadImage; + if (w <= 0 or h <= 0) return error.BadImage; + if (w > max_side or h > max_side or @as(u64, @intCast(w)) * @as(u64, @intCast(h)) > max_pixels) return error.ImageTooLarge; + const W: usize = @intCast(w); + const H: usize = @intCast(h); + const out = try gpa.alloc(u8, W * H * 3); + errdefer gpa.free(out); + if (stbi_is_16_bit_from_memory(bytes.ptr, n) != 0 and comp == 1) { + const p = stbi_load_16_from_memory(bytes.ptr, n, &w, &h, &comp, 0) orelse return error.BadImage; + defer stbi_image_free(p); + for (0..W * H) |i| @memset(out[i * 3 ..][0..3], @intCast(@min(p[i], 255))); + } else { + const p = stbi_load_from_memory(bytes.ptr, n, &w, &h, &comp, 0) orelse return error.BadImage; + defer stbi_image_free(p); + const c: usize = @intCast(comp); + for (0..W * H) |i| { + const s = p[i * c ..][0..c]; + const px = out[i * 3 ..][0..3]; + switch (c) { + 1 => @memset(px, s[0]), + 2 => @memset(px, overWhite(s[0], s[1])), + 3 => @memcpy(px, s[0..3]), + 4 => for (0..3) |k| { + px[k] = overWhite(s[k], s[3]); + }, + else => return error.BadImage, + } + } + } + const img: Rgb = .{ .w = @intCast(W), .h = @intCast(H), .px = out }; + const o = orientation(bytes); + if (o < 2 or o > 8) return img; + defer img.deinit(gpa); + return orient(gpa, img, o); +} + +/// An APNG (an acTL chunk before the image data) has more than one frame: images.py refuses it. +fn pngAnimated(bytes: []const u8) bool { + var at: usize = 8; + while (at + 8 <= bytes.len) { + const len = std.mem.readInt(u32, bytes[at..][0..4], .big); + const kind = bytes[at + 4 ..][0..4]; + if (std.mem.eql(u8, kind, "acTL")) return true; + if (std.mem.eql(u8, kind, "IDAT")) return false; + at += 12 + @as(usize, len); + } + return false; +} + +/// The EXIF orientation (tag 0x0112 of IFD0) a JPEG's APP1 or a PNG's eXIf chunk carries; 1 when none. +pub fn orientation(bytes: []const u8) u32 { + if (std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n")) { + var at: usize = 8; + while (at + 12 <= bytes.len) { + const len: usize = std.mem.readInt(u32, bytes[at..][0..4], .big); + if (at + 12 + len > bytes.len) break; + if (std.mem.eql(u8, bytes[at + 4 ..][0..4], "eXIf")) return tiffOrientation(bytes[at + 8 ..][0..len]); + at += 12 + len; + } + return 1; + } + var at: usize = 2; + while (at + 4 <= bytes.len and bytes[at] == 0xff) { + const marker = bytes[at + 1]; + if (marker == 0xd9 or marker == 0xda) break; // end of image, start of scan + const len: usize = std.mem.readInt(u16, bytes[at + 2 ..][0..2], .big); + if (len < 2 or at + 2 + len > bytes.len) break; + const seg = bytes[at + 4 .. at + 2 + len]; + if (marker == 0xe1 and std.mem.startsWith(u8, seg, "Exif\x00\x00")) return tiffOrientation(seg[6..]); + at += 2 + len; + } + return 1; +} + +fn tiffOrientation(t: []const u8) u32 { + if (t.len < 8) return 1; + const endian: std.builtin.Endian = if (std.mem.eql(u8, t[0..2], "II")) .little else if (std.mem.eql(u8, t[0..2], "MM")) .big else return 1; + if (std.mem.readInt(u16, t[2..4], endian) != 42) return 1; + const ifd: usize = std.mem.readInt(u32, t[4..8], endian); + if (ifd + 2 > t.len) return 1; + const count: usize = std.mem.readInt(u16, t[ifd..][0..2], endian); + for (0..count) |i| { + const e = ifd + 2 + i * 12; + if (e + 12 > t.len) return 1; + if (std.mem.readInt(u16, t[e..][0..2], endian) != 0x0112) continue; + if (std.mem.readInt(u16, t[e + 2 ..][0..2], endian) != 3) return 1; // SHORT + return std.mem.readInt(u16, t[e + 8 ..][0..2], endian); + } + return 1; +} + +// The functions below are the ones GLM's image.zig (families/glm) has for its Metal path: the same PIL arithmetic, +// kept here because the CUDA module cannot import that family's files. + +/// PIL's exif_transpose: orientation 2-8 as FLIP_LEFT_RIGHT, ROTATE_180, FLIP_TOP_BOTTOM, TRANSPOSE, ROTATE_270, +/// TRANSVERSE, ROTATE_90; each output pixel read from its source pixel. +pub fn orient(gpa: std.mem.Allocator, src: Rgb, o: u32) Error!Rgb { + const w: usize = src.w; + const h: usize = src.h; + const swap = o >= 5; + const ow = if (swap) h else w; + const oh = if (swap) w else h; + const out = try gpa.alloc(u8, ow * oh * 3); + for (0..oh) |y| for (0..ow) |x| { + const s: [2]usize = switch (o) { + 2 => .{ w - 1 - x, y }, + 3 => .{ w - 1 - x, h - 1 - y }, + 4 => .{ x, h - 1 - y }, + 5 => .{ y, x }, + 6 => .{ y, h - 1 - x }, + 7 => .{ w - 1 - y, h - 1 - x }, + else => .{ w - 1 - y, x }, + }; + @memcpy(out[(y * ow + x) * 3 ..][0..3], src.px[(s[1] * w + s[0]) * 3 ..][0..3]); + }; + return .{ .w = @intCast(ow), .h = @intCast(oh), .px = out }; +} + +/// PIL's paste of a pixel with alpha `a` onto white: DIV255(255 * (255 - a) + c * a). +fn overWhite(c: u8, a: u8) u8 { + const t: u32 = 255 * (255 - @as(u32, a)) + @as(u32, c) * a + 128; + return @intCast(((t >> 8) + t) >> 8); +} + +// ---- PIL's ImagingResample for 8-bit images (Resample.c), bicubic (a = -0.5) ---- + +const precision_bits = 32 - 8 - 2; + +fn bicubic(x0: f64) f64 { + const a = -0.5; + const x = @abs(x0); + if (x < 1.0) return ((a + 2.0) * x - (a + 3.0)) * x * x + 1; + if (x < 2.0) return (((x - 5) * x + 8) * x - 4) * a; + return 0; +} + +const Coeffs = struct { bounds: []u32, kk: []i32, ksize: usize }; + +/// precompute_coeffs and normalize_coeffs_8bpc: each output pixel's first input pixel, count and fixed-point weights. +fn coeffs(gpa: std.mem.Allocator, in_size: u32, out_size: u32) Error!Coeffs { + const scale = @as(f64, @floatFromInt(in_size)) / @as(f64, @floatFromInt(out_size)); + const filterscale = @max(scale, 1.0); + const support = 2.0 * filterscale; + const ksize: usize = @as(usize, @intFromFloat(@ceil(support))) * 2 + 1; + const bounds = try gpa.alloc(u32, @as(usize, out_size) * 2); + errdefer gpa.free(bounds); + const kk = try gpa.alloc(i32, @as(usize, out_size) * ksize); + errdefer gpa.free(kk); + var pre = try gpa.alloc(f64, ksize); + defer gpa.free(pre); + const ss = 1.0 / filterscale; + for (0..out_size) |xx| { + const center = (@as(f64, @floatFromInt(xx)) + 0.5) * scale; + var xmin_i: i64 = @intFromFloat(center - support + 0.5); // (int) truncates toward zero, as C does + if (xmin_i < 0) xmin_i = 0; + var xmax_i: i64 = @intFromFloat(center + support + 0.5); + if (xmax_i > in_size) xmax_i = in_size; + xmax_i -= xmin_i; + const xmin: usize = @intCast(xmin_i); + const xmax: usize = @intCast(xmax_i); + var ww: f64 = 0; + for (0..xmax) |x| { + const w = bicubic((@as(f64, @floatFromInt(x + xmin)) - center + 0.5) * ss); + pre[x] = w; + ww += w; + } + for (0..ksize) |x| { + const k = if (x < xmax) (if (ww != 0) pre[x] / ww else pre[x]) else 0; + const v = k * @as(f64, @floatFromInt(@as(i64, 1) << precision_bits)); + kk[xx * ksize + x] = @intFromFloat(if (v < 0) v - 0.5 else v + 0.5); // C's (int) of the rounded value + } + bounds[xx * 2] = @intCast(xmin); + bounds[xx * 2 + 1] = @intCast(xmax); + } + return .{ .bounds = bounds, .kk = kk, .ksize = ksize }; +} + +fn clip8(v: i64) u8 { + const s = v >> precision_bits; + return if (s < 0) 0 else if (s > 255) 255 else @intCast(s); +} + +/// Image.resize((w, h), BICUBIC) on an 8-bit RGB image: horizontal pass, then vertical, each rounded to 8 bits. +pub fn resize(gpa: std.mem.Allocator, src: Rgb, w: u32, h: u32) Error!Rgb { + var cur = src; + var owned = false; + errdefer if (owned) cur.deinit(gpa); + if (w != src.w) { + const c = try coeffs(gpa, src.w, w); + defer gpa.free(c.bounds); + defer gpa.free(c.kk); + const out = try gpa.alloc(u8, @as(usize, w) * cur.h * 3); + for (0..cur.h) |y| for (0..w) |xx| { + const xmin = c.bounds[xx * 2]; + const xmax = c.bounds[xx * 2 + 1]; + const k = c.kk[xx * c.ksize ..]; + for (0..3) |ch| { + var ss: i64 = 1 << (precision_bits - 1); + for (0..xmax) |x| ss += @as(i64, cur.px[(y * cur.w + x + xmin) * 3 + ch]) * k[x]; + out[(y * w + xx) * 3 + ch] = clip8(ss); + } + }; + if (owned) cur.deinit(gpa); + cur = .{ .w = w, .h = cur.h, .px = out }; + owned = true; + } + if (h != src.h) { + const c = try coeffs(gpa, src.h, h); + defer gpa.free(c.bounds); + defer gpa.free(c.kk); + const out = try gpa.alloc(u8, @as(usize, cur.w) * h * 3); + for (0..h) |yy| { + const ymin = c.bounds[yy * 2]; + const ymax = c.bounds[yy * 2 + 1]; + const k = c.kk[yy * c.ksize ..]; + for (0..cur.w) |x| for (0..3) |ch| { + var ss: i64 = 1 << (precision_bits - 1); + for (0..ymax) |y| ss += @as(i64, cur.px[((y + ymin) * cur.w + x) * 3 + ch]) * k[y]; + out[(yy * cur.w + x) * 3 + ch] = clip8(ss); + }; + } + if (owned) cur.deinit(gpa); + cur = .{ .w = cur.w, .h = h, .px = out }; + owned = true; + } + if (!owned) cur = .{ .w = src.w, .h = src.h, .px = try gpa.dupe(u8, src.px) }; + return cur; +} + +test "smart_resize rounds half to even and respects the pixel bounds" { + try std.testing.expectEqual(Size{ .h = 32, .w = 64 }, try smartResize(15, 20, 1024, 4096 * 1024)); + try std.testing.expectEqual(Size{ .h = 384, .w = 512 }, try smartResize(389, 517, 1024, 4096 * 1024)); + try std.testing.expectEqual(@as(f64, 2), roundEven(2.5)); + try std.testing.expectEqual(@as(f64, 2), roundEven(1.5)); +} diff --git a/zig/vendor/stb/COMMIT b/zig/vendor/stb/COMMIT new file mode 100644 index 0000000000..7b40c30ab3 --- /dev/null +++ b/zig/vendor/stb/COMMIT @@ -0,0 +1 @@ +2c980bb59875b0d32144a71867fbdebb2f77cd20 diff --git a/zig/vendor/stb/stb_image.c b/zig/vendor/stb/stb_image.c new file mode 100644 index 0000000000..488630f836 --- /dev/null +++ b/zig/vendor/stb/stb_image.c @@ -0,0 +1,9 @@ +// stb_image (v2.30, public domain or MIT; the commit in COMMIT): PNG and JPEG from memory, for the Linux image path. +#define STB_IMAGE_IMPLEMENTATION +#define STBI_ONLY_PNG +#define STBI_ONLY_JPEG +#define STBI_NO_STDIO +#define STBI_NO_LINEAR +#define STBI_NO_HDR +#define STBI_MAX_DIMENSIONS 8192 +#include "stb_image.h" diff --git a/zig/vendor/stb/stb_image.h b/zig/vendor/stb/stb_image.h new file mode 100644 index 0000000000..9eedabedc4 --- /dev/null +++ b/zig/vendor/stb/stb_image.h @@ -0,0 +1,7988 @@ +/* stb_image - v2.30 - public domain image loader - http://nothings.org/stb + no warranty implied; use at your own risk + + Do this: + #define STB_IMAGE_IMPLEMENTATION + before you include this file in *one* C or C++ file to create the implementation. + + // i.e. it should look like this: + #include ... + #include ... + #include ... + #define STB_IMAGE_IMPLEMENTATION + #include "stb_image.h" + + You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. + And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free + + + QUICK NOTES: + Primarily of interest to game developers and other people who can + avoid problematic images and only need the trivial interface + + JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) + PNG 1/2/4/8/16-bit-per-channel + + TGA (not sure what subset, if a subset) + BMP non-1bpp, non-RLE + PSD (composited view only, no extra channels, 8/16 bit-per-channel) + + GIF (*comp always reports as 4-channel) + HDR (radiance rgbE format) + PIC (Softimage PIC) + PNM (PPM and PGM binary only) + + Animated GIF still needs a proper API, but here's one way to do it: + http://gist.github.com/urraka/685d9a6340b26b830d49 + + - decode from memory or through FILE (define STBI_NO_STDIO to remove code) + - decode from arbitrary I/O callbacks + - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) + + Full documentation under "DOCUMENTATION" below. + + +LICENSE + + See end of file for license information. + +RECENT REVISION HISTORY: + + 2.30 (2024-05-31) avoid erroneous gcc warning + 2.29 (2023-05-xx) optimizations + 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff + 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes + 2.26 (2020-07-13) many minor fixes + 2.25 (2020-02-02) fix warnings + 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically + 2.23 (2019-08-11) fix clang static analysis warning + 2.22 (2019-03-04) gif fixes, fix warnings + 2.21 (2019-02-25) fix typo in comment + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings + 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes + 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 + RGB-format JPEG; remove white matting in PSD; + allocate large structures on the stack; + correct channel count for PNG & BMP + 2.10 (2016-01-22) avoid warning introduced in 2.09 + 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED + + See end of file for full revision history. + + + ============================ Contributors ========================= + + Image formats Extensions, features + Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) + Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) + Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) + Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) + Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) + Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) + Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) + github:urraka (animated gif) Junggon Kim (PNM comments) + Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) + socks-the-fox (16-bit PNG) + Jeremy Sawicki (handle all ImageNet JPGs) + Optimizations & bugfixes Mikhail Morozov (1-bit BMP) + Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) + Arseny Kapoulkine Simon Breuss (16-bit PNM) + John-Mark Allen + Carmelo J Fdez-Aguera + + Bug & warning fixes + Marc LeBlanc David Woo Guillaume George Martins Mozeiko + Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski + Phil Jordan Dave Moore Roy Eltham + Hayaki Saito Nathan Reed Won Chun + Luke Graham Johan Duparc Nick Verigakis the Horde3D community + Thomas Ruf Ronny Chevalier github:rlyeh + Janez Zemva John Bartholomew Michal Cichon github:romigrou + Jonathan Blow Ken Hamada Tero Hanninen github:svdijk + Eugene Golushkov Laurent Gomila Cort Stratton github:snagar + Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex + Cass Everitt Ryamond Barbiero github:grim210 + Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw + Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus + Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo + Julian Raschke Gregory Mullen Christian Floisand github:darealshinji + Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 + Brad Weinberger Matvey Cherevko github:mosra + Luca Sas Alexander Veselov Zack Middleton [reserved] + Ryan C. Gordon [reserved] [reserved] + DO NOT ADD YOUR NAME HERE + + Jacko Dirks + + To add your name to the credits, pick a random blank space in the middle and fill it. + 80% of merge conflicts on stb PRs are due to people adding their name at the end + of the credits. +*/ + +#ifndef STBI_INCLUDE_STB_IMAGE_H +#define STBI_INCLUDE_STB_IMAGE_H + +// DOCUMENTATION +// +// Limitations: +// - no 12-bit-per-channel JPEG +// - no JPEGs with arithmetic coding +// - GIF always returns *comp=4 +// +// Basic usage (see HDR discussion below for HDR usage): +// int x,y,n; +// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); +// // ... process data if not NULL ... +// // ... x = width, y = height, n = # 8-bit components per pixel ... +// // ... replace '0' with '1'..'4' to force that many components per pixel +// // ... but 'n' will always be the number that it would have been if you said 0 +// stbi_image_free(data); +// +// Standard parameters: +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *channels_in_file -- outputs # of image components in image file +// int desired_channels -- if non-zero, # of image components requested in result +// +// The return value from an image loader is an 'unsigned char *' which points +// to the pixel data, or NULL on an allocation failure or if the image is +// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, +// with each pixel consisting of N interleaved 8-bit components; the first +// pixel pointed to is top-left-most in the image. There is no padding between +// image scanlines or between pixels, regardless of format. The number of +// components N is 'desired_channels' if desired_channels is non-zero, or +// *channels_in_file otherwise. If desired_channels is non-zero, +// *channels_in_file has the number of components that _would_ have been +// output otherwise. E.g. if you set desired_channels to 4, you will always +// get RGBA output, but you can check *channels_in_file to see if it's trivially +// opaque because e.g. there were only 3 channels in the source image. +// +// An output image with N components has the following components interleaved +// in this order in each pixel: +// +// N=#comp components +// 1 grey +// 2 grey, alpha +// 3 red, green, blue +// 4 red, green, blue, alpha +// +// If image loading fails for any reason, the return value will be NULL, +// and *x, *y, *channels_in_file will be unchanged. The function +// stbi_failure_reason() can be queried for an extremely brief, end-user +// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS +// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// more user-friendly ones. +// +// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. +// +// To query the width, height and component count of an image without having to +// decode the full file, you can use the stbi_info family of functions: +// +// int x,y,n,ok; +// ok = stbi_info(filename, &x, &y, &n); +// // returns ok=1 and sets x, y, n if image is a supported format, +// // 0 otherwise. +// +// Note that stb_image pervasively uses ints in its public API for sizes, +// including sizes of memory buffers. This is now part of the API and thus +// hard to change without causing breakage. As a result, the various image +// loaders all have certain limits on image size; these differ somewhat +// by format but generally boil down to either just under 2GB or just under +// 1GB. When the decoded image would be larger than this, stb_image decoding +// will fail. +// +// Additionally, stb_image will reject image files that have any of their +// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS, +// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit, +// the only way to have an image with such dimensions load correctly +// is for it to have a rather extreme aspect ratio. Either way, the +// assumption here is that such larger images are likely to be malformed +// or malicious. If you do need to load an image with individual dimensions +// larger than that, and it still fits in the overall size limit, you can +// #define STBI_MAX_DIMENSIONS on your own to be something larger. +// +// =========================================================================== +// +// UNICODE: +// +// If compiling for Windows and you wish to use Unicode filenames, compile +// with +// #define STBI_WINDOWS_UTF8 +// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert +// Windows wchar_t filenames to utf8. +// +// =========================================================================== +// +// Philosophy +// +// stb libraries are designed with the following priorities: +// +// 1. easy to use +// 2. easy to maintain +// 3. good performance +// +// Sometimes I let "good performance" creep up in priority over "easy to maintain", +// and for best performance I may provide less-easy-to-use APIs that give higher +// performance, in addition to the easy-to-use ones. Nevertheless, it's important +// to keep in mind that from the standpoint of you, a client of this library, +// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. +// +// Some secondary priorities arise directly from the first two, some of which +// provide more explicit reasons why performance can't be emphasized. +// +// - Portable ("ease of use") +// - Small source code footprint ("easy to maintain") +// - No dependencies ("ease of use") +// +// =========================================================================== +// +// I/O callbacks +// +// I/O callbacks allow you to read from arbitrary sources, like packaged +// files or some other source. Data read from callbacks are processed +// through a small internal buffer (currently 128 bytes) to try to reduce +// overhead. +// +// The three functions you must define are "read" (reads some bytes of data), +// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). +// +// =========================================================================== +// +// SIMD support +// +// The JPEG decoder will try to automatically use SIMD kernels on x86 when +// supported by the compiler. For ARM Neon support, you must explicitly +// request it. +// +// (The old do-it-yourself SIMD API is no longer supported in the current +// code.) +// +// On x86, SSE2 will automatically be used when available based on a run-time +// test; if not, the generic C versions are used as a fall-back. On ARM targets, +// the typical path is to have separate builds for NEON and non-NEON devices +// (at least this is true for iOS and Android). Therefore, the NEON support is +// toggled by a build flag: define STBI_NEON to get NEON loops. +// +// If for some reason you do not want to use any of SIMD code, or if +// you have issues compiling it, you can disable it entirely by +// defining STBI_NO_SIMD. +// +// =========================================================================== +// +// HDR image support (disable by defining STBI_NO_HDR) +// +// stb_image supports loading HDR images in general, and currently the Radiance +// .HDR file format specifically. You can still load any file through the existing +// interface; if you attempt to load an HDR file, it will be automatically remapped +// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// both of these constants can be reconfigured through this interface: +// +// stbi_hdr_to_ldr_gamma(2.2f); +// stbi_hdr_to_ldr_scale(1.0f); +// +// (note, do not use _inverse_ constants; stbi_image will invert them +// appropriately). +// +// Additionally, there is a new, parallel interface for loading files as +// (linear) floats to preserve the full dynamic range: +// +// float *data = stbi_loadf(filename, &x, &y, &n, 0); +// +// If you load LDR images through this interface, those images will +// be promoted to floating point values, run through the inverse of +// constants corresponding to the above: +// +// stbi_ldr_to_hdr_scale(1.0f); +// stbi_ldr_to_hdr_gamma(2.2f); +// +// Finally, given a filename (or an open file or memory block--see header +// file for details) containing image data, you can query for the "most +// appropriate" interface to use (that is, whether the image is HDR or +// not), using: +// +// stbi_is_hdr(char *filename); +// +// =========================================================================== +// +// iPhone PNG support: +// +// We optionally support converting iPhone-formatted PNGs (which store +// premultiplied BGRA) back to RGB, even though they're internally encoded +// differently. To enable this conversion, call +// stbi_convert_iphone_png_to_rgb(1). +// +// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per +// pixel to remove any premultiplied alpha *only* if the image file explicitly +// says there's premultiplied data (currently only happens in iPhone images, +// and only if iPhone convert-to-rgb processing is on). +// +// =========================================================================== +// +// ADDITIONAL CONFIGURATION +// +// - You can suppress implementation of any of the decoders to reduce +// your code footprint by #defining one or more of the following +// symbols before creating the implementation. +// +// STBI_NO_JPEG +// STBI_NO_PNG +// STBI_NO_BMP +// STBI_NO_PSD +// STBI_NO_TGA +// STBI_NO_GIF +// STBI_NO_HDR +// STBI_NO_PIC +// STBI_NO_PNM (.ppm and .pgm) +// +// - You can request *only* certain decoders and suppress all other ones +// (this will be more forward-compatible, as addition of new decoders +// doesn't require you to disable them explicitly): +// +// STBI_ONLY_JPEG +// STBI_ONLY_PNG +// STBI_ONLY_BMP +// STBI_ONLY_PSD +// STBI_ONLY_TGA +// STBI_ONLY_GIF +// STBI_ONLY_HDR +// STBI_ONLY_PIC +// STBI_ONLY_PNM (.ppm and .pgm) +// +// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still +// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB +// +// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater +// than that size (in either width or height) without further processing. +// This is to let programs in the wild set an upper bound to prevent +// denial-of-service attacks on untrusted data, as one could generate a +// valid image of gigantic dimensions and force stb_image to allocate a +// huge block of memory and spend disproportionate time decoding it. By +// default this is set to (1 << 24), which is 16777216, but that's still +// very big. + +#ifndef STBI_NO_STDIO +#include +#endif // STBI_NO_STDIO + +#define STBI_VERSION 1 + +enum +{ + STBI_default = 0, // only used for desired_channels + + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 +}; + +#include +typedef unsigned char stbi_uc; +typedef unsigned short stbi_us; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef STBIDEF +#ifdef STB_IMAGE_STATIC +#define STBIDEF static +#else +#define STBIDEF extern +#endif +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// PRIMARY API - works on images of any type +// + +// +// load image by filename, open file, or memory buffer +// + +typedef struct +{ + int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read + void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + int (*eof) (void *user); // returns nonzero if we are at end of file/data +} stbi_io_callbacks; + +//////////////////////////////////// +// +// 8-bits-per-channel interface +// + +STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +// for stbi_load_from_file, file pointer is left pointing immediately after image +#endif + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +#endif + +#ifdef STBI_WINDOWS_UTF8 +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); +#endif + +//////////////////////////////////// +// +// 16-bits-per-channel interface +// + +STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +#endif + +//////////////////////////////////// +// +// float-per-channel interface +// +#ifndef STBI_NO_LINEAR + STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + + #ifndef STBI_NO_STDIO + STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); + #endif +#endif + +#ifndef STBI_NO_HDR + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); + STBIDEF void stbi_hdr_to_ldr_scale(float scale); +#endif // STBI_NO_HDR + +#ifndef STBI_NO_LINEAR + STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); + STBIDEF void stbi_ldr_to_hdr_scale(float scale); +#endif // STBI_NO_LINEAR + +// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename); +STBIDEF int stbi_is_hdr_from_file(FILE *f); +#endif // STBI_NO_STDIO + + +// get a VERY brief reason for failure +// on most compilers (and ALL modern mainstream compilers) this is threadsafe +STBIDEF const char *stbi_failure_reason (void); + +// free the loaded image -- this is just free() +STBIDEF void stbi_image_free (void *retval_from_stbi_load); + +// get image dimensions & components without fully decoding +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit (char const *filename); +STBIDEF int stbi_is_16_bit_from_file(FILE *f); +#endif + + + +// for image formats that explicitly notate that they have premultiplied alpha, +// we just return the colors as stored in the file. set this flag to force +// unpremultiplication. results are undefined if the unpremultiply overflow. +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); + +// indicate whether we should process iphone images back to canonical format, +// or just pass them through "as-is" +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); + +// flip the image vertically, so the first pixel in the output array is the bottom left +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); + +// as above, but only applies to images loaded on the thread that calls the function +// this function is only available if your compiler supports thread-local variables; +// calling it will fail to link if your compiler doesn't +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); + +// ZLIB client - used by PNG, available for other purposes + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); +STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + +STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + + +#ifdef __cplusplus +} +#endif + +// +// +//// end header file ///////////////////////////////////////////////////// +#endif // STBI_INCLUDE_STB_IMAGE_H + +#ifdef STB_IMAGE_IMPLEMENTATION + +#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ + || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ + || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ + || defined(STBI_ONLY_ZLIB) + #ifndef STBI_ONLY_JPEG + #define STBI_NO_JPEG + #endif + #ifndef STBI_ONLY_PNG + #define STBI_NO_PNG + #endif + #ifndef STBI_ONLY_BMP + #define STBI_NO_BMP + #endif + #ifndef STBI_ONLY_PSD + #define STBI_NO_PSD + #endif + #ifndef STBI_ONLY_TGA + #define STBI_NO_TGA + #endif + #ifndef STBI_ONLY_GIF + #define STBI_NO_GIF + #endif + #ifndef STBI_ONLY_HDR + #define STBI_NO_HDR + #endif + #ifndef STBI_ONLY_PIC + #define STBI_NO_PIC + #endif + #ifndef STBI_ONLY_PNM + #define STBI_NO_PNM + #endif +#endif + +#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) +#define STBI_NO_ZLIB +#endif + + +#include +#include // ptrdiff_t on osx +#include +#include +#include + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +#include // ldexp, pow +#endif + +#ifndef STBI_NO_STDIO +#include +#endif + +#ifndef STBI_ASSERT +#include +#define STBI_ASSERT(x) assert(x) +#endif + +#ifdef __cplusplus +#define STBI_EXTERN extern "C" +#else +#define STBI_EXTERN extern +#endif + + +#ifndef _MSC_VER + #ifdef __cplusplus + #define stbi_inline inline + #else + #define stbi_inline + #endif +#else + #define stbi_inline __forceinline +#endif + +#ifndef STBI_NO_THREAD_LOCALS + #if defined(__cplusplus) && __cplusplus >= 201103L + #define STBI_THREAD_LOCAL thread_local + #elif defined(__GNUC__) && __GNUC__ < 5 + #define STBI_THREAD_LOCAL __thread + #elif defined(_MSC_VER) + #define STBI_THREAD_LOCAL __declspec(thread) + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) + #define STBI_THREAD_LOCAL _Thread_local + #endif + + #ifndef STBI_THREAD_LOCAL + #if defined(__GNUC__) + #define STBI_THREAD_LOCAL __thread + #endif + #endif +#endif + +#if defined(_MSC_VER) || defined(__SYMBIAN32__) +typedef unsigned short stbi__uint16; +typedef signed short stbi__int16; +typedef unsigned int stbi__uint32; +typedef signed int stbi__int32; +#else +#include +typedef uint16_t stbi__uint16; +typedef int16_t stbi__int16; +typedef uint32_t stbi__uint32; +typedef int32_t stbi__int32; +#endif + +// should produce compiler error if size is wrong +typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; + +#ifdef _MSC_VER +#define STBI_NOTUSED(v) (void)(v) +#else +#define STBI_NOTUSED(v) (void)sizeof(v) +#endif + +#ifdef _MSC_VER +#define STBI_HAS_LROTL +#endif + +#ifdef STBI_HAS_LROTL + #define stbi_lrot(x,y) _lrotl(x,y) +#else + #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31))) +#endif + +#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) +// ok +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." +#endif + +#ifndef STBI_MALLOC +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p,newsz) realloc(p,newsz) +#define STBI_FREE(p) free(p) +#endif + +#ifndef STBI_REALLOC_SIZED +#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) +#endif + +// x86/x64 detection +#if defined(__x86_64__) || defined(_M_X64) +#define STBI__X64_TARGET +#elif defined(__i386) || defined(_M_IX86) +#define STBI__X86_TARGET +#endif + +#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) +// gcc doesn't support sse2 intrinsics unless you compile with -msse2, +// which in turn means it gets to use SSE2 everywhere. This is unfortunate, +// but previous attempts to provide the SSE2 functions with runtime +// detection caused numerous issues. The way architecture extensions are +// exposed in GCC/Clang is, sadly, not really suited for one-file libs. +// New behavior: if compiled with -msse2, we use SSE2 without any +// detection; if not, we don't use it at all. +#define STBI_NO_SIMD +#endif + +#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) +// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET +// +// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the +// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. +// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not +// simultaneously enabling "-mstackrealign". +// +// See https://github.com/nothings/stb/issues/81 for more information. +// +// So default to no SSE2 on 32-bit MinGW. If you've read this far and added +// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. +#define STBI_NO_SIMD +#endif + +#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) +#define STBI_SSE2 +#include + +#ifdef _MSC_VER + +#if _MSC_VER >= 1400 // not VC6 +#include // __cpuid +static int stbi__cpuid3(void) +{ + int info[4]; + __cpuid(info,1); + return info[3]; +} +#else +static int stbi__cpuid3(void) +{ + int res; + __asm { + mov eax,1 + cpuid + mov res,edx + } + return res; +} +#endif + +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + int info3 = stbi__cpuid3(); + return ((info3 >> 26) & 1) != 0; +} +#endif + +#else // assume GCC-style if not VC++ +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + // If we're even attempting to compile this on GCC/Clang, that means + // -msse2 is on, which means the compiler is allowed to use SSE2 + // instructions at will, and so are we. + return 1; +} +#endif + +#endif +#endif + +// ARM NEON +#if defined(STBI_NO_SIMD) && defined(STBI_NEON) +#undef STBI_NEON +#endif + +#ifdef STBI_NEON +#include +#ifdef _MSC_VER +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name +#else +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) +#endif +#endif + +#ifndef STBI_SIMD_ALIGN +#define STBI_SIMD_ALIGN(type, name) type name +#endif + +#ifndef STBI_MAX_DIMENSIONS +#define STBI_MAX_DIMENSIONS (1 << 24) +#endif + +/////////////////////////////////////////////// +// +// stbi__context struct and start_xxx functions + +// stbi__context structure is our basic context used by all images, so it +// contains all the IO context, plus some basic image information +typedef struct +{ + stbi__uint32 img_x, img_y; + int img_n, img_out_n; + + stbi_io_callbacks io; + void *io_user_data; + + int read_from_callbacks; + int buflen; + stbi_uc buffer_start[128]; + int callback_already_read; + + stbi_uc *img_buffer, *img_buffer_end; + stbi_uc *img_buffer_original, *img_buffer_original_end; +} stbi__context; + + +static void stbi__refill_buffer(stbi__context *s); + +// initialize a memory-decode context +static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) +{ + s->io.read = NULL; + s->read_from_callbacks = 0; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; + s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; +} + +// initialize a callback-based context +static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) +{ + s->io = *c; + s->io_user_data = user; + s->buflen = sizeof(s->buffer_start); + s->read_from_callbacks = 1; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = s->buffer_start; + stbi__refill_buffer(s); + s->img_buffer_original_end = s->img_buffer_end; +} + +#ifndef STBI_NO_STDIO + +static int stbi__stdio_read(void *user, char *data, int size) +{ + return (int) fread(data,1,size,(FILE*) user); +} + +static void stbi__stdio_skip(void *user, int n) +{ + int ch; + fseek((FILE*) user, n, SEEK_CUR); + ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ + if (ch != EOF) { + ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ + } +} + +static int stbi__stdio_eof(void *user) +{ + return feof((FILE*) user) || ferror((FILE *) user); +} + +static stbi_io_callbacks stbi__stdio_callbacks = +{ + stbi__stdio_read, + stbi__stdio_skip, + stbi__stdio_eof, +}; + +static void stbi__start_file(stbi__context *s, FILE *f) +{ + stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); +} + +//static void stop_file(stbi__context *s) { } + +#endif // !STBI_NO_STDIO + +static void stbi__rewind(stbi__context *s) +{ + // conceptually rewind SHOULD rewind to the beginning of the stream, + // but we just rewind to the beginning of the initial buffer, because + // we only use it after doing 'test', which only ever looks at at most 92 bytes + s->img_buffer = s->img_buffer_original; + s->img_buffer_end = s->img_buffer_original_end; +} + +enum +{ + STBI_ORDER_RGB, + STBI_ORDER_BGR +}; + +typedef struct +{ + int bits_per_channel; + int num_channels; + int channel_order; +} stbi__result_info; + +#ifndef STBI_NO_JPEG +static int stbi__jpeg_test(stbi__context *s); +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNG +static int stbi__png_test(stbi__context *s); +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__png_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_BMP +static int stbi__bmp_test(stbi__context *s); +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_TGA +static int stbi__tga_test(stbi__context *s); +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s); +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__psd_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_HDR +static int stbi__hdr_test(stbi__context *s); +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_test(stbi__context *s); +static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_GIF +static int stbi__gif_test(stbi__context *s); +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNM +static int stbi__pnm_test(stbi__context *s); +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__pnm_is16(stbi__context *s); +#endif + +static +#ifdef STBI_THREAD_LOCAL +STBI_THREAD_LOCAL +#endif +const char *stbi__g_failure_reason; + +STBIDEF const char *stbi_failure_reason(void) +{ + return stbi__g_failure_reason; +} + +#ifndef STBI_NO_FAILURE_STRINGS +static int stbi__err(const char *str) +{ + stbi__g_failure_reason = str; + return 0; +} +#endif + +static void *stbi__malloc(size_t size) +{ + return STBI_MALLOC(size); +} + +// stb_image uses ints pervasively, including for offset calculations. +// therefore the largest decoded image size we can support with the +// current code, even on 64-bit targets, is INT_MAX. this is not a +// significant limitation for the intended use case. +// +// we do, however, need to make sure our size calculations don't +// overflow. hence a few helper functions for size calculations that +// multiply integers together, making sure that they're non-negative +// and no overflow occurs. + +// return 1 if the sum is valid, 0 on overflow. +// negative terms are considered invalid. +static int stbi__addsizes_valid(int a, int b) +{ + if (b < 0) return 0; + // now 0 <= b <= INT_MAX, hence also + // 0 <= INT_MAX - b <= INTMAX. + // And "a + b <= INT_MAX" (which might overflow) is the + // same as a <= INT_MAX - b (no overflow) + return a <= INT_MAX - b; +} + +// returns 1 if the product is valid, 0 on overflow. +// negative factors are considered invalid. +static int stbi__mul2sizes_valid(int a, int b) +{ + if (a < 0 || b < 0) return 0; + if (b == 0) return 1; // mul-by-0 is always safe + // portable way to check for no overflows in a*b + return a <= INT_MAX/b; +} + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow +static int stbi__mad2sizes_valid(int a, int b, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); +} +#endif + +// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow +static int stbi__mad3sizes_valid(int a, int b, int c, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__addsizes_valid(a*b*c, add); +} + +// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); +} +#endif + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// mallocs with size overflow checking +static void *stbi__malloc_mad2(int a, int b, int add) +{ + if (!stbi__mad2sizes_valid(a, b, add)) return NULL; + return stbi__malloc(a*b + add); +} +#endif + +static void *stbi__malloc_mad3(int a, int b, int c, int add) +{ + if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; + return stbi__malloc(a*b*c + add); +} + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) +{ + if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; + return stbi__malloc(a*b*c*d + add); +} +#endif + +// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow. +static int stbi__addints_valid(int a, int b) +{ + if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow + if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0. + return a <= INT_MAX - b; +} + +// returns 1 if the product of two ints fits in a signed short, 0 on overflow. +static int stbi__mul2shorts_valid(int a, int b) +{ + if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow + if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid + if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN + return a >= SHRT_MIN / b; +} + +// stbi__err - error +// stbi__errpf - error returning pointer to float +// stbi__errpuc - error returning pointer to unsigned char + +#ifdef STBI_NO_FAILURE_STRINGS + #define stbi__err(x,y) 0 +#elif defined(STBI_FAILURE_USERMSG) + #define stbi__err(x,y) stbi__err(y) +#else + #define stbi__err(x,y) stbi__err(x) +#endif + +#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) +#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) + +STBIDEF void stbi_image_free(void *retval_from_stbi_load) +{ + STBI_FREE(retval_from_stbi_load); +} + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); +#endif + +#ifndef STBI_NO_HDR +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); +#endif + +static int stbi__vertically_flip_on_load_global = 0; + +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_global = flag_true_if_should_flip; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global +#else +static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; + +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_local = flag_true_if_should_flip; + stbi__vertically_flip_on_load_set = 1; +} + +#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ + ? stbi__vertically_flip_on_load_local \ + : stbi__vertically_flip_on_load_global) +#endif // STBI_THREAD_LOCAL + +static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields + ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed + ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order + ri->num_channels = 0; + + // test the formats with a very explicit header first (at least a FOURCC + // or distinctive magic number first) + #ifndef STBI_NO_PNG + if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_BMP + if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_GIF + if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PSD + if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); + #else + STBI_NOTUSED(bpc); + #endif + #ifndef STBI_NO_PIC + if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); + #endif + + // then the formats that can end up attempting to load with just 1 or 2 + // bytes matching expectations; these are prone to false positives, so + // try them later + #ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PNM + if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); + return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); + } + #endif + + #ifndef STBI_NO_TGA + // test tga last because it's a crappy test! + if (stbi__tga_test(s)) + return stbi__tga_load(s,x,y,comp,req_comp, ri); + #endif + + return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); +} + +static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi_uc *reduced; + + reduced = (stbi_uc *) stbi__malloc(img_len); + if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling + + STBI_FREE(orig); + return reduced; +} + +static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi__uint16 *enlarged; + + enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); + if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff + + STBI_FREE(orig); + return enlarged; +} + +static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) +{ + int row; + size_t bytes_per_row = (size_t)w * bytes_per_pixel; + stbi_uc temp[2048]; + stbi_uc *bytes = (stbi_uc *)image; + + for (row = 0; row < (h>>1); row++) { + stbi_uc *row0 = bytes + row*bytes_per_row; + stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; + // swap row0 with row1 + size_t bytes_left = bytes_per_row; + while (bytes_left) { + size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + memcpy(temp, row0, bytes_copy); + memcpy(row0, row1, bytes_copy); + memcpy(row1, temp, bytes_copy); + row0 += bytes_copy; + row1 += bytes_copy; + bytes_left -= bytes_copy; + } + } +} + +#ifndef STBI_NO_GIF +static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) +{ + int slice; + int slice_size = w * h * bytes_per_pixel; + + stbi_uc *bytes = (stbi_uc *)image; + for (slice = 0; slice < z; ++slice) { + stbi__vertical_flip(bytes, w, h, bytes_per_pixel); + bytes += slice_size; + } +} +#endif + +static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 8) { + result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 8; + } + + // @TODO: move stbi__convert_format to here + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); + } + + return (unsigned char *) result; +} + +static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 16) { + result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 16; + } + + // @TODO: move stbi__convert_format16 to here + // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); + } + + return (stbi__uint16 *) result; +} + +#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) +static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) +{ + if (stbi__vertically_flip_on_load && result != NULL) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); + } +} +#endif + +#ifndef STBI_NO_STDIO + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); +STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); +#endif + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) +{ + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); +} +#endif + +static FILE *stbi__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) + wchar_t wMode[64]; + wchar_t wFilename[1024]; + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) + return 0; + + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) + return 0; + +#if defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != _wfopen_s(&f, wFilename, wMode)) + f = 0; +#else + f = _wfopen(wFilename, wMode); +#endif + +#elif defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != fopen_s(&f, filename, mode)) + f=0; +#else + f = fopen(filename, mode); +#endif + return f; +} + + +STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + unsigned char *result; + if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__uint16 *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + stbi__uint16 *result; + if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file_16(f,x,y,comp,req_comp); + fclose(f); + return result; +} + + +#endif //!STBI_NO_STDIO + +STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_mem(&s,buffer,len); + + result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); + if (stbi__vertically_flip_on_load) { + stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); + } + + return result; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *data; + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + stbi__result_info ri; + float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); + if (hdr_data) + stbi__float_postprocess(hdr_data,x,y,comp,req_comp); + return hdr_data; + } + #endif + data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); + if (data) + return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); +} + +STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_STDIO +STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + float *result; + FILE *f = stbi__fopen(filename, "rb"); + if (!f) return stbi__errpf("can't fopen", "Unable to open file"); + result = stbi_loadf_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_file(&s,f); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} +#endif // !STBI_NO_STDIO + +#endif // !STBI_NO_LINEAR + +// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is +// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always +// reports false! + +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(buffer); + STBI_NOTUSED(len); + return 0; + #endif +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result=0; + if (f) { + result = stbi_is_hdr_from_file(f); + fclose(f); + } + return result; +} + +STBIDEF int stbi_is_hdr_from_file(FILE *f) +{ + #ifndef STBI_NO_HDR + long pos = ftell(f); + int res; + stbi__context s; + stbi__start_file(&s,f); + res = stbi__hdr_test(&s); + fseek(f, pos, SEEK_SET); + return res; + #else + STBI_NOTUSED(f); + return 0; + #endif +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(clbk); + STBI_NOTUSED(user); + return 0; + #endif +} + +#ifndef STBI_NO_LINEAR +static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; + +STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } +STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } +#endif + +static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; + +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } +STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } + + +////////////////////////////////////////////////////////////////////////////// +// +// Common code used by all image loaders +// + +enum +{ + STBI__SCAN_load=0, + STBI__SCAN_type, + STBI__SCAN_header +}; + +static void stbi__refill_buffer(stbi__context *s) +{ + int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); + s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); + if (n == 0) { + // at end of file, treat same as if from memory, but need to handle case + // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file + s->read_from_callbacks = 0; + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start+1; + *s->img_buffer = 0; + } else { + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + n; + } +} + +stbi_inline static stbi_uc stbi__get8(stbi__context *s) +{ + if (s->img_buffer < s->img_buffer_end) + return *s->img_buffer++; + if (s->read_from_callbacks) { + stbi__refill_buffer(s); + return *s->img_buffer++; + } + return 0; +} + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +stbi_inline static int stbi__at_eof(stbi__context *s) +{ + if (s->io.read) { + if (!(s->io.eof)(s->io_user_data)) return 0; + // if feof() is true, check if buffer = end + // special case: we've only got the special 0 character at the end + if (s->read_from_callbacks == 0) return 1; + } + + return s->img_buffer >= s->img_buffer_end; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) +// nothing +#else +static void stbi__skip(stbi__context *s, int n) +{ + if (n == 0) return; // already there! + if (n < 0) { + s->img_buffer = s->img_buffer_end; + return; + } + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + s->img_buffer = s->img_buffer_end; + (s->io.skip)(s->io_user_data, n - blen); + return; + } + } + s->img_buffer += n; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) +// nothing +#else +static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) +{ + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + int res, count; + + memcpy(buffer, s->img_buffer, blen); + + count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); + res = (count == (n-blen)); + s->img_buffer = s->img_buffer_end; + return res; + } + } + + if (s->img_buffer+n <= s->img_buffer_end) { + memcpy(buffer, s->img_buffer, n); + s->img_buffer += n; + return 1; + } else + return 0; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static int stbi__get16be(stbi__context *s) +{ + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static stbi__uint32 stbi__get32be(stbi__context *s) +{ + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); +} +#endif + +#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) +// nothing +#else +static int stbi__get16le(stbi__context *s) +{ + int z = stbi__get8(s); + return z + (stbi__get8(s) << 8); +} +#endif + +#ifndef STBI_NO_BMP +static stbi__uint32 stbi__get32le(stbi__context *s) +{ + stbi__uint32 z = stbi__get16le(s); + z += (stbi__uint32)stbi__get16le(s) << 16; + return z; +} +#endif + +#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +////////////////////////////////////////////////////////////////////////////// +// +// generic converter from built-in img_n to req_comp +// individual types do this automatically as much as possible (e.g. jpeg +// does all cases internally since it needs to colorspace convert anyway, +// and it never has alpha, so very few cases ). png can automatically +// interleave an alpha=255 channel, but falls back to this for other cases +// +// assume data buffer is malloced, so malloc a new one and free that one +// only failure mode is malloc failing + +static stbi_uc stbi__compute_y(int r, int g, int b) +{ + return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + unsigned char *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); + if (good == NULL) { + STBI_FREE(data); + return stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + unsigned char *src = data + j * x * img_n ; + unsigned char *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) +{ + return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + stbi__uint16 *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); + if (good == NULL) { + STBI_FREE(data); + return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + stbi__uint16 *src = data + j * x * img_n ; + stbi__uint16 *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) +{ + int i,k,n; + float *output; + if (!data) return NULL; + output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); + } + } + if (n < comp) { + for (i=0; i < x*y; ++i) { + output[i*comp + n] = data[i*comp + n]/255.0f; + } + } + STBI_FREE(data); + return output; +} +#endif + +#ifndef STBI_NO_HDR +#define stbi__float2int(x) ((int) (x)) +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) +{ + int i,k,n; + stbi_uc *output; + if (!data) return NULL; + output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + if (k < comp) { + float z = data[i*comp+k] * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + } + STBI_FREE(data); + return output; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// "baseline" JPEG/JFIF decoder +// +// simple implementation +// - doesn't support delayed output of y-dimension +// - simple interface (only one output format: 8-bit interleaved RGB) +// - doesn't try to recover corrupt jpegs +// - doesn't allow partial loading, loading multiple at once +// - still fast on x86 (copying globals into locals doesn't help x86) +// - allocates lots of intermediate memory (full size of all components) +// - non-interleaved case requires this anyway +// - allows good upsampling (see next) +// high-quality +// - upsampled channels are bilinearly interpolated, even across blocks +// - quality integer IDCT derived from IJG's 'slow' +// performance +// - fast huffman; reasonable integer IDCT +// - some SIMD kernels for common paths on targets with SSE2/NEON +// - uses a lot of intermediate memory, could cache poorly + +#ifndef STBI_NO_JPEG + +// huffman decoding acceleration +#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache + +typedef struct +{ + stbi_uc fast[1 << FAST_BITS]; + // weirdly, repacking this into AoS is a 10% speed loss, instead of a win + stbi__uint16 code[256]; + stbi_uc values[256]; + stbi_uc size[257]; + unsigned int maxcode[18]; + int delta[17]; // old 'firstsymbol' - old 'firstcode' +} stbi__huffman; + +typedef struct +{ + stbi__context *s; + stbi__huffman huff_dc[4]; + stbi__huffman huff_ac[4]; + stbi__uint16 dequant[4][64]; + stbi__int16 fast_ac[4][1 << FAST_BITS]; + +// sizes for components, interleaved MCUs + int img_h_max, img_v_max; + int img_mcu_x, img_mcu_y; + int img_mcu_w, img_mcu_h; + +// definition of jpeg image component + struct + { + int id; + int h,v; + int tq; + int hd,ha; + int dc_pred; + + int x,y,w2,h2; + stbi_uc *data; + void *raw_data, *raw_coeff; + stbi_uc *linebuf; + short *coeff; // progressive only + int coeff_w, coeff_h; // number of 8x8 coefficient blocks + } img_comp[4]; + + stbi__uint32 code_buffer; // jpeg entropy-coded buffer + int code_bits; // number of valid bits + unsigned char marker; // marker seen while filling entropy buffer + int nomore; // flag if we saw a marker so must stop + + int progressive; + int spec_start; + int spec_end; + int succ_high; + int succ_low; + int eob_run; + int jfif; + int app14_color_transform; // Adobe APP14 tag + int rgb; + + int scan_n, order[4]; + int restart_interval, todo; + +// kernels + void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); + void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); + stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); +} stbi__jpeg; + +static int stbi__build_huffman(stbi__huffman *h, int *count) +{ + int i,j,k=0; + unsigned int code; + // build size list for each symbol (from JPEG spec) + for (i=0; i < 16; ++i) { + for (j=0; j < count[i]; ++j) { + h->size[k++] = (stbi_uc) (i+1); + if(k >= 257) return stbi__err("bad size list","Corrupt JPEG"); + } + } + h->size[k] = 0; + + // compute actual symbols (from jpeg spec) + code = 0; + k = 0; + for(j=1; j <= 16; ++j) { + // compute delta to add to code to compute symbol id + h->delta[j] = k - code; + if (h->size[k] == j) { + while (h->size[k] == j) + h->code[k++] = (stbi__uint16) (code++); + if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); + } + // compute largest code + 1 for this size, preshifted as needed later + h->maxcode[j] = code << (16-j); + code <<= 1; + } + h->maxcode[j] = 0xffffffff; + + // build non-spec acceleration table; 255 is flag for not-accelerated + memset(h->fast, 255, 1 << FAST_BITS); + for (i=0; i < k; ++i) { + int s = h->size[i]; + if (s <= FAST_BITS) { + int c = h->code[i] << (FAST_BITS-s); + int m = 1 << (FAST_BITS-s); + for (j=0; j < m; ++j) { + h->fast[c+j] = (stbi_uc) i; + } + } + } + return 1; +} + +// build a table that decodes both magnitude and value of small ACs in +// one go. +static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) +{ + int i; + for (i=0; i < (1 << FAST_BITS); ++i) { + stbi_uc fast = h->fast[i]; + fast_ac[i] = 0; + if (fast < 255) { + int rs = h->values[fast]; + int run = (rs >> 4) & 15; + int magbits = rs & 15; + int len = h->size[fast]; + + if (magbits && len + magbits <= FAST_BITS) { + // magnitude code followed by receive_extend code + int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); + int m = 1 << (magbits - 1); + if (k < m) k += (~0U << magbits) + 1; + // if the result is small enough, we can fit it in fast_ac table + if (k >= -128 && k <= 127) + fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); + } + } + } +} + +static void stbi__grow_buffer_unsafe(stbi__jpeg *j) +{ + do { + unsigned int b = j->nomore ? 0 : stbi__get8(j->s); + if (b == 0xff) { + int c = stbi__get8(j->s); + while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes + if (c != 0) { + j->marker = (unsigned char) c; + j->nomore = 1; + return; + } + } + j->code_buffer |= b << (24 - j->code_bits); + j->code_bits += 8; + } while (j->code_bits <= 24); +} + +// (1 << n) - 1 +static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; + +// decode a jpeg huffman value from the bitstream +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) +{ + unsigned int temp; + int c,k; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + // look at the top FAST_BITS and determine what symbol ID it is, + // if the code is <= FAST_BITS + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + k = h->fast[c]; + if (k < 255) { + int s = h->size[k]; + if (s > j->code_bits) + return -1; + j->code_buffer <<= s; + j->code_bits -= s; + return h->values[k]; + } + + // naive test is to shift the code_buffer down so k bits are + // valid, then test against maxcode. To speed this up, we've + // preshifted maxcode left so that it has (16-k) 0s at the + // end; in other words, regardless of the number of bits, it + // wants to be compared against something shifted to have 16; + // that way we don't need to shift inside the loop. + temp = j->code_buffer >> 16; + for (k=FAST_BITS+1 ; ; ++k) + if (temp < h->maxcode[k]) + break; + if (k == 17) { + // error! code not found + j->code_bits -= 16; + return -1; + } + + if (k > j->code_bits) + return -1; + + // convert the huffman code to the symbol id + c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + if(c < 0 || c >= 256) // symbol id out of bounds! + return -1; + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); + + // convert the id to a symbol + j->code_bits -= k; + j->code_buffer <<= k; + return h->values[c]; +} + +// bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing + + sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative) + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k + (stbi__jbias[n] & (sgn - 1)); +} + +// get some unsigned bits +stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) +{ + unsigned int k; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k; +} + +stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) +{ + unsigned int k; + if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing + k = j->code_buffer; + j->code_buffer <<= 1; + --j->code_bits; + return k & 0x80000000; +} + +// given a value that's at position X in the zigzag stream, +// where does it appear in the 8x8 matrix coded as row-major? +static const stbi_uc stbi__jpeg_dezigzag[64+15] = +{ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + // let corrupt input sample past end + 63, 63, 63, 63, 63, 63, 63, 63, + 63, 63, 63, 63, 63, 63, 63 +}; + +// decode one 64-entry block-- +static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) +{ + int diff,dc,k; + int t; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG"); + + // 0 all the ac values now so we can do it 32-bits at a time + memset(data,0,64*sizeof(data[0])); + + diff = t ? stbi__extend_receive(j, t) : 0; + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short) (dc * dequant[0]); + + // decode AC components, see JPEG spec + k = 1; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * dequant[zig]); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (rs != 0xf0) break; // end block + k += 16; + } else { + k += r; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); + } + } + } while (k < 64); + return 1; +} + +static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) +{ + int diff,dc; + int t; + if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + if (j->succ_high == 0) { + // first scan for DC coefficient, must be first + memset(data,0,64*sizeof(data[0])); // 0 all the ac values now + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + diff = t ? stbi__extend_receive(j, t) : 0; + + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short) (dc * (1 << j->succ_low)); + } else { + // refinement scan for DC coefficient + if (stbi__jpeg_get_bit(j)) + data[0] += (short) (1 << j->succ_low); + } + return 1; +} + +// @OPTIMIZE: store non-zigzagged during the decode passes, +// and only de-zigzag when dequantizing +static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) +{ + int k; + if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->succ_high == 0) { + int shift = j->succ_low; + + if (j->eob_run) { + --j->eob_run; + return 1; + } + + k = j->spec_start; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * (1 << shift)); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r); + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + --j->eob_run; + break; + } + k += 16; + } else { + k += r; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift)); + } + } + } while (k <= j->spec_end); + } else { + // refinement scan for these AC coefficients + + short bit = (short) (1 << j->succ_low); + + if (j->eob_run) { + --j->eob_run; + for (k = j->spec_start; k <= j->spec_end; ++k) { + short *p = &data[stbi__jpeg_dezigzag[k]]; + if (*p != 0) + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } + } else { + k = j->spec_start; + do { + int r,s; + int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r) - 1; + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + r = 64; // force end of block + } else { + // r=15 s=0 should write 16 0s, so we just do + // a run of 15 0s and then write s (which is 0), + // so we don't have to do anything special here + } + } else { + if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); + // sign bit + if (stbi__jpeg_get_bit(j)) + s = bit; + else + s = -bit; + } + + // advance by r + while (k <= j->spec_end) { + short *p = &data[stbi__jpeg_dezigzag[k++]]; + if (*p != 0) { + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } else { + if (r == 0) { + *p = (short) s; + break; + } + --r; + } + } + } while (k <= j->spec_end); + } + } + return 1; +} + +// take a -128..127 value and stbi__clamp it and convert to 0..255 +stbi_inline static stbi_uc stbi__clamp(int x) +{ + // trick to use a single test to catch both cases + if ((unsigned int) x > 255) { + if (x < 0) return 0; + if (x > 255) return 255; + } + return (stbi_uc) x; +} + +#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) +#define stbi__fsh(x) ((x) * 4096) + +// derived from jidctint -- DCT_ISLOW +#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ + int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ + p2 = s2; \ + p3 = s6; \ + p1 = (p2+p3) * stbi__f2f(0.5411961f); \ + t2 = p1 + p3*stbi__f2f(-1.847759065f); \ + t3 = p1 + p2*stbi__f2f( 0.765366865f); \ + p2 = s0; \ + p3 = s4; \ + t0 = stbi__fsh(p2+p3); \ + t1 = stbi__fsh(p2-p3); \ + x0 = t0+t3; \ + x3 = t0-t3; \ + x1 = t1+t2; \ + x2 = t1-t2; \ + t0 = s7; \ + t1 = s5; \ + t2 = s3; \ + t3 = s1; \ + p3 = t0+t2; \ + p4 = t1+t3; \ + p1 = t0+t3; \ + p2 = t1+t2; \ + p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ + t0 = t0*stbi__f2f( 0.298631336f); \ + t1 = t1*stbi__f2f( 2.053119869f); \ + t2 = t2*stbi__f2f( 3.072711026f); \ + t3 = t3*stbi__f2f( 1.501321110f); \ + p1 = p5 + p1*stbi__f2f(-0.899976223f); \ + p2 = p5 + p2*stbi__f2f(-2.562915447f); \ + p3 = p3*stbi__f2f(-1.961570560f); \ + p4 = p4*stbi__f2f(-0.390180644f); \ + t3 += p1+p4; \ + t2 += p2+p3; \ + t1 += p2+p4; \ + t0 += p1+p3; + +static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) +{ + int i,val[64],*v=val; + stbi_uc *o; + short *d = data; + + // columns + for (i=0; i < 8; ++i,++d, ++v) { + // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing + if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 + && d[40]==0 && d[48]==0 && d[56]==0) { + // no shortcut 0 seconds + // (1|2|3|4|5|6|7)==0 0 seconds + // all separate -0.047 seconds + // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds + int dcterm = d[0]*4; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; + } else { + STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) + // constants scaled things up by 1<<12; let's bring them back + // down, but keep 2 extra bits of precision + x0 += 512; x1 += 512; x2 += 512; x3 += 512; + v[ 0] = (x0+t3) >> 10; + v[56] = (x0-t3) >> 10; + v[ 8] = (x1+t2) >> 10; + v[48] = (x1-t2) >> 10; + v[16] = (x2+t1) >> 10; + v[40] = (x2-t1) >> 10; + v[24] = (x3+t0) >> 10; + v[32] = (x3-t0) >> 10; + } + } + + for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { + // no fast case since the first 1D IDCT spread components out + STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) + // constants scaled things up by 1<<12, plus we had 1<<2 from first + // loop, plus horizontal and vertical each scale by sqrt(8) so together + // we've got an extra 1<<3, so 1<<17 total we need to remove. + // so we want to round that, which means adding 0.5 * 1<<17, + // aka 65536. Also, we'll end up with -128 to 127 that we want + // to encode as 0..255 by adding 128, so we'll add that before the shift + x0 += 65536 + (128<<17); + x1 += 65536 + (128<<17); + x2 += 65536 + (128<<17); + x3 += 65536 + (128<<17); + // tried computing the shifts into temps, or'ing the temps to see + // if any were out of range, but that was slower + o[0] = stbi__clamp((x0+t3) >> 17); + o[7] = stbi__clamp((x0-t3) >> 17); + o[1] = stbi__clamp((x1+t2) >> 17); + o[6] = stbi__clamp((x1-t2) >> 17); + o[2] = stbi__clamp((x2+t1) >> 17); + o[5] = stbi__clamp((x2-t1) >> 17); + o[3] = stbi__clamp((x3+t0) >> 17); + o[4] = stbi__clamp((x3-t0) >> 17); + } +} + +#ifdef STBI_SSE2 +// sse2 integer IDCT. not the fastest possible implementation but it +// produces bit-identical results to the generic C version so it's +// fully "transparent". +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + // This is constructed to match our regular (generic) integer IDCT exactly. + __m128i row0, row1, row2, row3, row4, row5, row6, row7; + __m128i tmp; + + // dot product constant: even elems=x, odd elems=y + #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) + + // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) + // out(1) = c1[even]*x + c1[odd]*y + #define dct_rot(out0,out1, x,y,c0,c1) \ + __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ + __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ + __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ + __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ + __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ + __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) + + // out = in << 12 (in 16-bit, out 32-bit) + #define dct_widen(out, in) \ + __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ + __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) + + // wide add + #define dct_wadd(out, a, b) \ + __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_add_epi32(a##_h, b##_h) + + // wide sub + #define dct_wsub(out, a, b) \ + __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) + + // butterfly a/b, add bias, then shift by "s" and pack + #define dct_bfly32o(out0, out1, a,b,bias,s) \ + { \ + __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ + __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ + dct_wadd(sum, abiased, b); \ + dct_wsub(dif, abiased, b); \ + out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ + out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ + } + + // 8-bit interleave step (for transposes) + #define dct_interleave8(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi8(a, b); \ + b = _mm_unpackhi_epi8(tmp, b) + + // 16-bit interleave step (for transposes) + #define dct_interleave16(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi16(a, b); \ + b = _mm_unpackhi_epi16(tmp, b) + + #define dct_pass(bias,shift) \ + { \ + /* even part */ \ + dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ + __m128i sum04 = _mm_add_epi16(row0, row4); \ + __m128i dif04 = _mm_sub_epi16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ + dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ + __m128i sum17 = _mm_add_epi16(row1, row7); \ + __m128i sum35 = _mm_add_epi16(row3, row5); \ + dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ + dct_wadd(x4, y0o, y4o); \ + dct_wadd(x5, y1o, y5o); \ + dct_wadd(x6, y2o, y5o); \ + dct_wadd(x7, y3o, y4o); \ + dct_bfly32o(row0,row7, x0,x7,bias,shift); \ + dct_bfly32o(row1,row6, x1,x6,bias,shift); \ + dct_bfly32o(row2,row5, x2,x5,bias,shift); \ + dct_bfly32o(row3,row4, x3,x4,bias,shift); \ + } + + __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); + __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); + __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); + __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); + __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); + __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); + __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); + __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); + + // rounding biases in column/row passes, see stbi__idct_block for explanation. + __m128i bias_0 = _mm_set1_epi32(512); + __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); + + // load + row0 = _mm_load_si128((const __m128i *) (data + 0*8)); + row1 = _mm_load_si128((const __m128i *) (data + 1*8)); + row2 = _mm_load_si128((const __m128i *) (data + 2*8)); + row3 = _mm_load_si128((const __m128i *) (data + 3*8)); + row4 = _mm_load_si128((const __m128i *) (data + 4*8)); + row5 = _mm_load_si128((const __m128i *) (data + 5*8)); + row6 = _mm_load_si128((const __m128i *) (data + 6*8)); + row7 = _mm_load_si128((const __m128i *) (data + 7*8)); + + // column pass + dct_pass(bias_0, 10); + + { + // 16bit 8x8 transpose pass 1 + dct_interleave16(row0, row4); + dct_interleave16(row1, row5); + dct_interleave16(row2, row6); + dct_interleave16(row3, row7); + + // transpose pass 2 + dct_interleave16(row0, row2); + dct_interleave16(row1, row3); + dct_interleave16(row4, row6); + dct_interleave16(row5, row7); + + // transpose pass 3 + dct_interleave16(row0, row1); + dct_interleave16(row2, row3); + dct_interleave16(row4, row5); + dct_interleave16(row6, row7); + } + + // row pass + dct_pass(bias_1, 17); + + { + // pack + __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 + __m128i p1 = _mm_packus_epi16(row2, row3); + __m128i p2 = _mm_packus_epi16(row4, row5); + __m128i p3 = _mm_packus_epi16(row6, row7); + + // 8bit 8x8 transpose pass 1 + dct_interleave8(p0, p2); // a0e0a1e1... + dct_interleave8(p1, p3); // c0g0c1g1... + + // transpose pass 2 + dct_interleave8(p0, p1); // a0c0e0g0... + dct_interleave8(p2, p3); // b0d0f0h0... + + // transpose pass 3 + dct_interleave8(p0, p2); // a0b0c0d0... + dct_interleave8(p1, p3); // a4b4c4d4... + + // store + _mm_storel_epi64((__m128i *) out, p0); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p2); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p1); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p3); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); + } + +#undef dct_const +#undef dct_rot +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_interleave8 +#undef dct_interleave16 +#undef dct_pass +} + +#endif // STBI_SSE2 + +#ifdef STBI_NEON + +// NEON integer IDCT. should produce bit-identical +// results to the generic C version. +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; + + int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); + int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); + int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); + int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); + int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); + int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); + int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); + int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); + int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); + int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); + int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); + int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); + +#define dct_long_mul(out, inq, coeff) \ + int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) + +#define dct_long_mac(out, acc, inq, coeff) \ + int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) + +#define dct_widen(out, inq) \ + int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ + int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) + +// wide add +#define dct_wadd(out, a, b) \ + int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vaddq_s32(a##_h, b##_h) + +// wide sub +#define dct_wsub(out, a, b) \ + int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vsubq_s32(a##_h, b##_h) + +// butterfly a/b, then shift using "shiftop" by "s" and pack +#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ + { \ + dct_wadd(sum, a, b); \ + dct_wsub(dif, a, b); \ + out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ + out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ + } + +#define dct_pass(shiftop, shift) \ + { \ + /* even part */ \ + int16x8_t sum26 = vaddq_s16(row2, row6); \ + dct_long_mul(p1e, sum26, rot0_0); \ + dct_long_mac(t2e, p1e, row6, rot0_1); \ + dct_long_mac(t3e, p1e, row2, rot0_2); \ + int16x8_t sum04 = vaddq_s16(row0, row4); \ + int16x8_t dif04 = vsubq_s16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + int16x8_t sum15 = vaddq_s16(row1, row5); \ + int16x8_t sum17 = vaddq_s16(row1, row7); \ + int16x8_t sum35 = vaddq_s16(row3, row5); \ + int16x8_t sum37 = vaddq_s16(row3, row7); \ + int16x8_t sumodd = vaddq_s16(sum17, sum35); \ + dct_long_mul(p5o, sumodd, rot1_0); \ + dct_long_mac(p1o, p5o, sum17, rot1_1); \ + dct_long_mac(p2o, p5o, sum35, rot1_2); \ + dct_long_mul(p3o, sum37, rot2_0); \ + dct_long_mul(p4o, sum15, rot2_1); \ + dct_wadd(sump13o, p1o, p3o); \ + dct_wadd(sump24o, p2o, p4o); \ + dct_wadd(sump23o, p2o, p3o); \ + dct_wadd(sump14o, p1o, p4o); \ + dct_long_mac(x4, sump13o, row7, rot3_0); \ + dct_long_mac(x5, sump24o, row5, rot3_1); \ + dct_long_mac(x6, sump23o, row3, rot3_2); \ + dct_long_mac(x7, sump14o, row1, rot3_3); \ + dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ + dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ + dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ + dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ + } + + // load + row0 = vld1q_s16(data + 0*8); + row1 = vld1q_s16(data + 1*8); + row2 = vld1q_s16(data + 2*8); + row3 = vld1q_s16(data + 3*8); + row4 = vld1q_s16(data + 4*8); + row5 = vld1q_s16(data + 5*8); + row6 = vld1q_s16(data + 6*8); + row7 = vld1q_s16(data + 7*8); + + // add DC bias + row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); + + // column pass + dct_pass(vrshrn_n_s32, 10); + + // 16bit 8x8 transpose + { +// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. +// whether compilers actually get this is another story, sadly. +#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } +#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } + + // pass 1 + dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 + dct_trn16(row2, row3); + dct_trn16(row4, row5); + dct_trn16(row6, row7); + + // pass 2 + dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 + dct_trn32(row1, row3); + dct_trn32(row4, row6); + dct_trn32(row5, row7); + + // pass 3 + dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 + dct_trn64(row1, row5); + dct_trn64(row2, row6); + dct_trn64(row3, row7); + +#undef dct_trn16 +#undef dct_trn32 +#undef dct_trn64 + } + + // row pass + // vrshrn_n_s32 only supports shifts up to 16, we need + // 17. so do a non-rounding shift of 16 first then follow + // up with a rounding shift by 1. + dct_pass(vshrn_n_s32, 16); + + { + // pack and round + uint8x8_t p0 = vqrshrun_n_s16(row0, 1); + uint8x8_t p1 = vqrshrun_n_s16(row1, 1); + uint8x8_t p2 = vqrshrun_n_s16(row2, 1); + uint8x8_t p3 = vqrshrun_n_s16(row3, 1); + uint8x8_t p4 = vqrshrun_n_s16(row4, 1); + uint8x8_t p5 = vqrshrun_n_s16(row5, 1); + uint8x8_t p6 = vqrshrun_n_s16(row6, 1); + uint8x8_t p7 = vqrshrun_n_s16(row7, 1); + + // again, these can translate into one instruction, but often don't. +#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } +#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } + + // sadly can't use interleaved stores here since we only write + // 8 bytes to each scan line! + + // 8x8 8-bit transpose pass 1 + dct_trn8_8(p0, p1); + dct_trn8_8(p2, p3); + dct_trn8_8(p4, p5); + dct_trn8_8(p6, p7); + + // pass 2 + dct_trn8_16(p0, p2); + dct_trn8_16(p1, p3); + dct_trn8_16(p4, p6); + dct_trn8_16(p5, p7); + + // pass 3 + dct_trn8_32(p0, p4); + dct_trn8_32(p1, p5); + dct_trn8_32(p2, p6); + dct_trn8_32(p3, p7); + + // store + vst1_u8(out, p0); out += out_stride; + vst1_u8(out, p1); out += out_stride; + vst1_u8(out, p2); out += out_stride; + vst1_u8(out, p3); out += out_stride; + vst1_u8(out, p4); out += out_stride; + vst1_u8(out, p5); out += out_stride; + vst1_u8(out, p6); out += out_stride; + vst1_u8(out, p7); + +#undef dct_trn8_8 +#undef dct_trn8_16 +#undef dct_trn8_32 + } + +#undef dct_long_mul +#undef dct_long_mac +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_pass +} + +#endif // STBI_NEON + +#define STBI__MARKER_none 0xff +// if there's a pending marker from the entropy stream, return that +// otherwise, fetch from the stream and get a marker. if there's no +// marker, return 0xff, which is never a valid marker value +static stbi_uc stbi__get_marker(stbi__jpeg *j) +{ + stbi_uc x; + if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } + x = stbi__get8(j->s); + if (x != 0xff) return STBI__MARKER_none; + while (x == 0xff) + x = stbi__get8(j->s); // consume repeated 0xff fill bytes + return x; +} + +// in each scan, we'll have scan_n components, and the order +// of the components is specified by order[] +#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) + +// after a restart interval, stbi__jpeg_reset the entropy decoder and +// the dc prediction +static void stbi__jpeg_reset(stbi__jpeg *j) +{ + j->code_bits = 0; + j->code_buffer = 0; + j->nomore = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; + j->marker = STBI__MARKER_none; + j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; + j->eob_run = 0; + // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, + // since we don't even allow 1<<30 pixels +} + +static int stbi__parse_entropy_coded_data(stbi__jpeg *z) +{ + stbi__jpeg_reset(z); + if (!z->progressive) { + if (z->scan_n == 1) { + int i,j; + STBI_SIMD_ALIGN(short, data[64]); + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get corrupt data + // rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + STBI_SIMD_ALIGN(short, data[64]); + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x)*8; + int y2 = (j*z->img_comp[n].v + y)*8; + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } else { + if (z->scan_n == 1) { + int i,j; + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + if (z->spec_start == 0) { + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } else { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) + return 0; + } + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x); + int y2 = (j*z->img_comp[n].v + y); + short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } +} + +static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) +{ + int i; + for (i=0; i < 64; ++i) + data[i] *= dequant[i]; +} + +static void stbi__jpeg_finish(stbi__jpeg *z) +{ + if (z->progressive) { + // dequantize and idct the data + int i,j,n; + for (n=0; n < z->s->img_n; ++n) { + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + } + } + } + } +} + +static int stbi__process_marker(stbi__jpeg *z, int m) +{ + int L; + switch (m) { + case STBI__MARKER_none: // no marker found + return stbi__err("expected marker","Corrupt JPEG"); + + case 0xDD: // DRI - specify restart interval + if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); + z->restart_interval = stbi__get16be(z->s); + return 1; + + case 0xDB: // DQT - define quantization table + L = stbi__get16be(z->s)-2; + while (L > 0) { + int q = stbi__get8(z->s); + int p = q >> 4, sixteen = (p != 0); + int t = q & 15,i; + if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); + if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); + + for (i=0; i < 64; ++i) + z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); + L -= (sixteen ? 129 : 65); + } + return L==0; + + case 0xC4: // DHT - define huffman table + L = stbi__get16be(z->s)-2; + while (L > 0) { + stbi_uc *v; + int sizes[16],i,n=0; + int q = stbi__get8(z->s); + int tc = q >> 4; + int th = q & 15; + if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); + for (i=0; i < 16; ++i) { + sizes[i] = stbi__get8(z->s); + n += sizes[i]; + } + if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values! + L -= 17; + if (tc == 0) { + if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; + v = z->huff_dc[th].values; + } else { + if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; + v = z->huff_ac[th].values; + } + for (i=0; i < n; ++i) + v[i] = stbi__get8(z->s); + if (tc != 0) + stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); + L -= n; + } + return L==0; + } + + // check for comment block or APP blocks + if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { + L = stbi__get16be(z->s); + if (L < 2) { + if (m == 0xFE) + return stbi__err("bad COM len","Corrupt JPEG"); + else + return stbi__err("bad APP len","Corrupt JPEG"); + } + L -= 2; + + if (m == 0xE0 && L >= 5) { // JFIF APP0 segment + static const unsigned char tag[5] = {'J','F','I','F','\0'}; + int ok = 1; + int i; + for (i=0; i < 5; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 5; + if (ok) + z->jfif = 1; + } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment + static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; + int ok = 1; + int i; + for (i=0; i < 6; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 6; + if (ok) { + stbi__get8(z->s); // version + stbi__get16be(z->s); // flags0 + stbi__get16be(z->s); // flags1 + z->app14_color_transform = stbi__get8(z->s); // color transform + L -= 6; + } + } + + stbi__skip(z->s, L); + return 1; + } + + return stbi__err("unknown marker","Corrupt JPEG"); +} + +// after we see SOS +static int stbi__process_scan_header(stbi__jpeg *z) +{ + int i; + int Ls = stbi__get16be(z->s); + z->scan_n = stbi__get8(z->s); + if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); + if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); + for (i=0; i < z->scan_n; ++i) { + int id = stbi__get8(z->s), which; + int q = stbi__get8(z->s); + for (which = 0; which < z->s->img_n; ++which) + if (z->img_comp[which].id == id) + break; + if (which == z->s->img_n) return 0; // no match + z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); + z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); + z->order[i] = which; + } + + { + int aa; + z->spec_start = stbi__get8(z->s); + z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 + aa = stbi__get8(z->s); + z->succ_high = (aa >> 4); + z->succ_low = (aa & 15); + if (z->progressive) { + if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) + return stbi__err("bad SOS", "Corrupt JPEG"); + } else { + if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); + if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); + z->spec_end = 63; + } + } + + return 1; +} + +static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) +{ + int i; + for (i=0; i < ncomp; ++i) { + if (z->img_comp[i].raw_data) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + z->img_comp[i].data = NULL; + } + if (z->img_comp[i].raw_coeff) { + STBI_FREE(z->img_comp[i].raw_coeff); + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].coeff = 0; + } + if (z->img_comp[i].linebuf) { + STBI_FREE(z->img_comp[i].linebuf); + z->img_comp[i].linebuf = NULL; + } + } + return why; +} + +static int stbi__process_frame_header(stbi__jpeg *z, int scan) +{ + stbi__context *s = z->s; + int Lf,p,i,q, h_max=1,v_max=1,c; + Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG + p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline + s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG + s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + c = stbi__get8(s); + if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); + s->img_n = c; + for (i=0; i < c; ++i) { + z->img_comp[i].data = NULL; + z->img_comp[i].linebuf = NULL; + } + + if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); + + z->rgb = 0; + for (i=0; i < s->img_n; ++i) { + static const unsigned char rgb[3] = { 'R', 'G', 'B' }; + z->img_comp[i].id = stbi__get8(s); + if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) + ++z->rgb; + q = stbi__get8(s); + z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); + z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); + z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); + } + + if (scan != STBI__SCAN_load) return 1; + + if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); + + for (i=0; i < s->img_n; ++i) { + if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; + if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; + } + + // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios + // and I've never seen a non-corrupted JPEG file actually use them + for (i=0; i < s->img_n; ++i) { + if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG"); + if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG"); + } + + // compute interleaved mcu info + z->img_h_max = h_max; + z->img_v_max = v_max; + z->img_mcu_w = h_max * 8; + z->img_mcu_h = v_max * 8; + // these sizes can't be more than 17 bits + z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; + z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; + + for (i=0; i < s->img_n; ++i) { + // number of effective pixels (e.g. for non-interleaved MCU) + z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; + z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; + // to simplify generation, we'll allocate enough memory to decode + // the bogus oversized data from using interleaved MCUs and their + // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't + // discard the extra data until colorspace conversion + // + // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) + // so these muls can't overflow with 32-bit ints (which we require) + z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; + z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].linebuf = NULL; + z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + if (z->img_comp[i].raw_data == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + // align blocks for idct using mmx/sse + z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); + if (z->progressive) { + // w2, h2 are multiples of 8 (see above) + z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; + z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; + z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + if (z->img_comp[i].raw_coeff == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); + } + } + + return 1; +} + +// use comparisons since in some cases we handle more than one case (e.g. SOF) +#define stbi__DNL(x) ((x) == 0xdc) +#define stbi__SOI(x) ((x) == 0xd8) +#define stbi__EOI(x) ((x) == 0xd9) +#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) +#define stbi__SOS(x) ((x) == 0xda) + +#define stbi__SOF_progressive(x) ((x) == 0xc2) + +static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) +{ + int m; + z->jfif = 0; + z->app14_color_transform = -1; // valid values are 0,1,2 + z->marker = STBI__MARKER_none; // initialize cached marker to empty + m = stbi__get_marker(z); + if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); + if (scan == STBI__SCAN_type) return 1; + m = stbi__get_marker(z); + while (!stbi__SOF(m)) { + if (!stbi__process_marker(z,m)) return 0; + m = stbi__get_marker(z); + while (m == STBI__MARKER_none) { + // some files have extra padding after their blocks, so ok, we'll scan + if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); + m = stbi__get_marker(z); + } + } + z->progressive = stbi__SOF_progressive(m); + if (!stbi__process_frame_header(z, scan)) return 0; + return 1; +} + +static stbi_uc stbi__skip_jpeg_junk_at_end(stbi__jpeg *j) +{ + // some JPEGs have junk at end, skip over it but if we find what looks + // like a valid marker, resume there + while (!stbi__at_eof(j->s)) { + stbi_uc x = stbi__get8(j->s); + while (x == 0xff) { // might be a marker + if (stbi__at_eof(j->s)) return STBI__MARKER_none; + x = stbi__get8(j->s); + if (x != 0x00 && x != 0xff) { + // not a stuffed zero or lead-in to another marker, looks + // like an actual marker, return it + return x; + } + // stuffed zero has x=0 now which ends the loop, meaning we go + // back to regular scan loop. + // repeated 0xff keeps trying to read the next byte of the marker. + } + } + return STBI__MARKER_none; +} + +// decode image to YCbCr format +static int stbi__decode_jpeg_image(stbi__jpeg *j) +{ + int m; + for (m = 0; m < 4; m++) { + j->img_comp[m].raw_data = NULL; + j->img_comp[m].raw_coeff = NULL; + } + j->restart_interval = 0; + if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; + m = stbi__get_marker(j); + while (!stbi__EOI(m)) { + if (stbi__SOS(m)) { + if (!stbi__process_scan_header(j)) return 0; + if (!stbi__parse_entropy_coded_data(j)) return 0; + if (j->marker == STBI__MARKER_none ) { + j->marker = stbi__skip_jpeg_junk_at_end(j); + // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 + } + m = stbi__get_marker(j); + if (STBI__RESTART(m)) + m = stbi__get_marker(j); + } else if (stbi__DNL(m)) { + int Ld = stbi__get16be(j->s); + stbi__uint32 NL = stbi__get16be(j->s); + if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); + m = stbi__get_marker(j); + } else { + if (!stbi__process_marker(j, m)) return 1; + m = stbi__get_marker(j); + } + } + if (j->progressive) + stbi__jpeg_finish(j); + return 1; +} + +// static jfif-centered resampling (across block boundaries) + +typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, + int w, int hs); + +#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) + +static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + STBI_NOTUSED(out); + STBI_NOTUSED(in_far); + STBI_NOTUSED(w); + STBI_NOTUSED(hs); + return in_near; +} + +static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples vertically for every one in input + int i; + STBI_NOTUSED(hs); + for (i=0; i < w; ++i) + out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); + return out; +} + +static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples horizontally for every one in input + int i; + stbi_uc *input = in_near; + + if (w == 1) { + // if only one sample, can't do any interpolation + out[0] = out[1] = input[0]; + return out; + } + + out[0] = input[0]; + out[1] = stbi__div4(input[0]*3 + input[1] + 2); + for (i=1; i < w-1; ++i) { + int n = 3*input[i]+2; + out[i*2+0] = stbi__div4(n+input[i-1]); + out[i*2+1] = stbi__div4(n+input[i+1]); + } + out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); + out[i*2+1] = input[w-1]; + + STBI_NOTUSED(in_far); + STBI_NOTUSED(hs); + + return out; +} + +#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) + +static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i,t0,t1; + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + out[0] = stbi__div4(t1+2); + for (i=1; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i=0,t0,t1; + + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + // process groups of 8 pixels for as long as we can. + // note we can't handle the last pixel in a row in this loop + // because we need to handle the filter boundary conditions. + for (; i < ((w-1) & ~7); i += 8) { +#if defined(STBI_SSE2) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + __m128i zero = _mm_setzero_si128(); + __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); + __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); + __m128i farw = _mm_unpacklo_epi8(farb, zero); + __m128i nearw = _mm_unpacklo_epi8(nearb, zero); + __m128i diff = _mm_sub_epi16(farw, nearw); + __m128i nears = _mm_slli_epi16(nearw, 2); + __m128i curr = _mm_add_epi16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + __m128i prv0 = _mm_slli_si128(curr, 2); + __m128i nxt0 = _mm_srli_si128(curr, 2); + __m128i prev = _mm_insert_epi16(prv0, t1, 0); + __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + __m128i bias = _mm_set1_epi16(8); + __m128i curs = _mm_slli_epi16(curr, 2); + __m128i prvd = _mm_sub_epi16(prev, curr); + __m128i nxtd = _mm_sub_epi16(next, curr); + __m128i curb = _mm_add_epi16(curs, bias); + __m128i even = _mm_add_epi16(prvd, curb); + __m128i odd = _mm_add_epi16(nxtd, curb); + + // interleave even and odd pixels, then undo scaling. + __m128i int0 = _mm_unpacklo_epi16(even, odd); + __m128i int1 = _mm_unpackhi_epi16(even, odd); + __m128i de0 = _mm_srli_epi16(int0, 4); + __m128i de1 = _mm_srli_epi16(int1, 4); + + // pack and write output + __m128i outv = _mm_packus_epi16(de0, de1); + _mm_storeu_si128((__m128i *) (out + i*2), outv); +#elif defined(STBI_NEON) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + uint8x8_t farb = vld1_u8(in_far + i); + uint8x8_t nearb = vld1_u8(in_near + i); + int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); + int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); + int16x8_t curr = vaddq_s16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + int16x8_t prv0 = vextq_s16(curr, curr, 7); + int16x8_t nxt0 = vextq_s16(curr, curr, 1); + int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); + int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + int16x8_t curs = vshlq_n_s16(curr, 2); + int16x8_t prvd = vsubq_s16(prev, curr); + int16x8_t nxtd = vsubq_s16(next, curr); + int16x8_t even = vaddq_s16(curs, prvd); + int16x8_t odd = vaddq_s16(curs, nxtd); + + // undo scaling and round, then store with even/odd phases interleaved + uint8x8x2_t o; + o.val[0] = vqrshrun_n_s16(even, 4); + o.val[1] = vqrshrun_n_s16(odd, 4); + vst2_u8(out + i*2, o); +#endif + + // "previous" value for next iter + t1 = 3*in_near[i+7] + in_far[i+7]; + } + + t0 = t1; + t1 = 3*in_near[i] + in_far[i]; + out[i*2] = stbi__div16(3*t1 + t0 + 8); + + for (++i; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} +#endif + +static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // resample with nearest-neighbor + int i,j; + STBI_NOTUSED(in_far); + for (i=0; i < w; ++i) + for (j=0; j < hs; ++j) + out[i*hs+j] = in_near[i]; + return out; +} + +// this is a reduced-precision calculation of YCbCr-to-RGB introduced +// to make sure the code produces the same results in both SIMD and scalar +#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) +static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) +{ + int i; + for (i=0; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) +{ + int i = 0; + +#ifdef STBI_SSE2 + // step == 3 is pretty ugly on the final interleave, and i'm not convinced + // it's useful in practice (you wouldn't use it for textures, for example). + // so just accelerate step == 4 case. + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + __m128i signflip = _mm_set1_epi8(-0x80); + __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); + __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); + __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); + __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); + __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); + __m128i xw = _mm_set1_epi16(255); // alpha channel + + for (; i+7 < count; i += 8) { + // load + __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); + __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); + __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); + __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 + __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 + + // unpack to short (and left-shift cr, cb by 8) + __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); + __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); + __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); + + // color transform + __m128i yws = _mm_srli_epi16(yw, 4); + __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); + __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); + __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); + __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); + __m128i rws = _mm_add_epi16(cr0, yws); + __m128i gwt = _mm_add_epi16(cb0, yws); + __m128i bws = _mm_add_epi16(yws, cb1); + __m128i gws = _mm_add_epi16(gwt, cr1); + + // descale + __m128i rw = _mm_srai_epi16(rws, 4); + __m128i bw = _mm_srai_epi16(bws, 4); + __m128i gw = _mm_srai_epi16(gws, 4); + + // back to byte, set up for transpose + __m128i brb = _mm_packus_epi16(rw, bw); + __m128i gxb = _mm_packus_epi16(gw, xw); + + // transpose to interleave channels + __m128i t0 = _mm_unpacklo_epi8(brb, gxb); + __m128i t1 = _mm_unpackhi_epi8(brb, gxb); + __m128i o0 = _mm_unpacklo_epi16(t0, t1); + __m128i o1 = _mm_unpackhi_epi16(t0, t1); + + // store + _mm_storeu_si128((__m128i *) (out + 0), o0); + _mm_storeu_si128((__m128i *) (out + 16), o1); + out += 32; + } + } +#endif + +#ifdef STBI_NEON + // in this version, step=3 support would be easy to add. but is there demand? + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + uint8x8_t signflip = vdup_n_u8(0x80); + int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); + int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); + int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); + int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); + + for (; i+7 < count; i += 8) { + // load + uint8x8_t y_bytes = vld1_u8(y + i); + uint8x8_t cr_bytes = vld1_u8(pcr + i); + uint8x8_t cb_bytes = vld1_u8(pcb + i); + int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); + int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); + + // expand to s16 + int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); + int16x8_t crw = vshll_n_s8(cr_biased, 7); + int16x8_t cbw = vshll_n_s8(cb_biased, 7); + + // color transform + int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); + int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); + int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); + int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); + int16x8_t rws = vaddq_s16(yws, cr0); + int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); + int16x8_t bws = vaddq_s16(yws, cb1); + + // undo scaling, round, convert to byte + uint8x8x4_t o; + o.val[0] = vqrshrun_n_s16(rws, 4); + o.val[1] = vqrshrun_n_s16(gws, 4); + o.val[2] = vqrshrun_n_s16(bws, 4); + o.val[3] = vdup_n_u8(255); + + // store, interleaving r/g/b/a + vst4_u8(out, o); + out += 8*4; + } + } +#endif + + for (; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} +#endif + +// set up the kernels +static void stbi__setup_jpeg(stbi__jpeg *j) +{ + j->idct_block_kernel = stbi__idct_block; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; + +#ifdef STBI_SSE2 + if (stbi__sse2_available()) { + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; + } +#endif + +#ifdef STBI_NEON + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; +#endif +} + +// clean up the temporary component buffers +static void stbi__cleanup_jpeg(stbi__jpeg *j) +{ + stbi__free_jpeg_components(j, j->s->img_n, 0); +} + +typedef struct +{ + resample_row_func resample; + stbi_uc *line0,*line1; + int hs,vs; // expansion factor in each axis + int w_lores; // horizontal pixels pre-expansion + int ystep; // how far through vertical expansion we are + int ypos; // which pre-expansion row we're on +} stbi__resample; + +// fast 0..255 * 0..255 => 0..255 rounded multiplication +static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) +{ + unsigned int t = x*y + 128; + return (stbi_uc) ((t + (t >>8)) >> 8); +} + +static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) +{ + int n, decode_n, is_rgb; + z->s->img_n = 0; // make stbi__cleanup_jpeg safe + + // validate req_comp + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + + // load a jpeg image from whichever source, but leave in YCbCr format + if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } + + // determine actual number of components to generate + n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; + + is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + + if (z->s->img_n == 3 && n < 3 && !is_rgb) + decode_n = 1; + else + decode_n = z->s->img_n; + + // nothing to do if no components requested; check this now to avoid + // accessing uninitialized coutput[0] later + if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; } + + // resample and color-convert + { + int k; + unsigned int i,j; + stbi_uc *output; + stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; + + stbi__resample res_comp[4]; + + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + + // allocate line buffer big enough for upsampling off the edges + // with upsample factor of 4 + z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); + if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + r->hs = z->img_h_max / z->img_comp[k].h; + r->vs = z->img_v_max / z->img_comp[k].v; + r->ystep = r->vs >> 1; + r->w_lores = (z->s->img_x + r->hs-1) / r->hs; + r->ypos = 0; + r->line0 = r->line1 = z->img_comp[k].data; + + if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; + else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; + else r->resample = stbi__resample_row_generic; + } + + // can't error after this so, this is safe + output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); + if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + // now go ahead and resample + for (j=0; j < z->s->img_y; ++j) { + stbi_uc *out = output + n * z->s->img_x * j; + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + int y_bot = r->ystep >= (r->vs >> 1); + coutput[k] = r->resample(z->img_comp[k].linebuf, + y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, + r->w_lores, r->hs); + if (++r->ystep >= r->vs) { + r->ystep = 0; + r->line0 = r->line1; + if (++r->ypos < z->img_comp[k].y) + r->line1 += z->img_comp[k].w2; + } + } + if (n >= 3) { + stbi_uc *y = coutput[0]; + if (z->s->img_n == 3) { + if (is_rgb) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = y[i]; + out[1] = coutput[1][i]; + out[2] = coutput[2][i]; + out[3] = 255; + out += n; + } + } else { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else if (z->s->img_n == 4) { + if (z->app14_color_transform == 0) { // CMYK + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], m); + out[1] = stbi__blinn_8x8(coutput[1][i], m); + out[2] = stbi__blinn_8x8(coutput[2][i], m); + out[3] = 255; + out += n; + } + } else if (z->app14_color_transform == 2) { // YCCK + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], m); + out[1] = stbi__blinn_8x8(255 - out[1], m); + out[2] = stbi__blinn_8x8(255 - out[2], m); + out += n; + } + } else { // YCbCr + alpha? Ignore the fourth channel for now + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else + for (i=0; i < z->s->img_x; ++i) { + out[0] = out[1] = out[2] = y[i]; + out[3] = 255; // not used if n==3 + out += n; + } + } else { + if (is_rgb) { + if (n == 1) + for (i=0; i < z->s->img_x; ++i) + *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + else { + for (i=0; i < z->s->img_x; ++i, out += 2) { + out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + out[1] = 255; + } + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + out[0] = stbi__compute_y(r, g, b); + out[1] = 255; + out += n; + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); + out[1] = 255; + out += n; + } + } else { + stbi_uc *y = coutput[0]; + if (n == 1) + for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } + } + } + } + stbi__cleanup_jpeg(z); + *out_x = z->s->img_x; + *out_y = z->s->img_y; + if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output + return output; + } +} + +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + unsigned char* result; + stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__errpuc("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + STBI_NOTUSED(ri); + j->s = s; + stbi__setup_jpeg(j); + result = load_jpeg_image(j, x,y,comp,req_comp); + STBI_FREE(j); + return result; +} + +static int stbi__jpeg_test(stbi__context *s) +{ + int r; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + stbi__setup_jpeg(j); + r = stbi__decode_jpeg_header(j, STBI__SCAN_type); + stbi__rewind(s); + STBI_FREE(j); + return r; +} + +static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) +{ + if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { + stbi__rewind( j->s ); + return 0; + } + if (x) *x = j->s->img_x; + if (y) *y = j->s->img_y; + if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; + return 1; +} + +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) +{ + int result; + stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + result = stbi__jpeg_info_raw(j, x, y, comp); + STBI_FREE(j); + return result; +} +#endif + +// public domain zlib decode v0.2 Sean Barrett 2006-11-18 +// simple implementation +// - all input must be provided in an upfront buffer +// - all output is written to a single output buffer (can malloc/realloc) +// performance +// - fast huffman + +#ifndef STBI_NO_ZLIB + +// fast-way is faster to check than jpeg huffman, but slow way is slower +#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables +#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) +#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet + +// zlib-style huffman encoding +// (jpegs packs from left, zlib from right, so can't share code) +typedef struct +{ + stbi__uint16 fast[1 << STBI__ZFAST_BITS]; + stbi__uint16 firstcode[16]; + int maxcode[17]; + stbi__uint16 firstsymbol[16]; + stbi_uc size[STBI__ZNSYMS]; + stbi__uint16 value[STBI__ZNSYMS]; +} stbi__zhuffman; + +stbi_inline static int stbi__bitreverse16(int n) +{ + n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); + n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); + n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); + n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); + return n; +} + +stbi_inline static int stbi__bit_reverse(int v, int bits) +{ + STBI_ASSERT(bits <= 16); + // to bit reverse n bits, reverse 16 and shift + // e.g. 11 bits, bit reverse and shift away 5 + return stbi__bitreverse16(v) >> (16-bits); +} + +static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) +{ + int i,k=0; + int code, next_code[16], sizes[17]; + + // DEFLATE spec for generating codes + memset(sizes, 0, sizeof(sizes)); + memset(z->fast, 0, sizeof(z->fast)); + for (i=0; i < num; ++i) + ++sizes[sizelist[i]]; + sizes[0] = 0; + for (i=1; i < 16; ++i) + if (sizes[i] > (1 << i)) + return stbi__err("bad sizes", "Corrupt PNG"); + code = 0; + for (i=1; i < 16; ++i) { + next_code[i] = code; + z->firstcode[i] = (stbi__uint16) code; + z->firstsymbol[i] = (stbi__uint16) k; + code = (code + sizes[i]); + if (sizes[i]) + if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); + z->maxcode[i] = code << (16-i); // preshift for inner loop + code <<= 1; + k += sizes[i]; + } + z->maxcode[16] = 0x10000; // sentinel + for (i=0; i < num; ++i) { + int s = sizelist[i]; + if (s) { + int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); + z->size [c] = (stbi_uc ) s; + z->value[c] = (stbi__uint16) i; + if (s <= STBI__ZFAST_BITS) { + int j = stbi__bit_reverse(next_code[s],s); + while (j < (1 << STBI__ZFAST_BITS)) { + z->fast[j] = fastv; + j += (1 << s); + } + } + ++next_code[s]; + } + } + return 1; +} + +// zlib-from-memory implementation for PNG reading +// because PNG allows splitting the zlib stream arbitrarily, +// and it's annoying structurally to have PNG call ZLIB call PNG, +// we require PNG read all the IDATs and combine them into a single +// memory buffer + +typedef struct +{ + stbi_uc *zbuffer, *zbuffer_end; + int num_bits; + int hit_zeof_once; + stbi__uint32 code_buffer; + + char *zout; + char *zout_start; + char *zout_end; + int z_expandable; + + stbi__zhuffman z_length, z_distance; +} stbi__zbuf; + +stbi_inline static int stbi__zeof(stbi__zbuf *z) +{ + return (z->zbuffer >= z->zbuffer_end); +} + +stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) +{ + return stbi__zeof(z) ? 0 : *z->zbuffer++; +} + +static void stbi__fill_bits(stbi__zbuf *z) +{ + do { + if (z->code_buffer >= (1U << z->num_bits)) { + z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ + return; + } + z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; + z->num_bits += 8; + } while (z->num_bits <= 24); +} + +stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) +{ + unsigned int k; + if (z->num_bits < n) stbi__fill_bits(z); + k = z->code_buffer & ((1 << n) - 1); + z->code_buffer >>= n; + z->num_bits -= n; + return k; +} + +static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s,k; + // not resolved by fast table, so compute it the slow way + // use jpeg approach, which requires MSbits at top + k = stbi__bit_reverse(a->code_buffer, 16); + for (s=STBI__ZFAST_BITS+1; ; ++s) + if (k < z->maxcode[s]) + break; + if (s >= 16) return -1; // invalid code! + // code size is s, so: + b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; + if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! + if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; +} + +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s; + if (a->num_bits < 16) { + if (stbi__zeof(a)) { + if (!a->hit_zeof_once) { + // This is the first time we hit eof, insert 16 extra padding btis + // to allow us to keep going; if we actually consume any of them + // though, that is invalid data. This is caught later. + a->hit_zeof_once = 1; + a->num_bits += 16; // add 16 implicit zero bits + } else { + // We already inserted our extra 16 padding bits and are again + // out, this stream is actually prematurely terminated. + return -1; + } + } else { + stbi__fill_bits(a); + } + } + b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; + if (b) { + s = b >> 9; + a->code_buffer >>= s; + a->num_bits -= s; + return b & 511; + } + return stbi__zhuffman_decode_slowpath(a, z); +} + +static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes +{ + char *q; + unsigned int cur, limit, old_limit; + z->zout = zout; + if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); + cur = (unsigned int) (z->zout - z->zout_start); + limit = old_limit = (unsigned) (z->zout_end - z->zout_start); + if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); + while (cur + n > limit) { + if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); + limit *= 2; + } + q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); + if (q == NULL) return stbi__err("outofmem", "Out of memory"); + z->zout_start = q; + z->zout = q + cur; + z->zout_end = q + limit; + return 1; +} + +static const int stbi__zlength_base[31] = { + 3,4,5,6,7,8,9,10,11,13, + 15,17,19,23,27,31,35,43,51,59, + 67,83,99,115,131,163,195,227,258,0,0 }; + +static const int stbi__zlength_extra[31]= +{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + +static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, +257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + +static const int stbi__zdist_extra[32] = +{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +static int stbi__parse_huffman_block(stbi__zbuf *a) +{ + char *zout = a->zout; + for(;;) { + int z = stbi__zhuffman_decode(a, &a->z_length); + if (z < 256) { + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes + if (zout >= a->zout_end) { + if (!stbi__zexpand(a, zout, 1)) return 0; + zout = a->zout; + } + *zout++ = (char) z; + } else { + stbi_uc *p; + int len,dist; + if (z == 256) { + a->zout = zout; + if (a->hit_zeof_once && a->num_bits < 16) { + // The first time we hit zeof, we inserted 16 extra zero bits into our bit + // buffer so the decoder can just do its speculative decoding. But if we + // actually consumed any of those bits (which is the case when num_bits < 16), + // the stream actually read past the end so it is malformed. + return stbi__err("unexpected end","Corrupt PNG"); + } + return 1; + } + if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data + z -= 257; + len = stbi__zlength_base[z]; + if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); + z = stbi__zhuffman_decode(a, &a->z_distance); + if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data + dist = stbi__zdist_base[z]; + if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); + if (len > a->zout_end - zout) { + if (!stbi__zexpand(a, zout, len)) return 0; + zout = a->zout; + } + p = (stbi_uc *) (zout - dist); + if (dist == 1) { // run of one byte; common in images. + stbi_uc v = *p; + if (len) { do *zout++ = v; while (--len); } + } else { + if (len) { do *zout++ = *p++; while (--len); } + } + } + } +} + +static int stbi__compute_huffman_codes(stbi__zbuf *a) +{ + static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + stbi__zhuffman z_codelength; + stbi_uc lencodes[286+32+137];//padding for maximum single op + stbi_uc codelength_sizes[19]; + int i,n; + + int hlit = stbi__zreceive(a,5) + 257; + int hdist = stbi__zreceive(a,5) + 1; + int hclen = stbi__zreceive(a,4) + 4; + int ntot = hlit + hdist; + + memset(codelength_sizes, 0, sizeof(codelength_sizes)); + for (i=0; i < hclen; ++i) { + int s = stbi__zreceive(a,3); + codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; + } + if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; + + n = 0; + while (n < ntot) { + int c = stbi__zhuffman_decode(a, &z_codelength); + if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); + if (c < 16) + lencodes[n++] = (stbi_uc) c; + else { + stbi_uc fill = 0; + if (c == 16) { + c = stbi__zreceive(a,2)+3; + if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); + fill = lencodes[n-1]; + } else if (c == 17) { + c = stbi__zreceive(a,3)+3; + } else if (c == 18) { + c = stbi__zreceive(a,7)+11; + } else { + return stbi__err("bad codelengths", "Corrupt PNG"); + } + if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); + memset(lencodes+n, fill, c); + n += c; + } + } + if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); + if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; + return 1; +} + +static int stbi__parse_uncompressed_block(stbi__zbuf *a) +{ + stbi_uc header[4]; + int len,nlen,k; + if (a->num_bits & 7) + stbi__zreceive(a, a->num_bits & 7); // discard + // drain the bit-packed data into header + k = 0; + while (a->num_bits > 0) { + header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check + a->code_buffer >>= 8; + a->num_bits -= 8; + } + if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); + // now fill header the normal way + while (k < 4) + header[k++] = stbi__zget8(a); + len = header[1] * 256 + header[0]; + nlen = header[3] * 256 + header[2]; + if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); + if (a->zout + len > a->zout_end) + if (!stbi__zexpand(a, a->zout, len)) return 0; + memcpy(a->zout, a->zbuffer, len); + a->zbuffer += len; + a->zout += len; + return 1; +} + +static int stbi__parse_zlib_header(stbi__zbuf *a) +{ + int cmf = stbi__zget8(a); + int cm = cmf & 15; + /* int cinfo = cmf >> 4; */ + int flg = stbi__zget8(a); + if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png + if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png + // window = 1 << (8 + cinfo)... but who cares, we fully buffer output + return 1; +} + +static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = +{ + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 +}; +static const stbi_uc stbi__zdefault_distance[32] = +{ + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 +}; +/* +Init algorithm: +{ + int i; // use <= to match clearly with spec + for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; + for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; + for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; + for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; + + for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; +} +*/ + +static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) +{ + int final, type; + if (parse_header) + if (!stbi__parse_zlib_header(a)) return 0; + a->num_bits = 0; + a->code_buffer = 0; + a->hit_zeof_once = 0; + do { + final = stbi__zreceive(a,1); + type = stbi__zreceive(a,2); + if (type == 0) { + if (!stbi__parse_uncompressed_block(a)) return 0; + } else if (type == 3) { + return 0; + } else { + if (type == 1) { + // use fixed code lengths + if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; + } else { + if (!stbi__compute_huffman_codes(a)) return 0; + } + if (!stbi__parse_huffman_block(a)) return 0; + } + } while (!final); + return 1; +} + +static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) +{ + a->zout_start = obuf; + a->zout = obuf; + a->zout_end = obuf + olen; + a->z_expandable = exp; + + return stbi__parse_zlib(a, parse_header); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) +{ + return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) + return (int) (a.zout - a.zout_start); + else + return -1; +} + +STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(16384); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer+len; + if (stbi__do_zlib(&a, p, 16384, 1, 0)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) + return (int) (a.zout - a.zout_start); + else + return -1; +} +#endif + +// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 +// simple implementation +// - only 8-bit samples +// - no CRC checking +// - allocates lots of intermediate memory +// - avoids problem of streaming data between subsystems +// - avoids explicit window management +// performance +// - uses stb_zlib, a PD zlib implementation with fast huffman decoding + +#ifndef STBI_NO_PNG +typedef struct +{ + stbi__uint32 length; + stbi__uint32 type; +} stbi__pngchunk; + +static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) +{ + stbi__pngchunk c; + c.length = stbi__get32be(s); + c.type = stbi__get32be(s); + return c; +} + +static int stbi__check_png_header(stbi__context *s) +{ + static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + int i; + for (i=0; i < 8; ++i) + if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); + return 1; +} + +typedef struct +{ + stbi__context *s; + stbi_uc *idata, *expanded, *out; + int depth; +} stbi__png; + + +enum { + STBI__F_none=0, + STBI__F_sub=1, + STBI__F_up=2, + STBI__F_avg=3, + STBI__F_paeth=4, + // synthetic filter used for first scanline to avoid needing a dummy row of 0s + STBI__F_avg_first +}; + +static stbi_uc first_row_filter[5] = +{ + STBI__F_none, + STBI__F_sub, + STBI__F_none, + STBI__F_avg_first, + STBI__F_sub // Paeth with b=c=0 turns out to be equivalent to sub +}; + +static int stbi__paeth(int a, int b, int c) +{ + // This formulation looks very different from the reference in the PNG spec, but is + // actually equivalent and has favorable data dependencies and admits straightforward + // generation of branch-free code, which helps performance significantly. + int thresh = c*3 - (a + b); + int lo = a < b ? a : b; + int hi = a < b ? b : a; + int t0 = (hi <= thresh) ? lo : c; + int t1 = (thresh <= lo) ? hi : t0; + return t1; +} + +static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; + +// adds an extra all-255 alpha channel +// dest == src is legal +// img_n must be 1 or 3 +static void stbi__create_png_alpha_expand8(stbi_uc *dest, stbi_uc *src, stbi__uint32 x, int img_n) +{ + int i; + // must process data backwards since we allow dest==src + if (img_n == 1) { + for (i=x-1; i >= 0; --i) { + dest[i*2+1] = 255; + dest[i*2+0] = src[i]; + } + } else { + STBI_ASSERT(img_n == 3); + for (i=x-1; i >= 0; --i) { + dest[i*4+3] = 255; + dest[i*4+2] = src[i*3+2]; + dest[i*4+1] = src[i*3+1]; + dest[i*4+0] = src[i*3+0]; + } + } +} + +// create the png data from post-deflated data +static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) +{ + int bytes = (depth == 16 ? 2 : 1); + stbi__context *s = a->s; + stbi__uint32 i,j,stride = x*out_n*bytes; + stbi__uint32 img_len, img_width_bytes; + stbi_uc *filter_buf; + int all_ok = 1; + int k; + int img_n = s->img_n; // copy it into a local for later + + int output_bytes = out_n*bytes; + int filter_bytes = img_n*bytes; + int width = x; + + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); + a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into + if (!a->out) return stbi__err("outofmem", "Out of memory"); + + // note: error exits here don't need to clean up a->out individually, + // stbi__do_png always does on error. + if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); + img_width_bytes = (((img_n * x * depth) + 7) >> 3); + if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes)) return stbi__err("too large", "Corrupt PNG"); + img_len = (img_width_bytes + 1) * y; + + // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, + // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), + // so just check for raw_len < img_len always. + if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); + + // Allocate two scan lines worth of filter workspace buffer. + filter_buf = (stbi_uc *) stbi__malloc_mad2(img_width_bytes, 2, 0); + if (!filter_buf) return stbi__err("outofmem", "Out of memory"); + + // Filtering for low-bit-depth images + if (depth < 8) { + filter_bytes = 1; + width = img_width_bytes; + } + + for (j=0; j < y; ++j) { + // cur/prior filter buffers alternate + stbi_uc *cur = filter_buf + (j & 1)*img_width_bytes; + stbi_uc *prior = filter_buf + (~j & 1)*img_width_bytes; + stbi_uc *dest = a->out + stride*j; + int nk = width * filter_bytes; + int filter = *raw++; + + // check filter type + if (filter > 4) { + all_ok = stbi__err("invalid filter","Corrupt PNG"); + break; + } + + // if first row, use special filter that doesn't sample previous row + if (j == 0) filter = first_row_filter[filter]; + + // perform actual filtering + switch (filter) { + case STBI__F_none: + memcpy(cur, raw, nk); + break; + case STBI__F_sub: + memcpy(cur, raw, filter_bytes); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); + break; + case STBI__F_up: + for (k = 0; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + prior[k]); + break; + case STBI__F_avg: + for (k = 0; k < filter_bytes; ++k) + cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); + break; + case STBI__F_paeth: + for (k = 0; k < filter_bytes; ++k) + cur[k] = STBI__BYTECAST(raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0) + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes], prior[k], prior[k-filter_bytes])); + break; + case STBI__F_avg_first: + memcpy(cur, raw, filter_bytes); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); + break; + } + + raw += nk; + + // expand decoded bits in cur to dest, also adding an extra alpha channel if desired + if (depth < 8) { + stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range + stbi_uc *in = cur; + stbi_uc *out = dest; + stbi_uc inb = 0; + stbi__uint32 nsmp = x*img_n; + + // expand bits to bytes first + if (depth == 4) { + for (i=0; i < nsmp; ++i) { + if ((i & 1) == 0) inb = *in++; + *out++ = scale * (inb >> 4); + inb <<= 4; + } + } else if (depth == 2) { + for (i=0; i < nsmp; ++i) { + if ((i & 3) == 0) inb = *in++; + *out++ = scale * (inb >> 6); + inb <<= 2; + } + } else { + STBI_ASSERT(depth == 1); + for (i=0; i < nsmp; ++i) { + if ((i & 7) == 0) inb = *in++; + *out++ = scale * (inb >> 7); + inb <<= 1; + } + } + + // insert alpha=255 values if desired + if (img_n != out_n) + stbi__create_png_alpha_expand8(dest, dest, x, img_n); + } else if (depth == 8) { + if (img_n == out_n) + memcpy(dest, cur, x*img_n); + else + stbi__create_png_alpha_expand8(dest, cur, x, img_n); + } else if (depth == 16) { + // convert the image data from big-endian to platform-native + stbi__uint16 *dest16 = (stbi__uint16*)dest; + stbi__uint32 nsmp = x*img_n; + + if (img_n == out_n) { + for (i = 0; i < nsmp; ++i, ++dest16, cur += 2) + *dest16 = (cur[0] << 8) | cur[1]; + } else { + STBI_ASSERT(img_n+1 == out_n); + if (img_n == 1) { + for (i = 0; i < x; ++i, dest16 += 2, cur += 2) { + dest16[0] = (cur[0] << 8) | cur[1]; + dest16[1] = 0xffff; + } + } else { + STBI_ASSERT(img_n == 3); + for (i = 0; i < x; ++i, dest16 += 4, cur += 6) { + dest16[0] = (cur[0] << 8) | cur[1]; + dest16[1] = (cur[2] << 8) | cur[3]; + dest16[2] = (cur[4] << 8) | cur[5]; + dest16[3] = 0xffff; + } + } + } + } + } + + STBI_FREE(filter_buf); + if (!all_ok) return 0; + + return 1; +} + +static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) +{ + int bytes = (depth == 16 ? 2 : 1); + int out_bytes = out_n * bytes; + stbi_uc *final; + int p; + if (!interlaced) + return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); + + // de-interlacing + final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + if (!final) return stbi__err("outofmem", "Out of memory"); + for (p=0; p < 7; ++p) { + int xorig[] = { 0,4,0,2,0,1,0 }; + int yorig[] = { 0,0,4,0,2,0,1 }; + int xspc[] = { 8,8,4,4,2,2,1 }; + int yspc[] = { 8,8,8,4,4,2,2 }; + int i,j,x,y; + // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 + x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; + y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; + if (x && y) { + stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { + STBI_FREE(final); + return 0; + } + for (j=0; j < y; ++j) { + for (i=0; i < x; ++i) { + int out_y = j*yspc[p]+yorig[p]; + int out_x = i*xspc[p]+xorig[p]; + memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, + a->out + (j*x+i)*out_bytes, out_bytes); + } + } + STBI_FREE(a->out); + image_data += img_len; + image_data_len -= img_len; + } + } + a->out = final; + + return 1; +} + +static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + // compute color-based transparency, assuming we've + // already got 255 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i=0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 255); + p += 2; + } + } else { + for (i=0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi__uint16 *p = (stbi__uint16*) z->out; + + // compute color-based transparency, assuming we've + // already got 65535 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 65535); + p += 2; + } + } else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) +{ + stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; + stbi_uc *p, *temp_out, *orig = a->out; + + p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); + + // between here and free(out) below, exitting would leak + temp_out = p; + + if (pal_img_n == 3) { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p += 3; + } + } else { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p[3] = palette[n+3]; + p += 4; + } + } + STBI_FREE(a->out); + a->out = temp_out; + + STBI_NOTUSED(len); + + return 1; +} + +static int stbi__unpremultiply_on_load_global = 0; +static int stbi__de_iphone_flag_global = 0; + +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_global = flag_true_if_should_convert; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global +#define stbi__de_iphone_flag stbi__de_iphone_flag_global +#else +static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set; +static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set; + +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; + stbi__unpremultiply_on_load_set = 1; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_local = flag_true_if_should_convert; + stbi__de_iphone_flag_set = 1; +} + +#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \ + ? stbi__unpremultiply_on_load_local \ + : stbi__unpremultiply_on_load_global) +#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \ + ? stbi__de_iphone_flag_local \ + : stbi__de_iphone_flag_global) +#endif // STBI_THREAD_LOCAL + +static void stbi__de_iphone(stbi__png *z) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + if (s->img_out_n == 3) { // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 3; + } + } else { + STBI_ASSERT(s->img_out_n == 4); + if (stbi__unpremultiply_on_load) { + // convert bgr to rgb and unpremultiply + for (i=0; i < pixel_count; ++i) { + stbi_uc a = p[3]; + stbi_uc t = p[0]; + if (a) { + stbi_uc half = a / 2; + p[0] = (p[2] * 255 + half) / a; + p[1] = (p[1] * 255 + half) / a; + p[2] = ( t * 255 + half) / a; + } else { + p[0] = p[2]; + p[2] = t; + } + p += 4; + } + } else { + // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 4; + } + } + } +} + +#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) + +static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) +{ + stbi_uc palette[1024], pal_img_n=0; + stbi_uc has_trans=0, tc[3]={0}; + stbi__uint16 tc16[3]; + stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; + int first=1,k,interlace=0, color=0, is_iphone=0; + stbi__context *s = z->s; + + z->expanded = NULL; + z->idata = NULL; + z->out = NULL; + + if (!stbi__check_png_header(s)) return 0; + + if (scan == STBI__SCAN_type) return 1; + + for (;;) { + stbi__pngchunk c = stbi__get_chunk_header(s); + switch (c.type) { + case STBI__PNG_TYPE('C','g','B','I'): + is_iphone = 1; + stbi__skip(s, c.length); + break; + case STBI__PNG_TYPE('I','H','D','R'): { + int comp,filter; + if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); + first = 0; + if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); + s->img_x = stbi__get32be(s); + s->img_y = stbi__get32be(s); + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); + color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); + comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); + filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); + interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); + if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); + if (!pal_img_n) { + s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + } else { + // if paletted, then pal_n is our final components, and + // img_n is # components to decompress/filter. + s->img_n = 1; + if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); + } + // even with SCAN_header, have to scan to see if we have a tRNS + break; + } + + case STBI__PNG_TYPE('P','L','T','E'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); + pal_len = c.length / 3; + if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); + for (i=0; i < pal_len; ++i) { + palette[i*4+0] = stbi__get8(s); + palette[i*4+1] = stbi__get8(s); + palette[i*4+2] = stbi__get8(s); + palette[i*4+3] = 255; + } + break; + } + + case STBI__PNG_TYPE('t','R','N','S'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); + if (pal_img_n) { + if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } + if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); + if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); + pal_img_n = 4; + for (i=0; i < c.length; ++i) + palette[i*4+3] = stbi__get8(s); + } else { + if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); + if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); + has_trans = 1; + // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now. + if (scan == STBI__SCAN_header) { ++s->img_n; return 1; } + if (z->depth == 16) { + for (k = 0; k < s->img_n && k < 3; ++k) // extra loop test to suppress false GCC warning + tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is + } else { + for (k = 0; k < s->img_n && k < 3; ++k) + tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger + } + } + break; + } + + case STBI__PNG_TYPE('I','D','A','T'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); + if (scan == STBI__SCAN_header) { + // header scan definitely stops at first IDAT + if (pal_img_n) + s->img_n = pal_img_n; + return 1; + } + if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes"); + if ((int)(ioff + c.length) < (int)ioff) return 0; + if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; + stbi_uc *p; + if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; + while (ioff + c.length > idata_limit) + idata_limit *= 2; + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + z->idata = p; + } + if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); + ioff += c.length; + break; + } + + case STBI__PNG_TYPE('I','E','N','D'): { + stbi__uint32 raw_len, bpl; + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (scan != STBI__SCAN_load) return 1; + if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); + // initial guess for decoded data size to avoid unnecessary reallocs + bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component + raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; + z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); + if (z->expanded == NULL) return 0; // zlib should set error + STBI_FREE(z->idata); z->idata = NULL; + if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) + s->img_out_n = s->img_n+1; + else + s->img_out_n = s->img_n; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; + if (has_trans) { + if (z->depth == 16) { + if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; + } else { + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + } + } + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) + stbi__de_iphone(z); + if (pal_img_n) { + // pal_img_n == 3 or 4 + s->img_n = pal_img_n; // record the actual colors we had + s->img_out_n = pal_img_n; + if (req_comp >= 3) s->img_out_n = req_comp; + if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) + return 0; + } else if (has_trans) { + // non-paletted image with tRNS -> source image has (constant) alpha + ++s->img_n; + } + STBI_FREE(z->expanded); z->expanded = NULL; + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + return 1; + } + + default: + // if critical, fail + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if ((c.type & (1 << 29)) == 0) { + #ifndef STBI_NO_FAILURE_STRINGS + // not threadsafe + static char invalid_chunk[] = "XXXX PNG chunk not known"; + invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); + invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); + invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); + invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); + #endif + return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); + } + stbi__skip(s, c.length); + break; + } + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + } +} + +static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) +{ + void *result=NULL; + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + if (p->depth <= 8) + ri->bits_per_channel = 8; + else if (p->depth == 16) + ri->bits_per_channel = 16; + else + return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); + result = p->out; + p->out = NULL; + if (req_comp && req_comp != p->s->img_out_n) { + if (ri->bits_per_channel == 8) + result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + else + result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + p->s->img_out_n = req_comp; + if (result == NULL) return result; + } + *x = p->s->img_x; + *y = p->s->img_y; + if (n) *n = p->s->img_n; + } + STBI_FREE(p->out); p->out = NULL; + STBI_FREE(p->expanded); p->expanded = NULL; + STBI_FREE(p->idata); p->idata = NULL; + + return result; +} + +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi__png p; + p.s = s; + return stbi__do_png(&p, x,y,comp,req_comp, ri); +} + +static int stbi__png_test(stbi__context *s) +{ + int r; + r = stbi__check_png_header(s); + stbi__rewind(s); + return r; +} + +static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) +{ + if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { + stbi__rewind( p->s ); + return 0; + } + if (x) *x = p->s->img_x; + if (y) *y = p->s->img_y; + if (comp) *comp = p->s->img_n; + return 1; +} + +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__png p; + p.s = s; + return stbi__png_info_raw(&p, x, y, comp); +} + +static int stbi__png_is16(stbi__context *s) +{ + stbi__png p; + p.s = s; + if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) + return 0; + if (p.depth != 16) { + stbi__rewind(p.s); + return 0; + } + return 1; +} +#endif + +// Microsoft/Windows BMP image + +#ifndef STBI_NO_BMP +static int stbi__bmp_test_raw(stbi__context *s) +{ + int r; + int sz; + if (stbi__get8(s) != 'B') return 0; + if (stbi__get8(s) != 'M') return 0; + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + stbi__get32le(s); // discard data offset + sz = stbi__get32le(s); + r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); + return r; +} + +static int stbi__bmp_test(stbi__context *s) +{ + int r = stbi__bmp_test_raw(s); + stbi__rewind(s); + return r; +} + + +// returns 0..31 for the highest set bit +static int stbi__high_bit(unsigned int z) +{ + int n=0; + if (z == 0) return -1; + if (z >= 0x10000) { n += 16; z >>= 16; } + if (z >= 0x00100) { n += 8; z >>= 8; } + if (z >= 0x00010) { n += 4; z >>= 4; } + if (z >= 0x00004) { n += 2; z >>= 2; } + if (z >= 0x00002) { n += 1;/* >>= 1;*/ } + return n; +} + +static int stbi__bitcount(unsigned int a) +{ + a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 + a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits + a = (a + (a >> 8)); // max 16 per 8 bits + a = (a + (a >> 16)); // max 32 per 8 bits + return a & 0xff; +} + +// extract an arbitrarily-aligned N-bit value (N=bits) +// from v, and then make it 8-bits long and fractionally +// extend it to full full range. +static int stbi__shiftsigned(unsigned int v, int shift, int bits) +{ + static unsigned int mul_table[9] = { + 0, + 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, + 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, + }; + static unsigned int shift_table[9] = { + 0, 0,0,1,0,2,4,6,0, + }; + if (shift < 0) + v <<= -shift; + else + v >>= shift; + STBI_ASSERT(v < 256); + v >>= (8-bits); + STBI_ASSERT(bits >= 0 && bits <= 8); + return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; +} + +typedef struct +{ + int bpp, offset, hsz; + unsigned int mr,mg,mb,ma, all_a; + int extra_read; +} stbi__bmp_data; + +static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress) +{ + // BI_BITFIELDS specifies masks explicitly, don't override + if (compress == 3) + return 1; + + if (compress == 0) { + if (info->bpp == 16) { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } else if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 + } else { + // otherwise, use defaults, which is all-0 + info->mr = info->mg = info->mb = info->ma = 0; + } + return 1; + } + return 0; // error +} + +static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) +{ + int hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + info->mr = info->mg = info->mb = info->ma = 0; + info->extra_read = 14; + + if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); + + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); + if (hsz == 12) { + s->img_x = stbi__get16le(s); + s->img_y = stbi__get16le(s); + } else { + s->img_x = stbi__get32le(s); + s->img_y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); + info->bpp = stbi__get16le(s); + if (hsz != 12) { + int compress = stbi__get32le(s); + if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes + if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel + stbi__get32le(s); // discard sizeof + stbi__get32le(s); // discard hres + stbi__get32le(s); // discard vres + stbi__get32le(s); // discard colorsused + stbi__get32le(s); // discard max important + if (hsz == 40 || hsz == 56) { + if (hsz == 56) { + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + } + if (info->bpp == 16 || info->bpp == 32) { + if (compress == 0) { + stbi__bmp_set_mask_defaults(info, compress); + } else if (compress == 3) { + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->extra_read += 12; + // not documented, but generated by photoshop and handled by mspaint + if (info->mr == info->mg && info->mg == info->mb) { + // ?!?!? + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else { + // V4/V5 header + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs + stbi__bmp_set_mask_defaults(info, compress); + stbi__get32le(s); // discard color space + for (i=0; i < 12; ++i) + stbi__get32le(s); // discard color space parameters + if (hsz == 124) { + stbi__get32le(s); // discard rendering intent + stbi__get32le(s); // discard offset of profile data + stbi__get32le(s); // discard size of profile data + stbi__get32le(s); // discard reserved + } + } + } + return (void *) 1; +} + + +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + unsigned int mr=0,mg=0,mb=0,ma=0, all_a; + stbi_uc pal[256][4]; + int psize=0,i,j,width; + int flip_vertically, pad, target; + stbi__bmp_data info; + STBI_NOTUSED(ri); + + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set + + flip_vertically = ((int) s->img_y) > 0; + s->img_y = abs((int) s->img_y); + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; + + if (info.hsz == 12) { + if (info.bpp < 24) + psize = (info.offset - info.extra_read - 24) / 3; + } else { + if (info.bpp < 16) + psize = (info.offset - info.extra_read - info.hsz) >> 2; + } + if (psize == 0) { + // accept some number of extra bytes after the header, but if the offset points either to before + // the header ends or implies a large amount of extra data, reject the file as malformed + int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original); + int header_limit = 1024; // max we actually read is below 256 bytes currently. + int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size. + if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) { + return stbi__errpuc("bad header", "Corrupt BMP"); + } + // we established that bytes_read_so_far is positive and sensible. + // the first half of this test rejects offsets that are either too small positives, or + // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn + // ensures the number computed in the second half of the test can't overflow. + if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) { + return stbi__errpuc("bad offset", "Corrupt BMP"); + } else { + stbi__skip(s, info.offset - bytes_read_so_far); + } + } + + if (info.bpp == 24 && ma == 0xff000000) + s->img_n = 3; + else + s->img_n = ma ? 4 : 3; + if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 + target = req_comp; + else + target = s->img_n; // if they want monochrome, we'll post-convert + + // sanity-check size + if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "Corrupt BMP"); + + out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (info.bpp < 16) { + int z=0; + if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } + for (i=0; i < psize; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); + pal[i][3] = 255; + } + stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 1) width = (s->img_x + 7) >> 3; + else if (info.bpp == 4) width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) width = s->img_x; + else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } + pad = (-width)&3; + if (info.bpp == 1) { + for (j=0; j < (int) s->img_y; ++j) { + int bit_offset = 7, v = stbi__get8(s); + for (i=0; i < (int) s->img_x; ++i) { + int color = (v>>bit_offset)&0x1; + out[z++] = pal[color][0]; + out[z++] = pal[color][1]; + out[z++] = pal[color][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + if((--bit_offset) < 0) { + bit_offset = 7; + v = stbi__get8(s); + } + } + stbi__skip(s, pad); + } + } else { + for (j=0; j < (int) s->img_y; ++j) { + for (i=0; i < (int) s->img_x; i += 2) { + int v=stbi__get8(s),v2=0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); + } + } + } else { + int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; + int z = 0; + int easy=0; + stbi__skip(s, info.offset - info.extra_read - info.hsz); + if (info.bpp == 24) width = 3 * s->img_x; + else if (info.bpp == 16) width = 2*s->img_x; + else /* bpp = 32 and pad = 0 */ width=0; + pad = (-width) & 3; + if (info.bpp == 24) { + easy = 1; + } else if (info.bpp == 32) { + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) + easy = 2; + } + if (!easy) { + if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + // right shift amt to put high bit in position #7 + rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); + gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); + bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); + ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); + if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + } + for (j=0; j < (int) s->img_y; ++j) { + if (easy) { + for (i=0; i < (int) s->img_x; ++i) { + unsigned char a; + out[z+2] = stbi__get8(s); + out[z+1] = stbi__get8(s); + out[z+0] = stbi__get8(s); + z += 3; + a = (easy == 2 ? stbi__get8(s) : 255); + all_a |= a; + if (target == 4) out[z++] = a; + } + } else { + int bpp = info.bpp; + for (i=0; i < (int) s->img_x; ++i) { + stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); + unsigned int a; + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); + a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); + all_a |= a; + if (target == 4) out[z++] = STBI__BYTECAST(a); + } + } + stbi__skip(s, pad); + } + } + + // if alpha channel is all 0s, replace with all 255s + if (target == 4 && all_a == 0) + for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) + out[i] = 255; + + if (flip_vertically) { + stbi_uc t; + for (j=0; j < (int) s->img_y>>1; ++j) { + stbi_uc *p1 = out + j *s->img_x*target; + stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; + for (i=0; i < (int) s->img_x*target; ++i) { + t = p1[i]; p1[i] = p2[i]; p2[i] = t; + } + } + } + + if (req_comp && req_comp != target) { + out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + return out; +} +#endif + +// Targa Truevision - TGA +// by Jonathan Dummer +#ifndef STBI_NO_TGA +// returns STBI_rgb or whatever, 0 on error +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) +{ + // only RGB or RGBA (incl. 16bit) or grey allowed + if (is_rgb16) *is_rgb16 = 0; + switch(bits_per_pixel) { + case 8: return STBI_grey; + case 16: if(is_grey) return STBI_grey_alpha; + // fallthrough + case 15: if(is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fallthrough + case 32: return bits_per_pixel/8; + default: return 0; + } +} + +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) +{ + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; + int sz, tga_colormap_type; + stbi__get8(s); // discard Offset + tga_colormap_type = stbi__get8(s); // colormap type + if( tga_colormap_type > 1 ) { + stbi__rewind(s); + return 0; // only RGB or indexed allowed + } + tga_image_type = stbi__get8(s); // image type + if ( tga_colormap_type == 1 ) { // colormapped (paletted) image + if (tga_image_type != 1 && tga_image_type != 9) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip image x and y origin + tga_colormap_bpp = sz; + } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { + stbi__rewind(s); + return 0; // only RGB or grey allowed, +/- RLE + } + stbi__skip(s,9); // skip colormap specification and image x/y origin + tga_colormap_bpp = 0; + } + tga_w = stbi__get16le(s); + if( tga_w < 1 ) { + stbi__rewind(s); + return 0; // test width + } + tga_h = stbi__get16le(s); + if( tga_h < 1 ) { + stbi__rewind(s); + return 0; // test height + } + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits + if (tga_colormap_bpp != 0) { + if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the indexes + // I don't think anything but 8 or 16bit indexes makes sense + stbi__rewind(s); + return 0; + } + tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); + } else { + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + } + if(!tga_comp) { + stbi__rewind(s); + return 0; + } + if (x) *x = tga_w; + if (y) *y = tga_h; + if (comp) *comp = tga_comp; + return 1; // seems to have passed everything +} + +static int stbi__tga_test(stbi__context *s) +{ + int res = 0; + int sz, tga_color_type; + stbi__get8(s); // discard Offset + tga_color_type = stbi__get8(s); // color type + if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed + sz = stbi__get8(s); // image type + if ( tga_color_type == 1 ) { // colormapped (paletted) image + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + stbi__skip(s,4); // skip image x and y origin + } else { // "normal" image w/o colormap + if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s,9); // skip colormap specification and image x/y origin + } + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height + sz = stbi__get8(s); // bits per pixel + if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + + res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + +errorEnd: + stbi__rewind(s); + return res; +} + +// read 16bit value and convert to 24bit RGB +static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) +{ + stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later + out[0] = (stbi_uc)((r * 255)/31); + out[1] = (stbi_uc)((g * 255)/31); + out[2] = (stbi_uc)((b * 255)/31); + + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. +} + +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + // read in the TGA header stuff + int tga_offset = stbi__get8(s); + int tga_indexed = stbi__get8(s); + int tga_image_type = stbi__get8(s); + int tga_is_RLE = 0; + int tga_palette_start = stbi__get16le(s); + int tga_palette_len = stbi__get16le(s); + int tga_palette_bits = stbi__get8(s); + int tga_x_origin = stbi__get16le(s); + int tga_y_origin = stbi__get16le(s); + int tga_width = stbi__get16le(s); + int tga_height = stbi__get16le(s); + int tga_bits_per_pixel = stbi__get8(s); + int tga_comp, tga_rgb16=0; + int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) + // image data + unsigned char *tga_data; + unsigned char *tga_palette = NULL; + int i, j; + unsigned char raw_data[4] = {0}; + int RLE_count = 0; + int RLE_repeating = 0; + int read_next_pixel = 1; + STBI_NOTUSED(ri); + STBI_NOTUSED(tga_x_origin); // @TODO + STBI_NOTUSED(tga_y_origin); // @TODO + + if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // do a tiny bit of precessing + if ( tga_image_type >= 8 ) + { + tga_image_type -= 8; + tga_is_RLE = 1; + } + tga_inverted = 1 - ((tga_inverted >> 5) & 1); + + // If I'm paletted, then I'll use the number of bits from the palette + if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + + if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); + + // tga info + *x = tga_width; + *y = tga_height; + if (comp) *comp = tga_comp; + + if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) + return stbi__errpuc("too large", "Corrupt TGA"); + + tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); + if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); + + // skip to the data's starting position (offset usually = 0) + stbi__skip(s, tga_offset ); + + if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { + for (i=0; i < tga_height; ++i) { + int row = tga_inverted ? tga_height -i - 1 : i; + stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; + stbi__getn(s, tga_row, tga_width * tga_comp); + } + } else { + // do I need to load a palette? + if ( tga_indexed) + { + if (tga_palette_len == 0) { /* you have to have at least one entry! */ + STBI_FREE(tga_data); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + + // any data to skip? (offset usually = 0) + stbi__skip(s, tga_palette_start ); + // load the palette + tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); + if (!tga_palette) { + STBI_FREE(tga_data); + return stbi__errpuc("outofmem", "Out of memory"); + } + if (tga_rgb16) { + stbi_uc *pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i=0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + } + // load the data + for (i=0; i < tga_width * tga_height; ++i) + { + // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? + if ( tga_is_RLE ) + { + if ( RLE_count == 0 ) + { + // yep, get the next byte as a RLE command + int RLE_cmd = stbi__get8(s); + RLE_count = 1 + (RLE_cmd & 127); + RLE_repeating = RLE_cmd >> 7; + read_next_pixel = 1; + } else if ( !RLE_repeating ) + { + read_next_pixel = 1; + } + } else + { + read_next_pixel = 1; + } + // OK, if I need to read a pixel, do it now + if ( read_next_pixel ) + { + // load however much data we did have + if ( tga_indexed ) + { + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); + if ( pal_idx >= tga_palette_len ) { + // invalid index + pal_idx = 0; + } + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = tga_palette[pal_idx+j]; + } + } else if(tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } else { + // read in the data raw + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = stbi__get8(s); + } + } + // clear the reading flag for the next pixel + read_next_pixel = 0; + } // end of reading a pixel + + // copy data + for (j = 0; j < tga_comp; ++j) + tga_data[i*tga_comp+j] = raw_data[j]; + + // in case we're in RLE mode, keep counting down + --RLE_count; + } + // do I need to invert the image? + if ( tga_inverted ) + { + for (j = 0; j*2 < tga_height; ++j) + { + int index1 = j * tga_width * tga_comp; + int index2 = (tga_height - 1 - j) * tga_width * tga_comp; + for (i = tga_width * tga_comp; i > 0; --i) + { + unsigned char temp = tga_data[index1]; + tga_data[index1] = tga_data[index2]; + tga_data[index2] = temp; + ++index1; + ++index2; + } + } + } + // clear my palette, if I had one + if ( tga_palette != NULL ) + { + STBI_FREE( tga_palette ); + } + } + + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) + { + unsigned char* tga_pixel = tga_data; + for (i=0; i < tga_width * tga_height; ++i) + { + unsigned char temp = tga_pixel[0]; + tga_pixel[0] = tga_pixel[2]; + tga_pixel[2] = temp; + tga_pixel += tga_comp; + } + } + + // convert to target component count + if (req_comp && req_comp != tga_comp) + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); + + // the things I do to get rid of an error message, and yet keep + // Microsoft's C compilers happy... [8^( + tga_palette_start = tga_palette_len = tga_palette_bits = + tga_x_origin = tga_y_origin = 0; + STBI_NOTUSED(tga_palette_start); + // OK, done + return tga_data; +} +#endif + +// ************************************************************************************************* +// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s) +{ + int r = (stbi__get32be(s) == 0x38425053); + stbi__rewind(s); + return r; +} + +static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) +{ + int count, nleft, len; + + count = 0; + while ((nleft = pixelCount - count) > 0) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + if (len > nleft) return 0; // corrupt data + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len = 257 - len; + if (len > nleft) return 0; // corrupt data + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + + return 1; +} + +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + int pixelCount; + int channelCount, compression; + int channel, i; + int bitdepth; + int w,h; + stbi_uc *out; + STBI_NOTUSED(ri); + + // Check identifier + if (stbi__get32be(s) != 0x38425053) // "8BPS" + return stbi__errpuc("not PSD", "Corrupt PSD image"); + + // Check file type version. + if (stbi__get16be(s) != 1) + return stbi__errpuc("wrong version", "Unsupported version of PSD image"); + + // Skip 6 reserved bytes. + stbi__skip(s, 6 ); + + // Read the number of channels (R, G, B, A, etc). + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) + return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); + + // Read the rows and columns of the image. + h = stbi__get32be(s); + w = stbi__get32be(s); + + if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // Make sure the depth is 8 bits. + bitdepth = stbi__get16be(s); + if (bitdepth != 8 && bitdepth != 16) + return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); + + // Make sure the color mode is RGB. + // Valid options are: + // 0: Bitmap + // 1: Grayscale + // 2: Indexed color + // 3: RGB color + // 4: CMYK color + // 7: Multichannel + // 8: Duotone + // 9: Lab color + if (stbi__get16be(s) != 3) + return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); + + // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) + stbi__skip(s,stbi__get32be(s) ); + + // Skip the image resources. (resolution, pen tool paths, etc) + stbi__skip(s, stbi__get32be(s) ); + + // Skip the reserved data. + stbi__skip(s, stbi__get32be(s) ); + + // Find out if the data is compressed. + // Known values: + // 0: no compression + // 1: RLE compressed + compression = stbi__get16be(s); + if (compression > 1) + return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + + // Check size + if (!stbi__mad3sizes_valid(4, w, h, 0)) + return stbi__errpuc("too large", "Corrupt PSD"); + + // Create the destination image. + + if (!compression && bitdepth == 16 && bpc == 16) { + out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); + ri->bits_per_channel = 16; + } else + out = (stbi_uc *) stbi__malloc(4 * w*h); + + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + pixelCount = w*h; + + // Initialize the data to zero. + //memset( out, 0, pixelCount * 4 ); + + // Finally, the image data. + if (compression) { + // RLE as used by .PSD and .TIFF + // Loop until you get the number of unpacked bytes you are expecting: + // Read the next source byte into n. + // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. + // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. + // Else if n is 128, noop. + // Endloop + + // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, + // which we're going to just skip. + stbi__skip(s, h * channelCount * 2 ); + + // Read the RLE data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc *p; + + p = out+channel; + if (channel >= channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++, p += 4) + *p = (channel == 3 ? 255 : 0); + } else { + // Read the RLE data. + if (!stbi__psd_decode_rle(s, p, pixelCount)) { + STBI_FREE(out); + return stbi__errpuc("corrupt", "bad RLE data"); + } + } + } + + } else { + // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) + // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. + + // Read the data by channel. + for (channel = 0; channel < 4; channel++) { + if (channel >= channelCount) { + // Fill this channel with default data. + if (bitdepth == 16 && bpc == 16) { + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + stbi__uint16 val = channel == 3 ? 65535 : 0; + for (i = 0; i < pixelCount; i++, q += 4) + *q = val; + } else { + stbi_uc *p = out+channel; + stbi_uc val = channel == 3 ? 255 : 0; + for (i = 0; i < pixelCount; i++, p += 4) + *p = val; + } + } else { + if (ri->bits_per_channel == 16) { // output bpc + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + for (i = 0; i < pixelCount; i++, q += 4) + *q = (stbi__uint16) stbi__get16be(s); + } else { + stbi_uc *p = out+channel; + if (bitdepth == 16) { // input bpc + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc) (stbi__get16be(s) >> 8); + } else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } + } + } + } + } + + // remove weird white matte from PSD + if (channelCount >= 4) { + if (ri->bits_per_channel == 16) { + for (i=0; i < w*h; ++i) { + stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; + if (pixel[3] != 0 && pixel[3] != 65535) { + float a = pixel[3] / 65535.0f; + float ra = 1.0f / a; + float inv_a = 65535.0f * (1 - ra); + pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); + pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); + pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); + } + } + } else { + for (i=0; i < w*h; ++i) { + unsigned char *pixel = out + 4*i; + if (pixel[3] != 0 && pixel[3] != 255) { + float a = pixel[3] / 255.0f; + float ra = 1.0f / a; + float inv_a = 255.0f * (1 - ra); + pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); + pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); + pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); + } + } + } + } + + // convert to desired output format + if (req_comp && req_comp != 4) { + if (ri->bits_per_channel == 16) + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); + else + out = stbi__convert_format(out, 4, req_comp, w, h); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + if (comp) *comp = 4; + *y = h; + *x = w; + + return out; +} +#endif + +// ************************************************************************************************* +// Softimage PIC loader +// by Tom Seddon +// +// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format +// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ + +#ifndef STBI_NO_PIC +static int stbi__pic_is4(stbi__context *s,const char *str) +{ + int i; + for (i=0; i<4; ++i) + if (stbi__get8(s) != (stbi_uc)str[i]) + return 0; + + return 1; +} + +static int stbi__pic_test_core(stbi__context *s) +{ + int i; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) + return 0; + + for(i=0;i<84;++i) + stbi__get8(s); + + if (!stbi__pic_is4(s,"PICT")) + return 0; + + return 1; +} + +typedef struct +{ + stbi_uc size,type,channel; +} stbi__pic_packet; + +static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) +{ + int mask=0x80, i; + + for (i=0; i<4; ++i, mask>>=1) { + if (channel & mask) { + if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); + dest[i]=stbi__get8(s); + } + } + + return dest; +} + +static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) +{ + int mask=0x80,i; + + for (i=0;i<4; ++i, mask>>=1) + if (channel&mask) + dest[i]=src[i]; +} + +static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) +{ + int act_comp=0,num_packets=0,y,chained; + stbi__pic_packet packets[10]; + + // this will (should...) cater for even some bizarre stuff like having data + // for the same channel in multiple packets. + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return stbi__errpuc("bad format","too many packets"); + + packet = &packets[num_packets++]; + + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + + act_comp |= packet->channel; + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); + if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? + + for(y=0; ytype) { + default: + return stbi__errpuc("bad format","packet has bad compression type"); + + case 0: {//uncompressed + int x; + + for(x=0;xchannel,dest)) + return 0; + break; + } + + case 1://Pure RLE + { + int left=width, i; + + while (left>0) { + stbi_uc count,value[4]; + + count=stbi__get8(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); + + if (count > left) + count = (stbi_uc) left; + + if (!stbi__readval(s,packet->channel,value)) return 0; + + for(i=0; ichannel,dest,value); + left -= count; + } + } + break; + + case 2: {//Mixed RLE + int left=width; + while (left>0) { + int count = stbi__get8(s), i; + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); + + if (count >= 128) { // Repeated + stbi_uc value[4]; + + if (count==128) + count = stbi__get16be(s); + else + count -= 127; + if (count > left) + return stbi__errpuc("bad file","scanline overrun"); + + if (!stbi__readval(s,packet->channel,value)) + return 0; + + for(i=0;ichannel,dest,value); + } else { // Raw + ++count; + if (count>left) return stbi__errpuc("bad file","scanline overrun"); + + for(i=0;ichannel,dest)) + return 0; + } + left-=count; + } + break; + } + } + } + } + + return result; +} + +static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) +{ + stbi_uc *result; + int i, x,y, internal_comp; + STBI_NOTUSED(ri); + + if (!comp) comp = &internal_comp; + + for (i=0; i<92; ++i) + stbi__get8(s); + + x = stbi__get16be(s); + y = stbi__get16be(s); + + if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); + if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); + + stbi__get32be(s); //skip `ratio' + stbi__get16be(s); //skip `fields' + stbi__get16be(s); //skip `pad' + + // intermediate buffer is RGBA + result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); + if (!result) return stbi__errpuc("outofmem", "Out of memory"); + memset(result, 0xff, x*y*4); + + if (!stbi__pic_load_core(s,x,y,comp, result)) { + STBI_FREE(result); + result=0; + } + *px = x; + *py = y; + if (req_comp == 0) req_comp = *comp; + result=stbi__convert_format(result,4,req_comp,x,y); + + return result; +} + +static int stbi__pic_test(stbi__context *s) +{ + int r = stbi__pic_test_core(s); + stbi__rewind(s); + return r; +} +#endif + +// ************************************************************************************************* +// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb + +#ifndef STBI_NO_GIF +typedef struct +{ + stbi__int16 prefix; + stbi_uc first; + stbi_uc suffix; +} stbi__gif_lzw; + +typedef struct +{ + int w,h; + stbi_uc *out; // output buffer (always 4 components) + stbi_uc *background; // The current "background" as far as a gif is concerned + stbi_uc *history; + int flags, bgindex, ratio, transparent, eflags; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[8192]; + stbi_uc *color_table; + int parse, step; + int lflags; + int start_x, start_y; + int max_x, max_y; + int cur_x, cur_y; + int line_size; + int delay; +} stbi__gif; + +static int stbi__gif_test_raw(stbi__context *s) +{ + int sz; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; + sz = stbi__get8(s); + if (sz != '9' && sz != '7') return 0; + if (stbi__get8(s) != 'a') return 0; + return 1; +} + +static int stbi__gif_test(stbi__context *s) +{ + int r = stbi__gif_test_raw(s); + stbi__rewind(s); + return r; +} + +static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) +{ + int i; + for (i=0; i < num_entries; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + pal[i][3] = transp == i ? 0 : 255; + } +} + +static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) +{ + stbi_uc version; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') + return stbi__err("not GIF", "Corrupt GIF"); + + version = stbi__get8(s); + if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); + if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); + + stbi__g_failure_reason = ""; + g->w = stbi__get16le(s); + g->h = stbi__get16le(s); + g->flags = stbi__get8(s); + g->bgindex = stbi__get8(s); + g->ratio = stbi__get8(s); + g->transparent = -1; + + if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + + if (is_info) return 1; + + if (g->flags & 0x80) + stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); + + return 1; +} + +static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); + if (!g) return stbi__err("outofmem", "Out of memory"); + if (!stbi__gif_header(s, g, comp, 1)) { + STBI_FREE(g); + stbi__rewind( s ); + return 0; + } + if (x) *x = g->w; + if (y) *y = g->h; + STBI_FREE(g); + return 1; +} + +static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) +{ + stbi_uc *p, *c; + int idx; + + // recurse to decode the prefixes, since the linked-list is backwards, + // and working backwards through an interleaved image would be nasty + if (g->codes[code].prefix >= 0) + stbi__out_gif_code(g, g->codes[code].prefix); + + if (g->cur_y >= g->max_y) return; + + idx = g->cur_x + g->cur_y; + p = &g->out[idx]; + g->history[idx / 4] = 1; + + c = &g->color_table[g->codes[code].suffix * 4]; + if (c[3] > 128) { // don't render transparent pixels; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } + g->cur_x += 4; + + if (g->cur_x >= g->max_x) { + g->cur_x = g->start_x; + g->cur_y += g->step; + + while (g->cur_y >= g->max_y && g->parse > 0) { + g->step = (1 << g->parse) * g->line_size; + g->cur_y = g->start_y + (g->step >> 1); + --g->parse; + } + } +} + +static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) +{ + stbi_uc lzw_cs; + stbi__int32 len, init_code; + stbi__uint32 first; + stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; + stbi__gif_lzw *p; + + lzw_cs = stbi__get8(s); + if (lzw_cs > 12) return NULL; + clear = 1 << lzw_cs; + first = 1; + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + bits = 0; + valid_bits = 0; + for (init_code = 0; init_code < clear; init_code++) { + g->codes[init_code].prefix = -1; + g->codes[init_code].first = (stbi_uc) init_code; + g->codes[init_code].suffix = (stbi_uc) init_code; + } + + // support no starting clear code + avail = clear+2; + oldcode = -1; + + len = 0; + for(;;) { + if (valid_bits < codesize) { + if (len == 0) { + len = stbi__get8(s); // start new block + if (len == 0) + return g->out; + } + --len; + bits |= (stbi__int32) stbi__get8(s) << valid_bits; + valid_bits += 8; + } else { + stbi__int32 code = bits & codemask; + bits >>= codesize; + valid_bits -= codesize; + // @OPTIMIZE: is there some way we can accelerate the non-clear path? + if (code == clear) { // clear code + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + avail = clear + 2; + oldcode = -1; + first = 0; + } else if (code == clear + 1) { // end of stream code + stbi__skip(s, len); + while ((len = stbi__get8(s)) > 0) + stbi__skip(s,len); + return g->out; + } else if (code <= avail) { + if (first) { + return stbi__errpuc("no clear code", "Corrupt GIF"); + } + + if (oldcode >= 0) { + p = &g->codes[avail++]; + if (avail > 8192) { + return stbi__errpuc("too many codes", "Corrupt GIF"); + } + + p->prefix = (stbi__int16) oldcode; + p->first = g->codes[oldcode].first; + p->suffix = (code == avail) ? p->first : g->codes[code].first; + } else if (code == avail) + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + + stbi__out_gif_code(g, (stbi__uint16) code); + + if ((avail & codemask) == 0 && avail <= 0x0FFF) { + codesize++; + codemask = (1 << codesize) - 1; + } + + oldcode = code; + } else { + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + } + } + } +} + +// this function is designed to support animated gifs, although stb_image doesn't support it +// two back is the image from two frames ago, used for a very specific disposal format +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) +{ + int dispose; + int first_frame; + int pi; + int pcount; + STBI_NOTUSED(req_comp); + + // on first frame, any non-written pixels get the background colour (non-transparent) + first_frame = 0; + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) + return stbi__errpuc("too large", "GIF image is too large"); + pcount = g->w * g->h; + g->out = (stbi_uc *) stbi__malloc(4 * pcount); + g->background = (stbi_uc *) stbi__malloc(4 * pcount); + g->history = (stbi_uc *) stbi__malloc(pcount); + if (!g->out || !g->background || !g->history) + return stbi__errpuc("outofmem", "Out of memory"); + + // image is treated as "transparent" at the start - ie, nothing overwrites the current background; + // background colour is only used for pixels that are not rendered first frame, after that "background" + // color refers to the color that was there the previous frame. + memset(g->out, 0x00, 4 * pcount); + memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) + memset(g->history, 0x00, pcount); // pixels that were affected previous frame + first_frame = 1; + } else { + // second frame - how do we dispose of the previous one? + dispose = (g->eflags & 0x1C) >> 2; + pcount = g->w * g->h; + + if ((dispose == 3) && (two_back == 0)) { + dispose = 2; // if I don't have an image to revert back to, default to the old background + } + + if (dispose == 3) { // use previous graphic + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); + } + } + } else if (dispose == 2) { + // restore what was changed last frame to background before that frame; + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); + } + } + } else { + // This is a non-disposal case eithe way, so just + // leave the pixels as is, and they will become the new background + // 1: do not dispose + // 0: not specified. + } + + // background is what out is after the undoing of the previou frame; + memcpy( g->background, g->out, 4 * g->w * g->h ); + } + + // clear my history; + memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame + + for (;;) { + int tag = stbi__get8(s); + switch (tag) { + case 0x2C: /* Image Descriptor */ + { + stbi__int32 x, y, w, h; + stbi_uc *o; + + x = stbi__get16le(s); + y = stbi__get16le(s); + w = stbi__get16le(s); + h = stbi__get16le(s); + if (((x + w) > (g->w)) || ((y + h) > (g->h))) + return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); + + g->line_size = g->w * 4; + g->start_x = x * 4; + g->start_y = y * g->line_size; + g->max_x = g->start_x + w * 4; + g->max_y = g->start_y + h * g->line_size; + g->cur_x = g->start_x; + g->cur_y = g->start_y; + + // if the width of the specified rectangle is 0, that means + // we may not see *any* pixels or the image is malformed; + // to make sure this is caught, move the current y down to + // max_y (which is what out_gif_code checks). + if (w == 0) + g->cur_y = g->max_y; + + g->lflags = stbi__get8(s); + + if (g->lflags & 0x40) { + g->step = 8 * g->line_size; // first interlaced spacing + g->parse = 3; + } else { + g->step = g->line_size; + g->parse = 0; + } + + if (g->lflags & 0x80) { + stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); + g->color_table = (stbi_uc *) g->lpal; + } else if (g->flags & 0x80) { + g->color_table = (stbi_uc *) g->pal; + } else + return stbi__errpuc("missing color table", "Corrupt GIF"); + + o = stbi__process_gif_raster(s, g); + if (!o) return NULL; + + // if this was the first frame, + pcount = g->w * g->h; + if (first_frame && (g->bgindex > 0)) { + // if first frame, any pixel not drawn to gets the background color + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi] == 0) { + g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; + memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); + } + } + } + + return o; + } + + case 0x21: // Comment Extension. + { + int len; + int ext = stbi__get8(s); + if (ext == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. + + // unset old transparent + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 255; + } + if (g->eflags & 0x01) { + g->transparent = stbi__get8(s); + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 0; + } + } else { + // don't need transparent + stbi__skip(s, 1); + g->transparent = -1; + } + } else { + stbi__skip(s, len); + break; + } + } + while ((len = stbi__get8(s)) != 0) { + stbi__skip(s, len); + } + break; + } + + case 0x3B: // gif stream termination code + return (stbi_uc *) s; // using '1' causes warning on some compilers + + default: + return stbi__errpuc("unknown code", "Corrupt GIF"); + } + } +} + +static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays) +{ + STBI_FREE(g->out); + STBI_FREE(g->history); + STBI_FREE(g->background); + + if (out) STBI_FREE(out); + if (delays && *delays) STBI_FREE(*delays); + return stbi__errpuc("outofmem", "Out of memory"); +} + +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + if (stbi__gif_test(s)) { + int layers = 0; + stbi_uc *u = 0; + stbi_uc *out = 0; + stbi_uc *two_back = 0; + stbi__gif g; + int stride; + int out_size = 0; + int delays_size = 0; + + STBI_NOTUSED(out_size); + STBI_NOTUSED(delays_size); + + memset(&g, 0, sizeof(g)); + if (delays) { + *delays = 0; + } + + do { + u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + + if (u) { + *x = g.w; + *y = g.h; + ++layers; + stride = g.w * g.h * 4; + + if (out) { + void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); + if (!tmp) + return stbi__load_gif_main_outofmem(&g, out, delays); + else { + out = (stbi_uc*) tmp; + out_size = layers * stride; + } + + if (delays) { + int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); + if (!new_delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + *delays = new_delays; + delays_size = layers * sizeof(int); + } + } else { + out = (stbi_uc*)stbi__malloc( layers * stride ); + if (!out) + return stbi__load_gif_main_outofmem(&g, out, delays); + out_size = layers * stride; + if (delays) { + *delays = (int*) stbi__malloc( layers * sizeof(int) ); + if (!*delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + delays_size = layers * sizeof(int); + } + } + memcpy( out + ((layers - 1) * stride), u, stride ); + if (layers >= 2) { + two_back = out - 2 * stride; + } + + if (delays) { + (*delays)[layers - 1U] = g.delay; + } + } + } while (u != 0); + + // free temp buffer; + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + + // do the final conversion after loading everything; + if (req_comp && req_comp != 4) + out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); + + *z = layers; + return out; + } else { + return stbi__errpuc("not GIF", "Image was not as a gif type."); + } +} + +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *u = 0; + stbi__gif g; + memset(&g, 0, sizeof(g)); + STBI_NOTUSED(ri); + + u = stbi__gif_load_next(s, &g, comp, req_comp, 0); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + if (u) { + *x = g.w; + *y = g.h; + + // moved conversion to after successful load so that the same + // can be done for multiple frames. + if (req_comp && req_comp != 4) + u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + } else if (g.out) { + // if there was an error and we allocated an image buffer, free it! + STBI_FREE(g.out); + } + + // free buffers needed for multiple frame loading; + STBI_FREE(g.history); + STBI_FREE(g.background); + + return u; +} + +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) +{ + return stbi__gif_info_raw(s,x,y,comp); +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR loader +// originally by Nicolas Schulz +#ifndef STBI_NO_HDR +static int stbi__hdr_test_core(stbi__context *s, const char *signature) +{ + int i; + for (i=0; signature[i]; ++i) + if (stbi__get8(s) != signature[i]) + return 0; + stbi__rewind(s); + return 1; +} + +static int stbi__hdr_test(stbi__context* s) +{ + int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); + stbi__rewind(s); + if(!r) { + r = stbi__hdr_test_core(s, "#?RGBE\n"); + stbi__rewind(s); + } + return r; +} + +#define STBI__HDR_BUFLEN 1024 +static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) +{ + int len=0; + char c = '\0'; + + c = (char) stbi__get8(z); + + while (!stbi__at_eof(z) && c != '\n') { + buffer[len++] = c; + if (len == STBI__HDR_BUFLEN-1) { + // flush to end of line + while (!stbi__at_eof(z) && stbi__get8(z) != '\n') + ; + break; + } + c = (char) stbi__get8(z); + } + + buffer[len] = 0; + return buffer; +} + +static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) +{ + if ( input[3] != 0 ) { + float f1; + // Exponent + f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); + if (req_comp <= 2) + output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + else { + output[0] = input[0] * f1; + output[1] = input[1] * f1; + output[2] = input[2] * f1; + } + if (req_comp == 2) output[1] = 1; + if (req_comp == 4) output[3] = 1; + } else { + switch (req_comp) { + case 4: output[3] = 1; /* fallthrough */ + case 3: output[0] = output[1] = output[2] = 0; + break; + case 2: output[1] = 1; /* fallthrough */ + case 1: output[0] = 0; + break; + } + } +} + +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int width, height; + stbi_uc *scanline; + float *hdr_data; + int len; + unsigned char count, value; + int i, j, k, c1,c2, z; + const char *headerToken; + STBI_NOTUSED(ri); + + // Check identifier + headerToken = stbi__hdr_gettoken(s,buffer); + if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) + return stbi__errpf("not HDR", "Corrupt HDR image"); + + // Parse header + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); + + // Parse width and height + // can't use sscanf() if we're not using stdio! + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + height = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + width = (int) strtol(token, NULL, 10); + + if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + + *x = width; + *y = height; + + if (comp) *comp = 3; + if (req_comp == 0) req_comp = 3; + + if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) + return stbi__errpf("too large", "HDR image is too large"); + + // Read data + hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); + if (!hdr_data) + return stbi__errpf("outofmem", "Out of memory"); + + // Load image data + // image data is stored as some number of sca + if ( width < 8 || width >= 32768) { + // Read flat data + for (j=0; j < height; ++j) { + for (i=0; i < width; ++i) { + stbi_uc rgbe[4]; + main_decode_loop: + stbi__getn(s, rgbe, 4); + stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); + } + } + } else { + // Read RLE-encoded data + scanline = NULL; + + for (j = 0; j < height; ++j) { + c1 = stbi__get8(s); + c2 = stbi__get8(s); + len = stbi__get8(s); + if (c1 != 2 || c2 != 2 || (len & 0x80)) { + // not run-length encoded, so we have to actually use THIS data as a decoded + // pixel (note this can't be a valid pixel--one of RGB must be >= 128) + stbi_uc rgbe[4]; + rgbe[0] = (stbi_uc) c1; + rgbe[1] = (stbi_uc) c2; + rgbe[2] = (stbi_uc) len; + rgbe[3] = (stbi_uc) stbi__get8(s); + stbi__hdr_convert(hdr_data, rgbe, req_comp); + i = 1; + j = 0; + STBI_FREE(scanline); + goto main_decode_loop; // yes, this makes no sense + } + len <<= 8; + len |= stbi__get8(s); + if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } + if (scanline == NULL) { + scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); + if (!scanline) { + STBI_FREE(hdr_data); + return stbi__errpf("outofmem", "Out of memory"); + } + } + + for (k = 0; k < 4; ++k) { + int nleft; + i = 0; + while ((nleft = width - i) > 0) { + count = stbi__get8(s); + if (count > 128) { + // Run + value = stbi__get8(s); + count -= 128; + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = value; + } else { + // Dump + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = stbi__get8(s); + } + } + } + for (i=0; i < width; ++i) + stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); + } + if (scanline) + STBI_FREE(scanline); + } + + return hdr_data; +} + +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int dummy; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (stbi__hdr_test(s) == 0) { + stbi__rewind( s ); + return 0; + } + + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) { + stbi__rewind( s ); + return 0; + } + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *y = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *x = (int) strtol(token, NULL, 10); + *comp = 3; + return 1; +} +#endif // STBI_NO_HDR + +#ifndef STBI_NO_BMP +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) +{ + void *p; + stbi__bmp_data info; + + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + if (p == NULL) { + stbi__rewind( s ); + return 0; + } + if (x) *x = s->img_x; + if (y) *y = s->img_y; + if (comp) { + if (info.bpp == 24 && info.ma == 0xff000000) + *comp = 3; + else + *comp = info.ma ? 4 : 3; + } + return 1; +} +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) +{ + int channelCount, dummy, depth; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + *y = stbi__get32be(s); + *x = stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 8 && depth != 16) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind( s ); + return 0; + } + *comp = 4; + return 1; +} + +static int stbi__psd_is16(stbi__context *s) +{ + int channelCount, depth; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + STBI_NOTUSED(stbi__get32be(s)); + STBI_NOTUSED(stbi__get32be(s)); + depth = stbi__get16be(s); + if (depth != 16) { + stbi__rewind( s ); + return 0; + } + return 1; +} +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) +{ + int act_comp=0,num_packets=0,chained,dummy; + stbi__pic_packet packets[10]; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { + stbi__rewind(s); + return 0; + } + + stbi__skip(s, 88); + + *x = stbi__get16be(s); + *y = stbi__get16be(s); + if (stbi__at_eof(s)) { + stbi__rewind( s); + return 0; + } + if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { + stbi__rewind( s ); + return 0; + } + + stbi__skip(s, 8); + + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return 0; + + packet = &packets[num_packets++]; + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + act_comp |= packet->channel; + + if (stbi__at_eof(s)) { + stbi__rewind( s ); + return 0; + } + if (packet->size != 8) { + stbi__rewind( s ); + return 0; + } + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); + + return 1; +} +#endif + +// ************************************************************************************************* +// Portable Gray Map and Portable Pixel Map loader +// by Ken Miller +// +// PGM: http://netpbm.sourceforge.net/doc/pgm.html +// PPM: http://netpbm.sourceforge.net/doc/ppm.html +// +// Known limitations: +// Does not support comments in the header section +// Does not support ASCII image data (formats P2 and P3) + +#ifndef STBI_NO_PNM + +static int stbi__pnm_test(stbi__context *s) +{ + char p, t; + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind( s ); + return 0; + } + return 1; +} + +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + STBI_NOTUSED(ri); + + ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n); + if (ri->bits_per_channel == 0) + return 0; + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + + if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) + return stbi__errpuc("too large", "PNM too large"); + + out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { + STBI_FREE(out); + return stbi__errpuc("bad PNM", "PNM file truncated"); + } + + if (req_comp && req_comp != s->img_n) { + if (ri->bits_per_channel == 16) { + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y); + } else { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + } + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + return out; +} + +static int stbi__pnm_isspace(char c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; +} + +static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) +{ + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char) stbi__get8(s); + + if (stbi__at_eof(s) || *c != '#') + break; + + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) + *c = (char) stbi__get8(s); + } +} + +static int stbi__pnm_isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static int stbi__pnm_getinteger(stbi__context *s, char *c) +{ + int value = 0; + + while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { + value = value*10 + (*c - '0'); + *c = (char) stbi__get8(s); + if((value > 214748364) || (value == 214748364 && *c > '7')) + return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int"); + } + + return value; +} + +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) +{ + int maxv, dummy; + char c, p, t; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + stbi__rewind(s); + + // Get identifier + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + + *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm + + c = (char) stbi__get8(s); + stbi__pnm_skip_whitespace(s, &c); + + *x = stbi__pnm_getinteger(s, &c); // read width + if(*x == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + *y = stbi__pnm_getinteger(s, &c); // read height + if (*y == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + maxv = stbi__pnm_getinteger(s, &c); // read max value + if (maxv > 65535) + return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images"); + else if (maxv > 255) + return 16; + else + return 8; +} + +static int stbi__pnm_is16(stbi__context *s) +{ + if (stbi__pnm_info(s, NULL, NULL, NULL) == 16) + return 1; + return 0; +} +#endif + +static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) +{ + #ifndef STBI_NO_JPEG + if (stbi__jpeg_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNG + if (stbi__png_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_GIF + if (stbi__gif_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_BMP + if (stbi__bmp_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PIC + if (stbi__pic_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_info(s, x, y, comp)) return 1; + #endif + + // test tga last because it's a crappy test! + #ifndef STBI_NO_TGA + if (stbi__tga_info(s, x, y, comp)) + return 1; + #endif + return stbi__err("unknown image type", "Image not of any known type, or corrupt"); +} + +static int stbi__is_16_main(stbi__context *s) +{ + #ifndef STBI_NO_PNG + if (stbi__png_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_is16(s)) return 1; + #endif + return 0; +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_info_from_file(f, x, y, comp); + fclose(f); + return result; +} + +STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__info_main(&s,x,y,comp); + fseek(f,pos,SEEK_SET); + return r; +} + +STBIDEF int stbi_is_16_bit(char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_is_16_bit_from_file(f); + fclose(f); + return result; +} + +STBIDEF int stbi_is_16_bit_from_file(FILE *f) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__is_16_main(&s); + fseek(f,pos,SEEK_SET); + return r; +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__is_16_main(&s); +} + +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__is_16_main(&s); +} + +#endif // STB_IMAGE_IMPLEMENTATION + +/* + revision history: + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug + 1-bit BMP + *_is_16_bit api + avoid warnings + 2.16 (2017-07-23) all functions have 16-bit variants; + STBI_NO_STDIO works again; + compilation fixes; + fix rounding in unpremultiply; + optimize vertical flip; + disable raw_len validation; + documentation fixes + 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; + warning fixes; disable run-time SSE detection on gcc; + uniform handling of optional "return" values; + thread-safe initialization of zlib tables + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) allocate large structures on the stack + remove white matting for transparent PSD + fix reported channel count for PNG & BMP + re-enable SSE2 in non-gcc 64-bit + support RGB-formatted JPEG + read 16-bit PNGs (only as 8-bit) + 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED + 2.09 (2016-01-16) allow comments in PNM files + 16-bit-per-pixel TGA (not bit-per-component) + info() for TGA could break due to .hdr handling + info() for BMP to shares code instead of sloppy parse + can use STBI_REALLOC_SIZED if allocator doesn't support realloc + code cleanup + 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA + 2.07 (2015-09-13) fix compiler warnings + partial animated GIF support + limited 16-bpc PSD support + #ifdef unused functions + bug with < 92 byte PIC,PNM,HDR,TGA + 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value + 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning + 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit + 2.03 (2015-04-12) extra corruption checking (mmozeiko) + stbi_set_flip_vertically_on_load (nguillemot) + fix NEON support; fix mingw support + 2.02 (2015-01-19) fix incorrect assert, fix warning + 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 + 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG + 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) + progressive JPEG (stb) + PGM/PPM support (Ken Miller) + STBI_MALLOC,STBI_REALLOC,STBI_FREE + GIF bugfix -- seemingly never worked + STBI_NO_*, STBI_ONLY_* + 1.48 (2014-12-14) fix incorrectly-named assert() + 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) + optimize PNG (ryg) + fix bug in interlaced PNG with user-specified channel count (stb) + 1.46 (2014-08-26) + fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG + 1.45 (2014-08-16) + fix MSVC-ARM internal compiler error by wrapping malloc + 1.44 (2014-08-07) + various warning fixes from Ronny Chevalier + 1.43 (2014-07-15) + fix MSVC-only compiler problem in code changed in 1.42 + 1.42 (2014-07-09) + don't define _CRT_SECURE_NO_WARNINGS (affects user code) + fixes to stbi__cleanup_jpeg path + added STBI_ASSERT to avoid requiring assert.h + 1.41 (2014-06-25) + fix search&replace from 1.36 that messed up comments/error messages + 1.40 (2014-06-22) + fix gcc struct-initialization warning + 1.39 (2014-06-15) + fix to TGA optimization when req_comp != number of components in TGA; + fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) + add support for BMP version 5 (more ignored fields) + 1.38 (2014-06-06) + suppress MSVC warnings on integer casts truncating values + fix accidental rename of 'skip' field of I/O + 1.37 (2014-06-04) + remove duplicate typedef + 1.36 (2014-06-03) + convert to header file single-file library + if de-iphone isn't set, load iphone images color-swapped instead of returning NULL + 1.35 (2014-05-27) + various warnings + fix broken STBI_SIMD path + fix bug where stbi_load_from_file no longer left file pointer in correct place + fix broken non-easy path for 32-bit BMP (possibly never used) + TGA optimization by Arseny Kapoulkine + 1.34 (unknown) + use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case + 1.33 (2011-07-14) + make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements + 1.32 (2011-07-13) + support for "info" function for all supported filetypes (SpartanJ) + 1.31 (2011-06-20) + a few more leak fixes, bug in PNG handling (SpartanJ) + 1.30 (2011-06-11) + added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) + removed deprecated format-specific test/load functions + removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway + error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) + fix inefficiency in decoding 32-bit BMP (David Woo) + 1.29 (2010-08-16) + various warning fixes from Aurelien Pocheville + 1.28 (2010-08-01) + fix bug in GIF palette transparency (SpartanJ) + 1.27 (2010-08-01) + cast-to-stbi_uc to fix warnings + 1.26 (2010-07-24) + fix bug in file buffering for PNG reported by SpartanJ + 1.25 (2010-07-17) + refix trans_data warning (Won Chun) + 1.24 (2010-07-12) + perf improvements reading from files on platforms with lock-heavy fgetc() + minor perf improvements for jpeg + deprecated type-specific functions so we'll get feedback if they're needed + attempt to fix trans_data warning (Won Chun) + 1.23 fixed bug in iPhone support + 1.22 (2010-07-10) + removed image *writing* support + stbi_info support from Jetro Lauha + GIF support from Jean-Marc Lienher + iPhone PNG-extensions from James Brown + warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) + 1.21 fix use of 'stbi_uc' in header (reported by jon blow) + 1.20 added support for Softimage PIC, by Tom Seddon + 1.19 bug in interlaced PNG corruption check (found by ryg) + 1.18 (2008-08-02) + fix a threading bug (local mutable static) + 1.17 support interlaced PNG + 1.16 major bugfix - stbi__convert_format converted one too many pixels + 1.15 initialize some fields for thread safety + 1.14 fix threadsafe conversion bug + header-file-only version (#define STBI_HEADER_FILE_ONLY before including) + 1.13 threadsafe + 1.12 const qualifiers in the API + 1.11 Support installable IDCT, colorspace conversion routines + 1.10 Fixes for 64-bit (don't use "unsigned long") + optimized upsampling by Fabian "ryg" Giesen + 1.09 Fix format-conversion for PSD code (bad global variables!) + 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz + 1.07 attempt to fix C++ warning/errors again + 1.06 attempt to fix C++ warning/errors again + 1.05 fix TGA loading to return correct *comp and use good luminance calc + 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free + 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR + 1.02 support for (subset of) HDR files, float interface for preferred access to them + 1.01 fix bug: possible bug in handling right-side up bmps... not sure + fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all + 1.00 interface to zlib that skips zlib header + 0.99 correct handling of alpha in palette + 0.98 TGA loader by lonesock; dynamically add loaders (untested) + 0.97 jpeg errors on too large a file; also catch another malloc failure + 0.96 fix detection of invalid v value - particleman@mollyrocket forum + 0.95 during header scan, seek to markers in case of padding + 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same + 0.93 handle jpegtran output; verbose errors + 0.92 read 4,8,16,24,32-bit BMP files of several formats + 0.91 output 24-bit Windows 3.0 BMP files + 0.90 fix a few more warnings; bump version number to approach 1.0 + 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd + 0.60 fix compiling as c++ + 0.59 fix warnings: merge Dave Moore's -Wall fixes + 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian + 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available + 0.56 fix bug: zlib uncompressed mode len vs. nlen + 0.55 fix bug: restart_interval not initialized to 0 + 0.54 allow NULL for 'int *comp' + 0.53 fix bug in png 3->4; speedup png decoding + 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments + 0.51 obey req_comp requests, 1-component jpegs return as 1-component, + on 'test' only check type, not whether we support this variant + 0.50 (2006-11-19) + first released version +*/ + + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ From ff7cc227a517e03d70a32dc5b973b32d99320de7 Mon Sep 17 00:00:00 2001 From: BobClawblaw Date: Mon, 12 Oct 2026 03:00:21 +0000 Subject: [PATCH 08/17] Native image input for Qwen3.8-27B on CUDA: tower rows spliced into the prompt pass, M-RoPE positions - Media (vision.zig): the request's images encoded, each prompt row's feature row, and get_rope_index's three positions; rope_delta kept on the stream for decode and verify positions (the drafter's stay plain, as 0.6.6's do) - Forward.chunk: image rows take the tower's rows; a chunk holding them runs attn_prep with three position rows (qwen_vision.cu), others the captured kernel at their shifted 1-D positions - native/cuda.zig: --vision for families that serve it (Info.vision from the family's prepareImage and markers), the tower's call scratch kept out of the streams' room; other CUDA families refuse --vision - JPEGs through libturbojpeg when it loads (PIL's decoder): patches equal 0.6.6's on every fixture, PNG and JPEG - aot: a launch with no exact captured variant takes one that assumes less of its arguments; the 27B's attention plan segments start on 16-byte boundaries, as the Python engine's tensors do Checked on an RTX 5090 against 0.6.6: prompt token counts equal on five image requests, three replies word for word, text exactness unchanged (serial 4/4, windows 54/54, drafted 4/4, shared rounds 6/6), concurrent text replies equal solo beside an image request. --- zig/kernels/cuda/qwen_vision.cu | 43 ++++++++ zig/src/cuda/aot.zig | 33 +++++- zig/src/families/qwen27/cuda/engine.zig | 9 ++ zig/src/families/qwen27/cuda/forward.zig | 24 +++- zig/src/families/qwen27/cuda/image.zig | 68 +++++++++++- zig/src/families/qwen27/cuda/lanes.zig | 13 ++- zig/src/families/qwen27/cuda/lone.zig | 10 ++ zig/src/families/qwen27/cuda/native.zig | 32 +++++- zig/src/families/qwen27/cuda/round.zig | 34 ++++-- zig/src/families/qwen27/cuda/state.zig | 9 +- zig/src/families/qwen27/cuda/vision.zig | 134 +++++++++++++++++++++++ zig/src/native/cuda.zig | 27 ++++- 12 files changed, 408 insertions(+), 28 deletions(-) diff --git a/zig/kernels/cuda/qwen_vision.cu b/zig/kernels/cuda/qwen_vision.cu index 9b1a73db9d..fe3999a5b3 100644 --- a/zig/kernels/cuda/qwen_vision.cu +++ b/zig/kernels/cuda/qwen_vision.cu @@ -206,3 +206,46 @@ extern "C" __global__ void __launch_bounds__(256) tf_qv_splice(__nv_bfloat16* __ if (s < 0) return; for (int i = threadIdx.x; i < D; i += blockDim.x) x[row * D + i] = features[static_cast(s) * D + i]; } + +// glue._attn_prep with MROPE (0.6.6's Triton kernel, three position rows): each head's q (from the [q | gate] rows) +// or k RMS-normed to bf16, then rotate-half over the first 2 * HALF dims, frequency i taking the t, h or w position +// by Qwen's interleaved sections (axis 1 where i % 3 == 1 and i < 3 * hsec, axis 2 where i % 3 == 2 and +// i < 3 * wsec, else axis 0). A block of D threads a (row, head); pos is [3][rows]. +extern "C" __global__ void __launch_bounds__(256) tf_qv_attn_prep_mrope( + const __nv_bfloat16* __restrict__ qg, const __nv_bfloat16* __restrict__ kv, const __nv_bfloat16* __restrict__ qn, + const __nv_bfloat16* __restrict__ kn, const int* __restrict__ pos, const float* __restrict__ inv, + __nv_bfloat16* __restrict__ qout, __nv_bfloat16* __restrict__ kout, float eps, int H, int HKV, int D, int HALF, + int rows, int hsec, int wsec) { + __shared__ float part[8]; + __shared__ float vals[256]; + const int row = blockIdx.x; + const int head = blockIdx.y; + const int d = threadIdx.x; + const bool is_q = head < H; + const __nv_bfloat16* src = is_q ? qg + (static_cast(row) * H + head) * 2 * D + : kv + (static_cast(row) * HKV + head - H) * D; + const __nv_bfloat16* wn = is_q ? qn : kn; + const float x = bf(src[d]); + float s = x * x; + for (int o = 16; o; o >>= 1) s += __shfl_xor_sync(0xffffffffu, s, o); + if ((d & 31) == 0) part[d >> 5] = s; + __syncthreads(); + float tot = 0.0f; + for (int i = 0; i < (D >> 5); ++i) tot += part[i]; + const float r = 1.0f / sqrtf(tot / D + eps); + const float xn = rnd(x * r * bf(wn[d])); + vals[d] = xn; + __syncthreads(); + float out = xn; + if (d < 2 * HALF) { + const int i = d < HALF ? d : d - HALF; + const int axis = (i % 3 == 1 && i < 3 * hsec) ? 1 : ((i % 3 == 2 && i < 3 * wsec) ? 2 : 0); + const float ang = static_cast(pos[axis * rows + row]) * inv[i]; + const float cs = cosf(ang), sn = sinf(ang); + const float xp = vals[d < HALF ? d + HALF : d - HALF]; + out = d < HALF ? xn * cs - xp * sn : xn * cs + xp * sn; + } + __nv_bfloat16* dst = is_q ? qout + (static_cast(row) * H + head) * D + : kout + (static_cast(row) * HKV + head - H) * D; + dst[d] = __float2bfloat16_rn(out); +} diff --git a/zig/src/cuda/aot.zig b/zig/src/cuda/aot.zig index b8e58d2e8e..924893dc2e 100644 --- a/zig/src/cuda/aot.zig +++ b/zig/src/cuda/aot.zig @@ -122,7 +122,13 @@ pub const Set = struct { pub fn find(self: *const Set, function: []const u8, args: []const Arg, consts: []const Const) !*const Variant { for (self.variants) |*v| { if (!std.mem.eql(u8, v.spec.@"fn", function)) continue; - if (matches(v.spec, args, consts)) return v; + if (matches(v.spec, args, consts, .exact)) return v; + } + // a variant that assumes less of an argument than this launch gives (no 16-divisibility it has, or a runtime + // int where Triton would fold a 1) computes the same for it: Triton specializes for speed, not for values + for (self.variants) |*v| { + if (!std.mem.eql(u8, v.spec.@"fn", function)) continue; + if (matches(v.spec, args, consts, .general)) return v; } std.log.err("no captured Triton variant of {s} for this launch:", .{function}); for (args) |a| switch (a.value) { @@ -167,7 +173,9 @@ fn lookup(args: []const Arg, name: []const u8) ?Arg { return null; } -fn matches(k: KernelJson, args: []const Arg, consts: []const Const) bool { +const Fit = enum { exact, general }; + +fn matches(k: KernelJson, args: []const Arg, consts: []const Const, fit: Fit) bool { for (consts) |c| { const got = k.consts.map.get(c.name) orelse return false; if (c.int) |x| if (got.int == null or got.int.? != x) return false; @@ -188,12 +196,20 @@ fn matches(k: KernelJson, args: []const Arg, consts: []const Const) bool { } const p = param.?; if (!std.mem.eql(u8, p.type, "i32")) return false; - if (!p.nospec and x == 1) return false; - if (p.div16 != (!p.nospec and @mod(x, 16) == 0)) return false; + const div = !p.nospec and @mod(x, 16) == 0; + switch (fit) { + .exact => if ((!p.nospec and x == 1) or p.div16 != div) return false, + .general => if (p.div16 and !div) return false, + } }, .ptr => |x| { const p = param orelse return false; - if (!std.mem.eql(u8, p.type, x.ty) or p.div16 != (x.addr % 16 == 0)) return false; + if (!std.mem.eql(u8, p.type, x.ty)) return false; + const div = x.addr % 16 == 0; + switch (fit) { + .exact => if (p.div16 != div) return false, + .general => if (p.div16 and !div) return false, + } }, .f32 => { const p = param orelse return false; @@ -201,7 +217,12 @@ fn matches(k: KernelJson, args: []const Arg, consts: []const Const) bool { }, .u64 => |x| { const p = param orelse return false; - if (!std.mem.eql(u8, p.type, "u64") or p.div16 != (x % 16 == 0)) return false; + if (!std.mem.eql(u8, p.type, "u64")) return false; + const div = x % 16 == 0; + switch (fit) { + .exact => if (p.div16 != div) return false, + .general => if (p.div16 and !div) return false, + } }, } runtime += 1; diff --git a/zig/src/families/qwen27/cuda/engine.zig b/zig/src/families/qwen27/cuda/engine.zig index 52576d7cd3..daff994c44 100644 --- a/zig/src/families/qwen27/cuda/engine.zig +++ b/zig/src/families/qwen27/cuda/engine.zig @@ -6,6 +6,7 @@ const c = @import("shape.zig"); const kern = @import("kernels.zig"); const tri = @import("triton.zig"); const st = @import("state.zig"); +const vision = @import("vision.zig"); const wts = @import("weights.zig"); const Forward = @import("forward.zig").Forward; const Part = @import("forward.zig").Part; @@ -73,15 +74,23 @@ pub const Engine = struct { /// prefill_state from an empty state: the prompt in even chunks of at most `prompt_rows`, its last row normed. pub fn prefill(e: *Engine, seq: *st.Seq, prompt: []const u32) !void { + return e.prefillMedia(seq, prompt, null); + } + + /// prefill with an image prompt's rows and positions (null: text); its decode offset stays on the stream. + pub fn prefillMedia(e: *Engine, seq: *st.Seq, prompt: []const u32, media: ?*const vision.Media) !void { if (prompt.len == 0) return error.EmptyPrompt; if (prompt.len >= seq.capacity) return error.PromptTooLong; try seq.reset(e.ops(), e.w.g); + seq.media = media; + defer seq.media = null; var f = e.forward(); const n = (prompt.len + prompt_rows - 1) / prompt_rows; for (0..n) |j| { const b = chunkBounds(0, prompt.len, prompt_rows, j); try f.chunk(prompt[b[0]..b[1]], seq, j == n - 1); } + if (media) |m| seq.rope_delta = m.delta; } /// decode.serial_decode, greedy: one-row windows from `pending` until `count` tokens or an end token. diff --git a/zig/src/families/qwen27/cuda/forward.zig b/zig/src/families/qwen27/cuda/forward.zig index 4e4964be4e..3777e8f6aa 100644 --- a/zig/src/families/qwen27/cuda/forward.zig +++ b/zig/src/families/qwen27/cuda/forward.zig @@ -7,6 +7,7 @@ const tri = @import("triton.zig"); const st = @import("state.zig"); const wts = @import("weights.zig"); const rnd = @import("round.zig"); +const vision = @import("vision.zig"); const bf = 2; pub const Part = rnd.Part; @@ -41,6 +42,10 @@ pub const Forward = struct { return .{ .heads = f.g().query_heads, .kv_heads = f.g().kv_heads, .dim = c.head_dim, .half = c.rotary_dim / 2 }; } + fn gpu(f: *const Forward) vision.Gpu { + return .{ .d = f.ops.k.d, .s = f.ops.s, .discrete = f.ops.k.discrete }; + } + fn upload32(f: *Forward, dst: u64, values: []const i32) !void { try f.ops.upload(dst, std.mem.sliceAsBytes(values)); try f.ops.s.synchronize(); // the host copy must outlive the async upload @@ -225,7 +230,8 @@ pub const Forward = struct { defer f.gpa.free(host); for (ids, 0..) |tok, r| { host[r] = @intCast(tok); - host[W + r] = @intCast(p0 + r); + // an image prompt's text rows: their three positions are equal, so one row of them is theirs + host[W + r] = if (seq.media) |m| m.pos[p0 + r] else @intCast(p0 + r); for (0..c.conv_taps) |j| host[2 * W + r * c.conv_taps + j] = @intCast(r + j); } try f.upload32(s.ids, host[0..W]); @@ -233,6 +239,17 @@ pub const Forward = struct { try f.upload32(s.windows, host[2 * W ..]); } try f.t.embed(s.ids, w.embed.w, w.embed.s, w.embed.b, s.x, W, g_.hidden); + // rows of an image take the tower's rows, and the chunk's attention their three positions + const media: ?*const vision.Media = if (seq.media) |m| (if (m.hasImage(p0, W)) m else null) else null; + if (media) |m| { + const n = m.src.len; + const host = try f.gpa.alloc(i32, 4 * W); + defer f.gpa.free(host); + @memcpy(host[0..W], m.src[p0..][0..W]); + for (0..3) |a| @memcpy(host[W + a * W ..][0..W], m.pos[a * n + p0 ..][0..W]); + try f.upload32(m.dev.ptr, host); + try m.tower.splice(f.gpu(), s.x, m.features.ptr, m.dev.ptr, W); + } var x = s.x; var pending: ?u64 = null; const kv = g_.kvInner() * bf; @@ -263,7 +280,10 @@ pub const Forward = struct { try f.ops.prefillDense(s.y, a.q, s.qg, W); try f.ops.prefillDense(s.y, a.k, s.key, W); try f.ops.prefillDense(s.y, a.v, seq.values[i] + p0 * kv, W); - try f.t.attnPrep(s.qg, s.key, a.q_norm, a.k_norm, s.pos, w.inv_freq, s.q_rot, seq.keys[i] + p0 * kv, W, f.attnShape(), c.eps); + if (media) |m| { + const sh = f.attnShape(); + try m.tower.attnPrep(f.gpu(), s.qg, s.key, a.q_norm, a.k_norm, m.dev.ptr + W * 4, w.inv_freq, s.q_rot, seq.keys[i] + p0 * kv, W, .{ .heads = sh.heads, .kv_heads = sh.kv_heads, .dim = sh.dim, .half = sh.half }, c.eps); + } else try f.t.attnPrep(s.qg, s.key, a.q_norm, a.k_norm, s.pos, w.inv_freq, s.q_rot, seq.keys[i] + p0 * kv, W, f.attnShape(), c.eps); const scale: f32 = @floatCast(std.math.pow(f64, c.head_dim, -0.5)); try f.ops.prefillAttention(s.q_rot, seq.keys[i], seq.values[i], s.attn, p0, W, g_.query_heads, g_.kv_heads, scale); try f.t.gateMul(s.attn, s.qg, s.gated, s.gated_xs, W, g_.query_heads, c.head_dim); diff --git a/zig/src/families/qwen27/cuda/image.zig b/zig/src/families/qwen27/cuda/image.zig index 0546e66e8c..736e6960c1 100644 --- a/zig/src/families/qwen27/cuda/image.zig +++ b/zig/src/families/qwen27/cuda/image.zig @@ -3,7 +3,8 @@ //! alpha composited over white with PIL's integer blend), then transformers' Qwen2VLImageProcessorPil at the caps //! 0.6.6 passes it: smart_resize to multiples of 32 within [32^2, tokens * 32^2] pixels, PIL's 8-bit bicubic //! resampler, x / 255 in float64 rounded to float32, (x - 0.5) / 0.5, and 16x16 patches in 2x2 merge order with each -//! patch's frame given twice. PNG patches equal 0.6.6's bit for bit; JPEG decoders may differ by a level. +//! patch's frame given twice. JPEGs go through libjpeg-turbo (PIL's decoder) when libturbojpeg.so.0 loads, else +//! stb_image, whose IDCT may differ from PIL's by a level. const std = @import("std"); const vision = @import("vision.zig"); @@ -108,12 +109,71 @@ pub fn patchify(gpa: std.mem.Allocator, img: Rgb) Error![]f32 { // ---- decoding (stb_image), EXIF orientation and alpha, as PIL gives images.py its RGB ---- +/// TurboJPEG's decompression API (libturbojpeg.so.0), opened on first use; null when the library is absent. +const Turbo = struct { + init: *const fn () callconv(.c) ?*anyopaque, + header: *const fn (?*anyopaque, [*]const u8, c_ulong, *c_int, *c_int, *c_int, *c_int) callconv(.c) c_int, + decompress: *const fn (?*anyopaque, [*]const u8, c_ulong, [*]u8, c_int, c_int, c_int, c_int, c_int) callconv(.c) c_int, + destroy: *const fn (?*anyopaque) callconv(.c) c_int, + + var state = std.atomic.Value(u8).init(0); // 0: not opened, 1: opening, 2: done (api set or not) + var api: ?Turbo = null; + var lib: ?std.DynLib = null; + + fn load() void { + var l = std.DynLib.open("libturbojpeg.so.0") catch return; + api = .{ + .init = l.lookup(@FieldType(Turbo, "init"), "tjInitDecompress") orelse return l.close(), + .header = l.lookup(@FieldType(Turbo, "header"), "tjDecompressHeader3") orelse return l.close(), + .decompress = l.lookup(@FieldType(Turbo, "decompress"), "tjDecompress2") orelse return l.close(), + .destroy = l.lookup(@FieldType(Turbo, "destroy"), "tjDestroy") orelse return l.close(), + }; + lib = l; + } + + fn get() ?Turbo { + if (state.cmpxchgStrong(0, 1, .acquire, .acquire) == null) { + load(); + state.store(2, .release); + } + while (state.load(.acquire) != 2) std.atomic.spinLoopHint(); + return api; + } +}; + +const tjpf_rgb = 0; +const tjcs_cmyk = 3; +const tjcs_ycck = 4; + +/// A JPEG through libjpeg-turbo as PIL decodes it (accurate integer IDCT, fancy upsampling) into RGB rows; null +/// when TurboJPEG is absent or the image is CMYK (PIL converts those itself). +fn turboJpeg(gpa: std.mem.Allocator, bytes: []const u8) Error!?Rgb { + const t = Turbo.get() orelse return null; + const h = t.init() orelse return null; + defer _ = t.destroy(h); + var w: c_int = 0; + var ht: c_int = 0; + var sub: c_int = 0; + var cs: c_int = 0; + if (t.header(h, bytes.ptr, bytes.len, &w, &ht, &sub, &cs) != 0) return error.BadImage; + if (cs == tjcs_cmyk or cs == tjcs_ycck) return null; + if (w <= 0 or ht <= 0) return error.BadImage; + if (w > max_side or ht > max_side or @as(u64, @intCast(w)) * @as(u64, @intCast(ht)) > max_pixels) return error.ImageTooLarge; + const W: usize = @intCast(w); + const H: usize = @intCast(ht); + const out = try gpa.alloc(u8, W * H * 3); + errdefer gpa.free(out); + if (t.decompress(h, bytes.ptr, bytes.len, out.ptr, w, w * 3, ht, tjpf_rgb, 0) != 0) return error.BadImage; + return .{ .w = @intCast(W), .h = @intCast(H), .px = out }; +} + /// A single-frame PNG or JPEG as 8-bit RGB: upright by its EXIF orientation, alpha composited over white, 16-bit /// gray clipped to 255 and other 16-bit layouts cut to their high byte (what PIL's convert("RGB") gives). pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) Error!Rgb { if (bytes.len < 8 or bytes.len > std.math.maxInt(c_int)) return error.BadImage; const n: c_int = @intCast(bytes.len); if (std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n") and pngAnimated(bytes)) return error.Animated; + if (std.mem.startsWith(u8, bytes, "\xff\xd8\xff")) if (try turboJpeg(gpa, bytes)) |img| return upright(gpa, img, bytes); var w: c_int = 0; var h: c_int = 0; var comp: c_int = 0; @@ -146,7 +206,11 @@ pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) Error!Rgb { } } } - const img: Rgb = .{ .w = @intCast(W), .h = @intCast(H), .px = out }; + return upright(gpa, .{ .w = @intCast(W), .h = @intCast(H), .px = out }, bytes); +} + +/// The decoded image turned upright by the EXIF orientation its bytes carry (it takes `img`). +fn upright(gpa: std.mem.Allocator, img: Rgb, bytes: []const u8) Error!Rgb { const o = orientation(bytes); if (o < 2 or o > 8) return img; defer img.deinit(gpa); diff --git a/zig/src/families/qwen27/cuda/lanes.zig b/zig/src/families/qwen27/cuda/lanes.zig index 8a5f86fad8..d88d43baf6 100644 --- a/zig/src/families/qwen27/cuda/lanes.zig +++ b/zig/src/families/qwen27/cuda/lanes.zig @@ -13,6 +13,7 @@ const dr = @import("draft.zig"); const drafts = @import("drafts.zig"); const lone = @import("lone.zig"); const trees = @import("tree.zig"); +const vision = @import("vision.zig"); const be = lanes.backend; /// The row counts calibrate times (calibration_rows without the tile steps a GB10 skips), to 16 a stream. @@ -41,6 +42,7 @@ pub const Cuda = struct { values: []f64 = &.{}, pending: Pending = .{}, drafter: ?*dr.DFlash2 = null, // DFlash2, when its checkpoint is pulled and drafts are on + tower: ?*vision.Tower = null, // the image tower, with --vision drafting: std.AutoHashMapUnmanaged(*lanes.Stream, *drafts.Stream) = .empty, costs: [calibration.len + 1]lanes.config.Cost = undefined, // the forward's ms by a round's rows (calibrate) cost_count: usize = 0, @@ -228,11 +230,18 @@ pub const Cuda = struct { /// prefill_state into an opened stream: the prompt in chunks, a drafting stream's last window of taps absorbed. fn prefillOpened(x: *Cuda, s: *lanes.Stream, seq: *st.Seq) !void { + // an image prompt: the tower's rows and the prompt's three positions for its pass (EncodedVision) + const media: ?*vision.Media = if (s.images.len == 0) null else blk: { + const tower = x.tower orelse return error.VisionDisabled; + const gpu: vision.Gpu = .{ .d = x.e.ops().k.d, .s = x.e.ops().s, .discrete = x.e.ops().k.discrete }; + break :blk try vision.Media.init(x.gpa, tower, gpu, s.prompt(), s.images, prompt_rows); + }; + defer if (media) |m| m.deinit(); if (x.drafter) |d| if (s.drafts) { const ds = try x.draftingOf(s); - return lone.prefill(x.e, seq, &ds.ctx, d, s.prompt()); + return lone.prefillMedia(x.e, seq, &ds.ctx, d, s.prompt(), media); }; - try x.e.prefill(seq, s.prompt()); + try x.e.prefillMedia(seq, s.prompt(), media); } /// prefill_batch: prompts in shared passes of at most a chunk's rows (a longer one alone, in its chunks). diff --git a/zig/src/families/qwen27/cuda/lone.zig b/zig/src/families/qwen27/cuda/lone.zig index 0397ea706f..6aa91e3fe3 100644 --- a/zig/src/families/qwen27/cuda/lone.zig +++ b/zig/src/families/qwen27/cuda/lone.zig @@ -72,7 +72,17 @@ pub const Stats = struct { rounds: usize = 0, drafted: usize = 0, accepted: usiz /// prefill_state with a drafter: the prompt in even chunks, its last `window` rows' taps into the context. pub fn prefill(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, prompt: []const u32) !void { + return prefillMedia(e, seq, ctx, d, prompt, null); +} + +/// prefill with an image prompt's rows and positions (null: text); its decode offset stays on the stream. +pub fn prefillMedia(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, prompt: []const u32, media: ?*const @import("vision.zig").Media) !void { try seq.reset(e.ops(), e.w.g); + seq.media = media; + defer seq.media = null; + defer if (media) |m| { + seq.rope_delta = m.delta; + }; ctx.len = 0; ctx.end = 0; const tap_from = prompt.len -| dl.window; diff --git a/zig/src/families/qwen27/cuda/native.zig b/zig/src/families/qwen27/cuda/native.zig index 6e3f362fdf..8b8fdd1ea0 100644 --- a/zig/src/families/qwen27/cuda/native.zig +++ b/zig/src/families/qwen27/cuda/native.zig @@ -8,6 +8,8 @@ const st = @import("state.zig"); const engine = @import("engine.zig"); const Lanes = @import("lanes.zig").Cuda; const dr = @import("draft.zig"); +const vision = @import("vision.zig"); +const image = @import("image.zig"); pub const model_type = "qwen3_5"; pub const formats: []const []const u8 = &.{"mlx-q4g64"}; @@ -15,7 +17,19 @@ pub const default_context: i64 = 32768; pub const max_segments: u32 = 1; pub const prompt_rows: u32 = engine.prompt_rows; -pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, drafter: ?[]const u8 = null }; +pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, drafter: ?[]const u8 = null, vision: ?Vision = null }; + +/// --vision's limits: the visual tokens a request's images share, and its images. +pub const Vision = struct { image_tokens: u32, max_images: u32 }; + +/// The image placeholder the chat template writes once an image, and the tokens it wraps it in. +pub const image_token = vision.image_token; +pub const image_markers = [_]u32{ vision.vision_start, vision.image_token, vision.vision_end }; + +/// Info.vision's prepare: an image's bytes to the tower's patches (image.zig), on the HTTP thread. +pub fn prepareImage(a: std.mem.Allocator, bytes: []const u8, max_tokens: u32) !image.Prepared { + return image.prepare(a, bytes, max_tokens); +} /// A lone drafted stream's own driver (none here: one stream decodes in the lane core too, as under --parallel). pub const LoneRun = *const fn (ctx: *anyopaque, s: *lanes.Stream, hooks: *anyopaque, committed: *const fn (*anyopaque) void, yield: *const fn (*anyopaque) bool) anyerror!bool; @@ -31,12 +45,14 @@ pub const Loaded = struct { free_streams: u32 = 0, /// What a --slide trainer keeps out of the streams' room (none: the 27B does not learn on CUDA yet). learn_bytes: usize = 0, + /// What the image tower keeps out of the streams' room (--vision): one call's scratch and a request's rows. + vision_bytes: usize = 0, ctx: *anyopaque, deinit: *const fn (*anyopaque) void, lone: ?LoneRun = null, }; -const Owned = struct { gpa: std.mem.Allocator, e: *engine.Engine, lanes: Lanes, draft: ?*dr.DFlash2 = null }; +const Owned = struct { gpa: std.mem.Allocator, e: *engine.Engine, lanes: Lanes, draft: ?*dr.DFlash2 = null, tower: ?*vision.Tower = null }; /// The drafter the Python engine pairs with the 27B once pulled (z-lab/Qwen3.8-27B-DFlash2). const drafter_repo = "models--z-lab--Qwen3.8-27B-DFlash2"; @@ -82,11 +98,20 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ // the forward's ms by rows: a shared round's tree widths follow the curve try own.lanes.calibrate(io, most_streams); }; + var vision_bytes: usize = 0; + if (o.vision) |v| { + const ops = e.ops(); + own.tower = try vision.Tower.load(gpa, io, .{ .d = ops.k.d, .s = ops.s, .discrete = ops.k.discrete }, dir); + own.lanes.tower = own.tower; + vision_bytes = vision.Tower.scratchBytes(vision.max_patches) + @as(usize, v.image_tokens) * vision.out_hidden * 2 + engine.prompt_rows * 16; + std.log.info("image tower loaded: {d:.2} GiB, {d:.2} GiB kept for one image call", .{ @as(f64, @floatFromInt(own.tower.?.weight_bytes)) / (1 << 30), @as(f64, @floatFromInt(vision_bytes)) / (1 << 30) }); + } return .{ .backend = own.lanes.backend(), .facts = own.lanes.facts(), .rows = st.max_rows, .stream_bytes = st.Seq.bytes(e.w.g, o.context) + if (own.draft != null) dr.Context.bytes() else 0, + .vision_bytes = vision_bytes, .ctx = own, .deinit = release, }; @@ -98,6 +123,8 @@ pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { error.PromptTooLong => "the prompt and its reply exceed this server's context window: shorten it or lower max_tokens", error.OutOfDeviceMemory => "the GPU had no memory left for this request's caches: retry once another request ends", error.QwenCheckpointHasNoDraftHead => "this checkpoint has no draft head on CUDA yet: serve with --no-drafts", + error.VisionDisabled => "image input needs this server started with --vision", + error.BadImagePlaceholders => "the image placeholders do not match the prepared images", else => null, }; } @@ -106,6 +133,7 @@ fn release(p: *anyopaque) void { const own: *Owned = @ptrCast(@alignCast(p)); own.lanes.deinit(); if (own.draft) |d| d.deinit(); + if (own.tower) |t| t.deinit(); own.e.deinit(); own.gpa.destroy(own); } diff --git a/zig/src/families/qwen27/cuda/round.zig b/zig/src/families/qwen27/cuda/round.zig index 2b2d4e2697..2354420e90 100644 --- a/zig/src/families/qwen27/cuda/round.zig +++ b/zig/src/families/qwen27/cuda/round.zig @@ -55,14 +55,27 @@ pub fn parentsOf(p: Part, buf: []i32) []const i32 { } /// attention.plan_host: rows, (first, rows, keys, slots) per stream, items, then window parents (global rows). -fn attnPlan(gpa: std.mem.Allocator, out: *std.ArrayList(i32), parts: []const Part, group: usize) !usize { +/// Where attnPlan put its segments, in ints from the plan's first: each starts on a 16-byte boundary, so the +/// attention kernels' plan pointers are the aligned ones Triton's captured variants were compiled for. +const AttnAt = struct { n_items: usize, streams: usize, items: usize, parents: usize }; + +fn pad16(out: *std.ArrayList(i32), gpa: std.mem.Allocator, from: usize) !usize { + while ((out.items.len - from) % 4 != 0) try out.append(gpa, 0); + return out.items.len - from; +} + +fn attnPlan(gpa: std.mem.Allocator, out: *std.ArrayList(i32), parts: []const Part, group: usize) !AttnAt { + const from = out.items.len; + var at: AttnAt = undefined; for (parts, 0..) |p, s| for (p.tokens) |_| try out.append(gpa, @intCast(s)); + at.streams = try pad16(out, gpa, from); var start: usize = 0; for (parts) |p| { const w = p.tokens.len; try out.appendSlice(gpa, &.{ @intCast(start), @intCast(w), @intCast(p.seq.pos), @intCast(tri.slots(p.seq.pos, w)) }); start += w; } + at.items = try pad16(out, gpa, from); var n_items: usize = 0; for (parts, 0..) |p, s| { const w = p.tokens.len; @@ -77,13 +90,15 @@ fn attnPlan(gpa: std.mem.Allocator, out: *std.ArrayList(i32), parts: []const Par } } } + at.parents = try pad16(out, gpa, from); start = 0; var buf: [tree.max_nodes]i32 = undefined; for (parts) |p| { for (parentsOf(p, &buf)) |x| try out.append(gpa, if (x < 0) -1 else @intCast(start + @as(usize, @intCast(x)))); start += p.tokens.len; } - return n_items; + at.n_items = n_items; + return at; } /// Each stream's key and value caches as bf16 element offsets from the scratch's origin. @@ -103,7 +118,7 @@ fn plans(gpa: std.mem.Allocator, parts: []const Part, starts: []const usize, mul const parents = parentsOf(p, &buf); const w = parents.len; try tree.depths(parents, dep[0..w]); - for (dep[0..w]) |d| try h.pos.append(gpa, @intCast(p.seq.pos + d)); + for (dep[0..w]) |d| try h.pos.append(gpa, @as(i32, @intCast(p.seq.pos + d)) + p.seq.rope_delta); const s = try tree.schedule(gpa, parents); defer gpa.free(s.entries); for (s.entries, 0..) |x, j| try h.entries.append(gpa, if (j % 3 == 0) x + @as(i32, @intCast(starts[k])) else x); @@ -161,7 +176,7 @@ pub fn stage(gpa: std.mem.Allocator, ops: kern.Ops, t: tri.Tri, s: *st.Scratch, try ops.upload(s.plan, std.mem.sliceAsBytes(host.items)); try ops.s.synchronize(); host.clearRetainingCapacity(); - const n_items = try attnPlan(gpa, &host, parts, group); + const ap = try attnPlan(gpa, &host, parts, group); try ops.upload(s.attn_plan, std.mem.sliceAsBytes(host.items)); try ops.s.synchronize(); for (0..g.layers) |i| try offs.appendSlice(gpa, if (c.linear(i)) &.{ 0, 0 } else &.{ offsetOf(s, p.seq.keys[i]), offsetOf(s, p.seq.values[i]) }); @@ -175,8 +190,8 @@ pub fn stage(gpa: std.mem.Allocator, ops: kern.Ops, t: tri.Tri, s: *st.Scratch, r.starts = s.plan + 3 * W * 4; r.tables = 0; r.offs = s.offs; - r.attn = .{ .rows = s.attn_plan, .streams = s.attn_plan + W * 4, .items = s.attn_plan + (W + 4) * 4, .n_items = n_items, .paths = s.paths, .depths = s.depths, .width = W }; - try t.paths(s.attn_plan + (W + 4 + 3 * n_items) * 4, s.paths, s.depths, W); + r.attn = .{ .rows = s.attn_plan, .streams = s.attn_plan + ap.streams * 4, .items = s.attn_plan + ap.items * 4, .n_items = ap.n_items, .paths = s.paths, .depths = s.depths, .width = W }; + try t.paths(s.attn_plan + ap.parents * 4, s.paths, s.depths, W); return r; } // multi_tree_forward: positions, stream ids, plan entries, starts, ids, windows, attention's plan in one copy @@ -186,8 +201,9 @@ pub fn stage(gpa: std.mem.Allocator, ops: kern.Ops, t: tri.Tri, s: *st.Scratch, for (r.starts_host[0 .. S + 1]) |x| try host.append(gpa, @intCast(x)); for (parts) |p| for (p.tokens) |tok| try host.append(gpa, @intCast(tok)); try host.appendSlice(gpa, h.windows.items); + while (host.items.len % 4 != 0) try host.append(gpa, 0); // the attention plan from a 16-byte boundary const at_attn = host.items.len; - const n_items = try attnPlan(gpa, &host, parts, group); + const ap = try attnPlan(gpa, &host, parts, group); try ops.upload(s.round, std.mem.sliceAsBytes(host.items)); try ops.s.synchronize(); const base = s.round; @@ -198,7 +214,7 @@ pub fn stage(gpa: std.mem.Allocator, ops: kern.Ops, t: tri.Tri, s: *st.Scratch, r.ids = base + (5 * W + S + 1) * 4; r.windows = base + (6 * W + S + 1) * 4; const ab = base + at_attn * 4; - r.attn = .{ .rows = ab, .streams = ab + W * 4, .items = ab + (W + 4 * S) * 4, .n_items = n_items, .paths = s.paths, .depths = s.depths, .width = W }; + r.attn = .{ .rows = ab, .streams = ab + ap.streams * 4, .items = ab + ap.items * 4, .n_items = ap.n_items, .paths = s.paths, .depths = s.depths, .width = W }; // the state pointer table and cache offsets, one copy each; every stream's conv rows stacked by layer var ptrs: std.ArrayList(u64) = .empty; defer ptrs.deinit(gpa); @@ -225,6 +241,6 @@ pub fn stage(gpa: std.mem.Allocator, ops: kern.Ops, t: tri.Tri, s: *st.Scratch, try ops.s.synchronize(); r.tables = s.tables; r.offs = s.offs; - try t.paths(ab + (W + 4 * S + 3 * n_items) * 4, s.paths, s.depths, W); + try t.paths(ab + ap.parents * 4, s.paths, s.depths, W); return r; } diff --git a/zig/src/families/qwen27/cuda/state.zig b/zig/src/families/qwen27/cuda/state.zig index 4cbe06c07e..29d276651b 100644 --- a/zig/src/families/qwen27/cuda/state.zig +++ b/zig/src/families/qwen27/cuda/state.zig @@ -5,6 +5,7 @@ const cuda = @import("cuda"); const c = @import("shape.zig"); const kern = @import("kernels.zig"); const tri = @import("triton.zig"); +const vision = @import("vision.zig"); const torch_ops = kern.torch_ops; /// The most rows a stream's verify window takes (the multi-stream GDN tree kernel's limit). @@ -51,6 +52,8 @@ pub const Seq = struct { head_xs: u64, capacity: usize, pos: usize = 0, + rope_delta: i32 = 0, // an image prompt's rotary shift past its rows (decode positions are pos + rope_delta) + media: ?*const vision.Media = null, // during an image prompt's pass: its rows and positions gpa: std.mem.Allocator, /// Device bytes a stream of `capacity` positions takes. @@ -110,6 +113,8 @@ pub const Seq = struct { try ops.fill32(s.conv[i], 0, g.convBytes() / 4); }; s.pos = 0; + s.rope_delta = 0; + s.media = null; } }; @@ -263,7 +268,7 @@ pub const Scratch = struct { s.prompt_values = try A.take(R * g.kvInner() * bf); s.windows = try A.take(R * c.conv_taps * 4); s.plan = try A.take(R * 3 * 4); - s.attn_plan = try A.take((W + 4 + 3 * items + W) * 4); + s.attn_plan = try A.take((W + 4 + 3 * items + W + 12) * 4); // + each segment's 16-byte padding s.paths = try A.take(W * tri.max_nodes * 4); s.depths = try A.take(W * 4); s.offs = try A.take(g.layers * max_streams * 2 * 8); @@ -276,7 +281,7 @@ pub const Scratch = struct { s.taps = try A.take(R * 5 * g.hidden * bf); s.replay_table = try A.take(g.layers * (4 + max_streams) * 8); s.replay_rows = try A.take(max_streams * (W + 1) * 4); - s.round = try A.take((6 * W + max_streams + 1 + W * c.conv_taps + W + 4 * max_streams + 3 * items * max_streams + W) * 4); + s.round = try A.take((6 * W + max_streams + 1 + W * c.conv_taps + 4 + W + 4 * max_streams + 3 * items * max_streams + W + 12) * 4); s.tables = try A.take(g.layers * max_streams * 8); s.conv_cat = try A.take(g.layers * max_streams * (c.conv_taps - 1) * g.convDim() * bf); for (0..g.layers) |i| { diff --git a/zig/src/families/qwen27/cuda/vision.zig b/zig/src/families/qwen27/cuda/vision.zig index 1305d9b3d6..951cff63d0 100644 --- a/zig/src/families/qwen27/cuda/vision.zig +++ b/zig/src/families/qwen27/cuda/vision.zig @@ -26,6 +26,12 @@ pub const patch_width = channels * temporal * patch * patch; // 1536 pub const grid_side = 48; // sqrt(num_position_embeddings 2304) pub const merged = hidden * merge * merge; // 4608 pub const eps: f32 = 1e-6; +/// The language model's rope_parameters.mrope_section (t, h, w frequencies, interleaved). +pub const mrope_section = [3]u32{ 11, 11, 10 }; +/// Tokens the template writes around an image, and the image placeholder it expands. +pub const vision_start: u32 = 248053; +pub const vision_end: u32 = 248054; +pub const image_token: u32 = 248056; /// One tower call's patches: a 4,096-token image's (0.6.6's MAX_PATCHES). pub const max_patches = 16384; const workspace_bytes = 32 << 20; @@ -56,6 +62,7 @@ const Fns = struct { bias_residual: cuda.Function, bias_cast: cuda.Function, splice: cuda.Function, + attn_prep: cuda.Function, }; /// The image tower's weights on the GPU and its kernels; `encode` turns patches into language-width rows. @@ -98,6 +105,7 @@ pub const Tower = struct { .bias_residual = try t.mod.function("tf_qv_bias_residual"), .bias_cast = try t.mod.function("tf_qv_bias_cast"), .splice = try t.mod.function("tf_qv_splice"), + .attn_prep = try t.mod.function("tf_qv_attn_prep_mrope"), }; errdefer t.freeBuffers(); var src = try source.Source.init(gpa, .{ .d = ops.d, .s = ops.s, .discrete = ops.discrete }); @@ -297,6 +305,11 @@ pub const Tower = struct { try t.go(ops, t.f.splice, rows, 1, 256, .{ x, features, src, int(out_hidden) }); } + /// glue.attn_prep with three position rows (pos [3][rows], device int32): normed, M-RoPE-rotated q and k. + pub fn attnPrep(t: *Tower, ops: Gpu, qg: u64, key: u64, qn: u64, kn: u64, pos: u64, inv: u64, qout: u64, kout: u64, rows: usize, a: struct { heads: usize, kv_heads: usize, dim: usize, half: usize }, eps_: f32) !void { + try t.go(ops, t.f.attn_prep, rows, a.heads + a.kv_heads, @intCast(a.dim), .{ qg, key, qn, kn, pos, inv, qout, kout, eps_, int(a.heads), int(a.kv_heads), int(a.dim), int(a.half), int(rows), int(mrope_section[1]), int(mrope_section[2]) }); + } + fn go(t: *Tower, ops: Gpu, f: cuda.Function, gx: usize, gy: usize, block: u32, args: anytype) !void { _ = t; var a: cuda.Args = .{}; @@ -395,3 +408,124 @@ test "bilinear taps match align_corners resampling at the ends and middle" { try std.testing.expectEqual(@as(i32, 47), b.i[0]); try std.testing.expectEqual(@as(f32, 1), b.w[0]); } + +/// An image prompt's rows for its prompt pass (0.6.6's EncodedVision): the tower's rows on the GPU, each prompt row's +/// feature row (or -1), the three rotary positions of every prompt row and the decode offset after the prompt. +pub const Media = struct { + gpa: std.mem.Allocator, + tower: *Tower, + features: cuda.DeviceBuffer, // bf16 [image rows, out_hidden] + src: []i32, // [prompt]: feature row or -1 + pos: []i32, // [3][prompt]: t, h, w + delta: i32, + dev: cuda.DeviceBuffer, // a chunk's src and [3][rows] positions + + /// Encodes `images` (Image.at: the first of its tokens' rows) and lays out the prompt's positions as + /// transformers' get_rope_index does: text counts up on all three axes; an image sits at the next position with + /// its merged rows and columns on the h and w axes; text after it resumes past its larger side. + pub fn init(gpa: std.mem.Allocator, tower: *Tower, ops: Gpu, prompt: []const u32, images: anytype, chunk_rows: usize) !*Media { + const n = prompt.len; + const m = try gpa.create(Media); + errdefer gpa.destroy(m); + var rows: usize = 0; + for (images) |img| rows += img.tokens; + m.* = .{ .gpa = gpa, .tower = tower, .features = try cuda.DeviceBuffer.alloc(ops.d, rows * out_hidden * 2), .src = &.{}, .pos = &.{}, .delta = 0, .dev = undefined }; + errdefer m.features.free(); + m.dev = try cuda.DeviceBuffer.alloc(ops.d, chunk_rows * 4 * 4); + errdefer m.dev.free(); + m.src = try gpa.alloc(i32, n); + errdefer gpa.free(m.src); + m.pos = try gpa.alloc(i32, 3 * n); + errdefer gpa.free(m.pos); + @memset(m.src, -1); + // the tower: runs of whole images within one call's patches, in prompt order + var done: usize = 0; // feature rows written + var i: usize = 0; + while (i < images.len) { + var j = i; + var patches: usize = 0; + while (j < images.len and (j == i or patches + images[j].gh * images[j].gw <= max_patches)) : (j += 1) patches += images[j].gh * images[j].gw; + const px = try gpa.alloc(f32, patches * patch_width); + defer gpa.free(px); + const grids = try gpa.alloc(Grid, j - i); + defer gpa.free(grids); + var at: usize = 0; + for (images[i..j], grids) |img, *g| { + if (img.pixels.len != @as(usize, img.gh) * img.gw * patch_width or img.tokens * merge * merge != img.gh * img.gw) return error.BadImagePatches; + @memcpy(px[at..][0..img.pixels.len], img.pixels); + at += img.pixels.len; + g.* = .{ .h = img.gh, .w = img.gw }; + } + try tower.encode(ops, px, grids, m.features.ptr + done * out_hidden * 2); + for (images[i..j]) |img| done += img.tokens; + i = j; + } + m.delta = try layout(prompt, images, m.src, m.pos); + return m; + } + + pub fn deinit(m: *Media) void { + m.features.free(); + m.dev.free(); + m.gpa.free(m.src); + m.gpa.free(m.pos); + m.gpa.destroy(m); + } + + /// Whether rows [p0, p0 + w) hold an image row. + pub fn hasImage(m: *const Media, p0: usize, w: usize) bool { + for (m.src[p0..][0..w]) |v| if (v >= 0) return true; + return false; + } +}; + +/// The prompt's three rotary positions ([3][n]) and each placeholder row's feature row (src, -1 for text), as +/// transformers' get_rope_index lays them out; returns the decode offset (rope_delta). +pub fn layout(prompt: []const u32, images: anytype, src: []i32, pos: []i32) !i32 { + const n = prompt.len; + @memset(src, -1); + var next: i32 = 0; + var cursor: usize = 0; + var row: i32 = 0; + for (images) |img| { + const begin: usize = img.at; + const h: usize = img.gh / merge; + const w: usize = img.gw / merge; + const end = begin + h * w; + if (begin < cursor or begin == 0 or end >= n or prompt[begin - 1] != vision_start or prompt[end] != vision_end) return error.BadImagePlaceholders; + for (prompt[begin..end]) |t| if (t != image_token) return error.BadImagePlaceholders; + for (cursor..begin) |r| { + const v = next + @as(i32, @intCast(r - cursor)); + for (0..3) |a| pos[a * n + r] = v; + } + const base = next + @as(i32, @intCast(begin - cursor)); + for (0..h * w) |k| { + const r = begin + k; + pos[r] = base; + pos[n + r] = base + @as(i32, @intCast(k / w)); + pos[2 * n + r] = base + @as(i32, @intCast(k % w)); + src[r] = row; + row += 1; + } + next = base + @as(i32, @intCast(@max(h, w))); + cursor = end; + } + for (cursor..n) |r| { + const v = next + @as(i32, @intCast(r - cursor)); + for (0..3) |a| pos[a * n + r] = v; + } + return next - @as(i32, @intCast(cursor)); +} + +test "media positions: text counts up, an image sits at one position with its grid, text resumes past its side" { + const I = struct { gh: u32, gw: u32, at: u32, tokens: u32 }; + const prompt = [_]u32{ 7, vision_start, image_token, image_token, image_token, image_token, image_token, image_token, vision_end, 9 }; + var src: [10]i32 = undefined; + var pos: [30]i32 = undefined; + const delta = try layout(&prompt, &[_]I{.{ .gh = 4, .gw = 6, .at = 2, .tokens = 6 }}, &src, &pos); + try std.testing.expectEqual(@as(i32, -3), delta); + try std.testing.expectEqualSlices(i32, &.{ 0, 1, 2, 2, 2, 2, 2, 2, 5, 6 }, pos[0..10]); + try std.testing.expectEqualSlices(i32, &.{ 0, 1, 2, 2, 2, 3, 3, 3, 5, 6 }, pos[10..20]); + try std.testing.expectEqualSlices(i32, &.{ 0, 1, 2, 3, 4, 2, 3, 4, 5, 6 }, pos[20..30]); + try std.testing.expectEqualSlices(i32, &.{ -1, -1, 0, 1, 2, 3, 4, 5, -1, -1 }, &src); +} diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 792bbb6632..ba1c01688a 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -428,6 +428,13 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O var family_options: F.Options = .{ .context = @intCast(window), .drafts = o.drafts, .segments = segments }; if (@hasField(F.Options, "slide")) family_options.slide = o.slide; if (@hasField(F.Options, "drafter")) family_options.drafter = o.drafter; + if (o.vision) |v| { + if (!@hasField(F.Options, "vision")) { + problem.* = try std.fmt.allocPrint(a, "--vision: the native CUDA engine reads images for Qwen3.8-27B only, not {s} checkpoints", .{o.model_type}); + return null; + } + family_options.vision = .{ .image_tokens = v.image_tokens, .max_images = v.max_images }; + } const loaded = F.open(gpa, io, &g.ctx, o.dir, kernels, family_options) catch |e| { problem.* = try std.fmt.allocPrint(a, "the native CUDA engine cannot load {s} with {s} glue kernels ({s})", .{ o.dir, kernels orelse "its own", @errorName(e) }); return null; @@ -435,7 +442,8 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O defer if (!opened) loaded.deinit(loaded.ctx); const model = cuda.usage(false).device - held0; const after = try pool(a, io, &g.ctx, problem) orelse return null; - const room = after.room(model) -| loaded.learn_bytes; + const vision_bytes: usize = if (@hasField(@TypeOf(loaded), "vision_bytes")) loaded.vision_bytes else 0; + const room = after.room(model) -| loaded.learn_bytes -| vision_bytes; const free = loaded.free_streams; const streams = budget.admit(room, loaded.stream_bytes, free, o.lanes, o.lanes_fixed) catch |e| { problem.* = switch (e) { @@ -450,7 +458,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O // prompt-cache snapshots are Nemotron's (cuda_reuse.zig); a family without them serves without a cache const cache = if (@hasDecl(F, "snap_bytes")) budget.cacheBytes(o.prompt_cache_gib, room, loaded.stream_bytes * (streams -| free)) else 0; h.startup = try std.fmt.allocPrint(gpa, "CUDA sm_{d} device {d} ({s}{s}): model {d:.2} GiB{s}; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window, of {d:.1} GiB left after a {d:.1} GiB reserve; prompts in {d}-row chunks{s}{s}; {s}", .{ - capability, device, name, if (after.unified) ", memory shared with the host" else "", toGib(model), if (loaded.learn_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for --slide's trainer", .{toGib(loaded.learn_bytes)}) else "", streams, if (streams == 1) "" else "s", toGib(loaded.stream_bytes), window, toGib(room), toGib(after.reserve), F.prompt_rows, if (segments > 1) try std.fmt.allocPrint(a, ", {d} staggered segments a call", .{segments}) else "", + capability, device, name, if (after.unified) ", memory shared with the host" else "", toGib(model), if (loaded.learn_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for --slide's trainer", .{toGib(loaded.learn_bytes)}) else if (vision_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for the image tower's calls", .{toGib(vision_bytes)}) else "", streams, if (streams == 1) "" else "s", toGib(loaded.stream_bytes), window, toGib(room), toGib(after.reserve), F.prompt_rows, if (segments > 1) try std.fmt.allocPrint(a, ", {d} staggered segments a call", .{segments}) else "", if (cache > 0) try std.fmt.allocPrint(a, ", a {d:.1} GiB prompt cache", .{toGib(cache)}) else ", no prompt cache", if (kernels) |dir| try std.fmt.allocPrint(a, "glue kernels captured at {s}", .{dir}) else "own glue kernels", }); errdefer gpa.free(h.startup); @@ -485,7 +493,20 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O gpa.free(h.dir); }; // the family cuts its own prompt grid from position 0, as `tensorfold run` does: prefill_step 0 - try h.serve(io, loaded.facts, loaded.rows, .{ .lanes = streams, .context_window = @intCast(window), .startup = h.startup, .prompt_cache = h.store != null, .logprobs = loaded.backend.vtable.first_row != null, .structures = loaded.backend.vtable.first_masked != null }, .{ .ctx = loaded.ctx, .text = F.explain }); + const vision: ?api.Vision = if (@hasDecl(F, "prepareImage")) (if (o.vision) |v| .{ + .ctx = h, + .prepare = struct { + fn f(_: *anyopaque, al: Allocator, bytes: []const u8, max_tokens: u32) anyerror!api.PreparedImage { + const p = try F.prepareImage(al, bytes, max_tokens); + return .{ .pixels = p.pixels, .gh = p.gh, .gw = p.gw, .tokens = p.tokens, .hash = p.hash }; + } + }.f, + .image_token = F.image_token, + .markers = &F.image_markers, + .image_tokens = v.image_tokens, + .max_images = v.max_images, + } else null) else null; + try h.serve(io, loaded.facts, loaded.rows, .{ .lanes = streams, .context_window = @intCast(window), .startup = h.startup, .prompt_cache = h.store != null, .logprobs = loaded.backend.vtable.first_row != null, .structures = loaded.backend.vtable.first_masked != null, .vision = vision }, .{ .ctx = loaded.ctx, .text = F.explain }); opened = true; return .{ .engine = h.host.engine(), .close = Host.close, .ctx = h }; } From 5d8bf48592d41a6496cd907589237f7830455bb9 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:24:49 +0000 Subject: [PATCH 09/17] qwen27 CUDA: --kv-cache fp8, and attention partials sized for the admitted 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 --- zig/kernels/cuda/prefill_attention.cu | 99 +++++++- zig/kernels/cuda/qwen_ops.cu | 40 +++ zig/src/cli/qwen27_cuda.zig | 91 ++++++- zig/src/core/engine_api.zig | 2 + zig/src/families/qwen27/cuda/engine.zig | 12 +- zig/src/families/qwen27/cuda/forward.zig | 58 ++++- zig/src/families/qwen27/cuda/kernels.zig | 30 +++ zig/src/families/qwen27/cuda/native.zig | 13 +- zig/src/families/qwen27/cuda/round.zig | 30 ++- zig/src/families/qwen27/cuda/state.zig | 74 ++++-- zig/src/families/qwen27/cuda/triton.zig | 20 ++ zig/src/native/cuda.zig | 15 +- zig/src/native/metal.zig | 4 + zig/src/server/cli.zig | 5 +- zig/tests/cuda/qwen27/attention_kv8.py | 296 +++++++++++++++++++++++ 15 files changed, 742 insertions(+), 47 deletions(-) create mode 100644 zig/tests/cuda/qwen27/attention_kv8.py diff --git a/zig/kernels/cuda/prefill_attention.cu b/zig/kernels/cuda/prefill_attention.cu index cd9a012fc3..fe241822e3 100644 --- a/zig/kernels/cuda/prefill_attention.cu +++ b/zig/kernels/cuda/prefill_attention.cu @@ -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 +#include #include #include @@ -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 -__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 +__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[]; @@ -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(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(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(&pre[j]); + uint32_t* o = reinterpret_cast(&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(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(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(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(i / C, i % C), src + ((int64_t)(in ? key : 0) * HK + hk) * D + (i % C) * 8, in); + } } }; uint32_t qa[QREG ? K16 : 1][4]; @@ -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; @@ -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) { @@ -238,6 +296,22 @@ pattn_kernel(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restric } } +template +__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(q, kc, vc, nullptr, nullptr, out, p0, W, H, HK, G, scale); +} + +template +__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(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). @@ -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); diff --git a/zig/kernels/cuda/qwen_ops.cu b/zig/kernels/cuda/qwen_ops.cu index 778cc1f16e..34b025326d 100644 --- a/zig/kernels/cuda/qwen_ops.cu +++ b/zig/kernels/cuda/qwen_ops.cu @@ -1,5 +1,6 @@ // The 27B's own small kernels: batched state copies, the drafter's taps and its fp32 RMSNorm. #include +#include #include struct TfCopy { @@ -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(blockIdx.x) * 8 + threadIdx.x / 32; + if (row >= it.rows) return; + const int lane = threadIdx.x % 32; + const uint4 w = reinterpret_cast(it.src)[row * 32 + lane]; + const __nv_bfloat162* h = reinterpret_cast(&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(it.dst)[row * 32 + lane] = out; + if (lane == 0) reinterpret_cast(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, diff --git a/zig/src/cli/qwen27_cuda.zig b/zig/src/cli/qwen27_cuda.zig index d1d0e879ad..2cb255d077 100644 --- a/zig/src/cli/qwen27_cuda.zig +++ b/zig/src/cli/qwen27_cuda.zig @@ -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). \\ @@ -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 { @@ -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; } @@ -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; } @@ -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; @@ -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, .{})); diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index cbacca9162..973cb8c2d7 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -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. diff --git a/zig/src/families/qwen27/cuda/engine.zig b/zig/src/families/qwen27/cuda/engine.zig index daff994c44..de2c8ddd5c 100644 --- a/zig/src/families/qwen27/cuda/engine.zig +++ b/zig/src/families/qwen27/cuda/engine.zig @@ -20,7 +20,7 @@ pub fn chunkBounds(start: usize, end: usize, size: usize, j: usize) [2]usize { return .{ start + (end - start) * j / n, start + (end - start) * (j + 1) / n }; } -pub const Options = struct { context: usize }; +pub const Options = struct { context: usize, kv8: bool = false }; pub const Engine = struct { gpa: std.mem.Allocator, @@ -30,6 +30,7 @@ pub const Engine = struct { w: wts.Weights, scratch: st.Scratch, context: usize, + kv8: bool, // --kv-cache fp8: every stream's attention caches e4m3 with a scale a row pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: []const u8, o: Options) !*Engine { const cfg = try c.Config.read(gpa, io, dir); @@ -39,6 +40,7 @@ pub const Engine = struct { e.gpa = gpa; e.ctx = ctx; e.context = o.context; + e.kv8 = o.kv8; e.s = try cuda.Stream.init(ctx.d, true); errdefer e.s.deinit(); e.k = try kern.Kernels.load(gpa, io, ctx, kernels, g.linear_v_heads); @@ -69,7 +71,13 @@ pub const Engine = struct { /// A stream's state for `capacity` positions (its caches, recurrences and conv windows), empty. pub fn sequence(e: *Engine, capacity: usize) !st.Seq { - return st.Seq.init(e.gpa, e.ops(), e.w.g, capacity); + return st.Seq.init(e.gpa, e.ops(), e.w.g, capacity, e.kv8); + } + + /// Attention's partials for `streams` streams of the engine's context in one round. + pub fn fit(e: *Engine, streams: usize) !void { + try e.s.synchronize(); + try e.scratch.fitPartials(e.ctx.d, e.w.g, streams * st.Scratch.streamPartRows(e.context)); } /// prefill_state from an empty state: the prompt in even chunks of at most `prompt_rows`, its last row normed. diff --git a/zig/src/families/qwen27/cuda/forward.zig b/zig/src/families/qwen27/cuda/forward.zig index 3777e8f6aa..e188647925 100644 --- a/zig/src/families/qwen27/cuda/forward.zig +++ b/zig/src/families/qwen27/cuda/forward.zig @@ -121,7 +121,8 @@ pub const Forward = struct { try f.ops.dense(s.y, s.xs, a.k, s.key, W); try f.ops.dense(s.y, s.xs, a.v, rec.v, W); try f.t.attnPrep(s.qg, s.key, a.q_norm, a.k_norm, r.pos, w.inv_freq, s.q_rot, rec.k, W, f.attnShape(), c.eps); - try f.t.attention(s.q_rot, rec.k, rec.v, s.origin, r.offsets(i, att), r.attn, .{ .o = s.part_o, .m = s.part_m, .l = s.part_l }, s.attn, f.attnShape()); + const part: tri.Tri.Partials = .{ .o = s.part_o, .m = s.part_m, .l = s.part_l }; + if (r.kv8) try f.t.attention8(s.q_rot, rec.k, rec.v, s.origin, r.offsets(i, att), r.attn, part, s.attn, f.attnShape()) else try f.t.attention(s.q_rot, rec.k, rec.v, s.origin, r.offsets(i, att), r.attn, part, s.attn, f.attnShape()); try f.t.gateMul(s.attn, s.qg, s.gated, s.gated_xs, W, g_.query_heads, c.head_dim); try f.ops.dense(s.gated, s.gated_xs, a.o, s.r, W); att += 1; @@ -183,6 +184,9 @@ pub const Forward = struct { defer save.deinit(f.gpa); var write: std.ArrayList(kern.Copy) = .empty; defer write.deinit(f.gpa); + var quant: std.ArrayList(kern.Quant) = .empty; // kv8: the accepted keys and values, quantized into the caches + defer quant.deinit(f.gpa); + const hk = g_.kv_heads; base = 0; for (parts, paths, 0..) |p, path, k| { const n = path.len; @@ -199,7 +203,13 @@ pub const Forward = struct { lin += 1; } else { for (path, 0..) |acc, j| { - const at = (p.seq.pos + j) * kv; + const pos = p.seq.pos + j; + if (p.seq.kv8) { + try quant.append(f.gpa, .{ .src = s.attn_records[i].k + (base + acc) * kv, .dst = p.seq.keys[i] + pos * kv / bf, .scale = p.seq.kscale[i] + pos * hk * 4, .rows = hk }); + try quant.append(f.gpa, .{ .src = s.attn_records[i].v + (base + acc) * kv, .dst = p.seq.values[i] + pos * kv / bf, .scale = p.seq.vscale[i] + pos * hk * 4, .rows = hk }); + continue; + } + const at = pos * kv; try write.append(f.gpa, .{ .dst = p.seq.keys[i] + at, .src = s.attn_records[i].k + (base + acc) * kv, .bytes = kv }); try write.append(f.gpa, .{ .dst = p.seq.values[i] + at, .src = s.attn_records[i].v + (base + acc) * kv, .bytes = kv }); } @@ -213,6 +223,9 @@ pub const Forward = struct { try f.ops.upload(second, std.mem.sliceAsBytes(write.items)); try f.ops.copies(s.copy_items, save.items.len); try f.ops.copies(second, write.items.len); + if (quant.items.len > st.copy_items) return error.InvalidQwenCommit; + try f.ops.upload(s.quant_items, std.mem.sliceAsBytes(quant.items)); + try f.ops.quant(s.quant_items, quant.items.len, hk); try f.ops.s.synchronize(); // the tables' host copies go when this returns } @@ -279,13 +292,25 @@ pub const Forward = struct { .attention => |a| { try f.ops.prefillDense(s.y, a.q, s.qg, W); try f.ops.prefillDense(s.y, a.k, s.key, W); - try f.ops.prefillDense(s.y, a.v, seq.values[i] + p0 * kv, W); + // kv8: the chunk's rotated keys and values go through the prompt buffers, quantized into the caches + const kdst = if (seq.kv8) s.prompt_keys else seq.keys[i] + p0 * kv; + const vdst = if (seq.kv8) s.prompt_values else seq.values[i] + p0 * kv; + try f.ops.prefillDense(s.y, a.v, vdst, W); if (media) |m| { const sh = f.attnShape(); - try m.tower.attnPrep(f.gpu(), s.qg, s.key, a.q_norm, a.k_norm, m.dev.ptr + W * 4, w.inv_freq, s.q_rot, seq.keys[i] + p0 * kv, W, .{ .heads = sh.heads, .kv_heads = sh.kv_heads, .dim = sh.dim, .half = sh.half }, c.eps); - } else try f.t.attnPrep(s.qg, s.key, a.q_norm, a.k_norm, s.pos, w.inv_freq, s.q_rot, seq.keys[i] + p0 * kv, W, f.attnShape(), c.eps); + try m.tower.attnPrep(f.gpu(), s.qg, s.key, a.q_norm, a.k_norm, m.dev.ptr + W * 4, w.inv_freq, s.q_rot, kdst, W, .{ .heads = sh.heads, .kv_heads = sh.kv_heads, .dim = sh.dim, .half = sh.half }, c.eps); + } else try f.t.attnPrep(s.qg, s.key, a.q_norm, a.k_norm, s.pos, w.inv_freq, s.q_rot, kdst, W, f.attnShape(), c.eps); const scale: f32 = @floatCast(std.math.pow(f64, c.head_dim, -0.5)); - try f.ops.prefillAttention(s.q_rot, seq.keys[i], seq.values[i], s.attn, p0, W, g_.query_heads, g_.kv_heads, scale); + if (seq.kv8) { + const hk = g_.kv_heads; + const q = [_]kern.Quant{ + .{ .src = s.prompt_keys, .dst = seq.keys[i] + p0 * kv / bf, .scale = seq.kscale[i] + p0 * hk * 4, .rows = W * hk }, + .{ .src = s.prompt_values, .dst = seq.values[i] + p0 * kv / bf, .scale = seq.vscale[i] + p0 * hk * 4, .rows = W * hk }, + }; + try f.ops.upload(s.quant_items, std.mem.sliceAsBytes(&q)); + try f.ops.quant(s.quant_items, q.len, W * hk); + try f.ops.prefillAttention8(s.q_rot, seq.keys[i], seq.values[i], seq.kscale[i], seq.vscale[i], s.attn, p0, W, g_.query_heads, g_.kv_heads, scale); + } else try f.ops.prefillAttention(s.q_rot, seq.keys[i], seq.values[i], s.attn, p0, W, g_.query_heads, g_.kv_heads, scale); try f.t.gateMul(s.attn, s.qg, s.gated, s.gated_xs, W, g_.query_heads, c.head_dim); try f.ops.prefillDense(s.gated, a.o, s.r, W); }, @@ -355,6 +380,10 @@ pub const Forward = struct { }; const staged = items.items.len; var at_layer: [256]usize = undefined; // each layer's first write, then the end + var quant: std.ArrayList(kern.Quant) = .empty; // kv8: each attention layer's prompt rows to quantize + defer quant.deinit(f.gpa); + var quant_at: [256]usize = @splat(0); + var quant_rows: usize = 0; lin_n = 0; for (0..g_.layers) |i| { at_layer[i] = items.items.len; @@ -373,15 +402,26 @@ pub const Forward = struct { } lin_n += 1; } else { + quant_at[i] = quant.items.len; for (pieces, 0..) |p, k| { const o = starts[k]; const n = p.ids.len; + if (p.seq.kv8) { + const hk = g_.kv_heads; + try quant.append(f.gpa, .{ .src = s.prompt_keys + o * kv, .dst = p.seq.keys[i] + p.seq.pos * kv / bf, .scale = p.seq.kscale[i] + p.seq.pos * hk * 4, .rows = n * hk }); + try quant.append(f.gpa, .{ .src = s.prompt_values + o * kv, .dst = p.seq.values[i] + p.seq.pos * kv / bf, .scale = p.seq.vscale[i] + p.seq.pos * hk * 4, .rows = n * hk }); + quant_rows = @max(quant_rows, n * hk); + continue; + } try items.append(f.gpa, .{ .dst = p.seq.keys[i] + p.seq.pos * kv, .src = s.prompt_keys + o * kv, .bytes = n * kv }); try items.append(f.gpa, .{ .dst = p.seq.values[i] + p.seq.pos * kv, .src = s.prompt_values + o * kv, .bytes = n * kv }); } } } + quant_at[g_.layers] = quant.items.len; at_layer[g_.layers] = items.items.len; + if (quant.items.len > st.copy_items) return error.InvalidQwenWindows; + try f.ops.upload(s.quant_items, std.mem.sliceAsBytes(quant.items)); if (items.items.len > 2 * st.copy_items) return error.InvalidQwenWindows; try f.ops.upload(s.copy_items, std.mem.sliceAsBytes(items.items)); try f.ops.copies(s.copy_items, staged); @@ -416,9 +456,13 @@ pub const Forward = struct { try f.ops.prefillDense(s.y, a.v, s.prompt_values, W); try f.t.attnPrep(s.qg, s.key, a.q_norm, a.k_norm, s.pos, w.inv_freq, s.q_rot, s.prompt_keys, W, f.attnShape(), c.eps); try f.ops.copies(s.copy_items + at_layer[i] * item, at_layer[i + 1] - at_layer[i]); + try f.ops.quant(s.quant_items + quant_at[i] * @sizeOf(kern.Quant), quant_at[i + 1] - quant_at[i], quant_rows); const scale: f32 = @floatCast(std.math.pow(f64, c.head_dim, -0.5)); const qrow = g_.query_heads * c.head_dim * bf; - for (pieces, 0..) |p, k| try f.ops.prefillAttention(s.q_rot + starts[k] * qrow, p.seq.keys[i], p.seq.values[i], s.attn + starts[k] * qrow, p.seq.pos, p.ids.len, g_.query_heads, g_.kv_heads, scale); + for (pieces, 0..) |p, k| if (p.seq.kv8) + try f.ops.prefillAttention8(s.q_rot + starts[k] * qrow, p.seq.keys[i], p.seq.values[i], p.seq.kscale[i], p.seq.vscale[i], s.attn + starts[k] * qrow, p.seq.pos, p.ids.len, g_.query_heads, g_.kv_heads, scale) + else + try f.ops.prefillAttention(s.q_rot + starts[k] * qrow, p.seq.keys[i], p.seq.values[i], s.attn + starts[k] * qrow, p.seq.pos, p.ids.len, g_.query_heads, g_.kv_heads, scale); try f.t.gateMul(s.attn, s.qg, s.gated, s.gated_xs, W, g_.query_heads, c.head_dim); try f.ops.prefillDense(s.gated, a.o, s.r, W); }, diff --git a/zig/src/families/qwen27/cuda/kernels.zig b/zig/src/families/qwen27/cuda/kernels.zig index 4b486922f8..964eb4536b 100644 --- a/zig/src/families/qwen27/cuda/kernels.zig +++ b/zig/src/families/qwen27/cuda/kernels.zig @@ -15,6 +15,7 @@ const sym = struct { const gemv = "_ZN12tf_lane_gemv11gemv_kernelILi64ELi64ELi8EEEvPK13__nv_bfloat16PKfNS_4PartEiii"; const prefill_mm = "_ZN14tf_qmm_prefill14prefill_kernelILi64ELi128ELi128ELi2ELi2ELi2ELb0EEEvPK13__nv_bfloat16PKjS3_S3_Pviiiiii"; const pattn = "_ZN20tf_prefill_attention12pattn_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16S3_S3_PS1_iiiiif"; + const pattn8 = "_ZN20tf_prefill_attention13pattn8_kernelILi256ELi8ELi2ELi2EEEvPK13__nv_bfloat16PKhS5_PKfS7_PS1_iiiiif"; const chain128 = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16Li128ELi32EEEvPKT_S4_PKS1_PKfS8_S8_PfPS1_iii"; const chain64 = "_ZN14tf_gdn_prefill12chain_kernelI13__nv_bfloat16Li64ELi32EEEvPKT_S4_PKS1_PKfS8_S8_PfPS1_iii"; const argmax = "tf_argmax_rows_i32_kernel"; @@ -44,6 +45,10 @@ pub const pattn_smem: u32 = 98304; // two 32-key slots of 256 dims beside eight /// One item of a batched copy: 16-byte aligned pointers, a multiple of 16 bytes. pub const Copy = extern struct { dst: u64, src: u64, bytes: u64 }; +/// One item of qwen_ops.cu's kv_quant (--kv-cache fp8): `rows` bf16 rows of 256 from src, as e4m3 rows at dst and +/// one fp32 scale a row at scale. +pub const Quant = extern struct { src: u64, dst: u64, scale: u64, rows: u64 }; + /// A tiled 4-bit projection: packed words, (kg, npad) scales and biases, n outputs from k inputs. pub const QLinear = struct { w: u64, s: u64, b: u64, n: usize, k: usize, npad: usize }; @@ -56,6 +61,8 @@ pub const Kernels = struct { gemv: cuda.Function, prefill_mm: cuda.Function, pattn: cuda.Function, + pattn8: cuda.Function, + kv_quant: cuda.Function, trees: [cuda.kernels.gdn_variants.len]cuda.Function, // tree_kernel by gdn_variants: [0] the chain one chip: [3]c_int, // major, minor, SMs: what dispatch_tree reads replay: cuda.Function, @@ -95,6 +102,7 @@ pub const Kernels = struct { k.prefill_mm = try k.mods[1].function(sym.prefill_mm); k.gemv = try k.mods[2].function(sym.gemv); k.pattn = try k.mods[3].function(sym.pattn); + k.pattn8 = try k.mods[3].function(sym.pattn8); for (&k.trees, cuda.kernels.gdn_variants) |*f, v| f.* = try k.mods[4].function(v.symbol); k.replay = try k.mods[4].function(cuda.kernels.gdn_symbols.replay_bf16); k.pack_dense = try k.mods[6].function(cuda.qlinear.symbols.pack_words); @@ -102,6 +110,7 @@ pub const Kernels = struct { k.argmax = try k.mods[7].function(sym.argmax); k.torch = try torch_ops.Functions.resolve(k.mods[7..13]); k.copy_batch = try k.mods[13].function("tf_copy_batch"); + k.kv_quant = try k.mods[13].function("tf_kv_quant"); k.tap = try k.mods[13].function("tf_tap"); k.rms_norm = try k.mods[13].function("tf_rms_norm"); k.inv_freq = try k.mods[13].function("tf_inv_freq"); @@ -118,6 +127,7 @@ pub const Kernels = struct { try k.gemv.allowDynamicShared(group_smem); try k.prefill_mm.allowDynamicShared(prefill_mm_smem); try k.pattn.allowDynamicShared(pattn_smem); + try k.pattn8.allowDynamicShared(pattn_smem); k.gemv_blocks = @max(1, try k.gemv.occupancy(128, group_smem)) * sms; const major = try ctx.attribute(.compute_capability_major); const minor = try ctx.attribute(.compute_capability_minor); @@ -309,6 +319,26 @@ pub const Ops = struct { try o.go(o.k.pattn, .{ (rows + block_rows - 1) / block_rows, kv_heads * (g / hpc), 1 }, 256, pattn_smem, &a); } + /// prefill_attention over an fp8 cache: e4m3 keys and values with a scale a (position, key head) row. + pub fn prefillAttention8(o: Ops, q: u64, kc: u64, vc: u64, ks: u64, vs: u64, out: u64, p0: usize, rows: usize, heads: usize, kv_heads: usize, scale: f32) !void { + const g = heads / kv_heads; + const hpc = 2; + var a: cuda.Args = .{}; + for ([_]u64{ q, kc, vc, ks, vs, out }) |v| a.add(v); + for ([_]usize{ p0, rows, heads, kv_heads, g }) |v| a.add(int(v)); + a.add(scale); + const block_rows = 16 * (8 / hpc); + try o.go(o.k.pattn8, .{ (rows + block_rows - 1) / block_rows, kv_heads * (g / hpc), 1 }, 256, pattn_smem, &a); + } + + /// qwen_ops.cu's tf_kv_quant: `count` items from the device table `items`, none over `most` rows. + pub fn quant(o: Ops, items: u64, count: usize, most: usize) !void { + if (count == 0) return; + var a: cuda.Args = .{}; + a.add(items); + try o.go(o.k.kv_quant, .{ (most + 7) / 8, count, 1 }, 256, 0, &a); + } + /// torch.argmax(rows of bf16 logits) as int32: the first maximum, a NaN first. pub fn argmax(o: Ops, logits: u64, vocab: usize, ld: usize, out: u64, rows: usize) !void { var a: cuda.Args = .{}; diff --git a/zig/src/families/qwen27/cuda/native.zig b/zig/src/families/qwen27/cuda/native.zig index 8b8fdd1ea0..32833fe00c 100644 --- a/zig/src/families/qwen27/cuda/native.zig +++ b/zig/src/families/qwen27/cuda/native.zig @@ -17,7 +17,7 @@ pub const default_context: i64 = 32768; pub const max_segments: u32 = 1; pub const prompt_rows: u32 = engine.prompt_rows; -pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, drafter: ?[]const u8 = null, vision: ?Vision = null }; +pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, drafter: ?[]const u8 = null, vision: ?Vision = null, kv8: bool = false }; /// --vision's limits: the visual tokens a request's images share, and its images. pub const Vision = struct { image_tokens: u32, max_images: u32 }; @@ -83,7 +83,7 @@ const most_streams = 32; pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { // the 27B's glue runs the Python engine's Triton kernels, captured on this chip (no own glue kernels yet) - const e = try engine.Engine.init(gpa, io, ctx, dir, kernels orelse return error.QwenNeedsCapturedKernels, .{ .context = o.context }); + const e = try engine.Engine.init(gpa, io, ctx, dir, kernels orelse return error.QwenNeedsCapturedKernels, .{ .context = o.context, .kv8 = o.kv8 }); errdefer e.deinit(); const own = try gpa.create(Owned); errdefer gpa.destroy(own); @@ -110,13 +110,20 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ .backend = own.lanes.backend(), .facts = own.lanes.facts(), .rows = st.max_rows, - .stream_bytes = st.Seq.bytes(e.w.g, o.context) + if (own.draft != null) dr.Context.bytes() else 0, + // each stream's caches, its drafter context, and its share of a round's attention partials (`fit`) + .stream_bytes = st.Seq.bytes(e.w.g, o.context, o.kv8) + st.Scratch.partialBytes(e.w.g, st.Scratch.streamPartRows(o.context)) + if (own.draft != null) dr.Context.bytes() else 0, .vision_bytes = vision_bytes, .ctx = own, .deinit = release, }; } +/// After admission: attention's partials sized for the `streams` the budget admitted. +pub fn fit(p: *anyopaque, streams: u32) !void { + const own: *Owned = @ptrCast(@alignCast(p)); + try own.e.fit(@min(streams, st.max_streams)); +} + /// A request this engine refuses, in words; null: none of its own. pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { return switch (err) { diff --git a/zig/src/families/qwen27/cuda/round.zig b/zig/src/families/qwen27/cuda/round.zig index 2354420e90..7fd0b2f770 100644 --- a/zig/src/families/qwen27/cuda/round.zig +++ b/zig/src/families/qwen27/cuda/round.zig @@ -27,7 +27,8 @@ pub const Round = struct { most: usize, // the most rows a stream's window holds tables: u64, // multi: (DeltaNet layers, streams) state pointers, a layer's row at its DeltaNet index attn: tri.Tri.Plan, - offs: u64, // (attention layers, streams, 2) int64 cache offsets; single: indexed by layer + offs: u64, // (attention layers, streams, 2) int64 cache offsets (4 under kv8: scales too); single: by layer + kv8: bool, // the streams' caches are e4m3 with scales (attention8) starts_host: [st.max_streams + 1]usize, /// The conv rows gdn_pre reads for layer `i` (its DeltaNet index `j`): the stream's own, or the stacked copy. @@ -38,7 +39,8 @@ pub const Round = struct { /// Layer `i`'s attention cache offsets: tree_forward's (one stream, by layer) or the packed (layer, streams) rows. pub fn offsets(r: *const Round, i: usize, a: usize) u64 { - return if (r.multi) r.offs + a * r.streams * 16 else r.offs + i * 16; + const each: usize = if (r.kv8) 32 else 16; + return if (r.multi) r.offs + a * r.streams * each else r.offs + i * each; } /// The DeltaNet state table of DeltaNet layer `j` (multi only). @@ -106,6 +108,18 @@ fn offsetOf(s: *const st.Scratch, ptr: u64) i64 { return @divExact(@as(i64, @bitCast(ptr -% s.origin)), bf); } +/// Layer `i`'s cache offsets for a stream: bf16 elements of keys and values, or under kv8 e4m3 bytes of keys and +/// values and fp32 elements of their scales. +fn cacheOffsets(s: *const st.Scratch, seq: *const st.Seq, i: usize, out: *std.ArrayList(i64), gpa: std.mem.Allocator) !void { + if (!seq.kv8) return out.appendSlice(gpa, &.{ offsetOf(s, seq.keys[i]), offsetOf(s, seq.values[i]) }); + const d = struct { + fn at(sc: *const st.Scratch, ptr: u64, size: i64) i64 { + return @divExact(@as(i64, @bitCast(ptr -% sc.origin)), size); + } + }; + try out.appendSlice(gpa, &.{ d.at(s, seq.keys[i], 1), d.at(s, seq.values[i], 1), d.at(s, seq.kscale[i], 4), d.at(s, seq.vscale[i], 4) }); +} + /// Every stream's host plans: positions (pos + depth), the GDN schedule (nodes offset by its start), conv windows. const Host = struct { pos: std.ArrayList(i32) = .empty, entries: std.ArrayList(i32) = .empty, windows: std.ArrayList(i32) = .empty, slots: usize = 0, most: usize = 0 }; @@ -144,6 +158,14 @@ pub fn stage(gpa: std.mem.Allocator, ops: kern.Ops, t: tri.Tri, s: *st.Scratch, r.starts_host[k + 1] = W; } if (W > st.round_rows) return error.WindowTooWide; + // attention's partials: the most slots any stream takes, for every row of the round + var most_slots: usize = 0; + for (parts) |p| { + most_slots = @max(most_slots, tri.slots(p.seq.pos, p.tokens.len)); + if (p.seq.kv8 != parts[0].seq.kv8) return error.InvalidQwenWindows; + } + if (most_slots * W > s.part_rows) return error.WindowTooWide; + r.kv8 = parts[0].seq.kv8; r.rows = W; r.streams = parts.len; r.multi = parts.len > 1; @@ -179,7 +201,7 @@ pub fn stage(gpa: std.mem.Allocator, ops: kern.Ops, t: tri.Tri, s: *st.Scratch, const ap = try attnPlan(gpa, &host, parts, group); try ops.upload(s.attn_plan, std.mem.sliceAsBytes(host.items)); try ops.s.synchronize(); - for (0..g.layers) |i| try offs.appendSlice(gpa, if (c.linear(i)) &.{ 0, 0 } else &.{ offsetOf(s, p.seq.keys[i]), offsetOf(s, p.seq.values[i]) }); + for (0..g.layers) |i| if (c.linear(i)) try offs.appendNTimes(gpa, 0, if (r.kv8) 4 else 2) else try cacheOffsets(s, p.seq, i, &offs, gpa); try ops.upload(s.offs, std.mem.sliceAsBytes(offs.items)); try ops.s.synchronize(); r.ids = s.ids; @@ -224,7 +246,7 @@ pub fn stage(gpa: std.mem.Allocator, ops: kern.Ops, t: tri.Tri, s: *st.Scratch, var j: usize = 0; for (0..g.layers) |i| { if (!c.linear(i)) { - for (parts) |p| try offs.appendSlice(gpa, &.{ offsetOf(s, p.seq.keys[i]), offsetOf(s, p.seq.values[i]) }); + for (parts) |p| try cacheOffsets(s, p.seq, i, &offs, gpa); continue; } const cat = s.conv_cat + j * st.max_streams * keep * g.convDim() * bf; diff --git a/zig/src/families/qwen27/cuda/state.zig b/zig/src/families/qwen27/cuda/state.zig index 29d276651b..e85f68a5b5 100644 --- a/zig/src/families/qwen27/cuda/state.zig +++ b/zig/src/families/qwen27/cuda/state.zig @@ -46,8 +46,11 @@ pub const Seq = struct { arena: Arena, rec: []u64, // by layer: (hv, dv, dk) fp32, 0 for attention layers conv: []u64, // by layer: (3, conv dim) bf16 - keys: []u64, // by layer: (capacity, kv heads, head dim) bf16 + keys: []u64, // by layer: (capacity, kv heads, head dim) bf16, or e4m3 under kv8 values: []u64, + kscale: []u64, // kv8: by layer, (capacity, kv heads) fp32, each key row's scale (0 for DeltaNet layers) + vscale: []u64, + kv8: bool, // --kv-cache fp8: keys and values as e4m3 rows with a scale each head_in: u64, // the last prompt row normed, (hidden) bf16, and its group sums: the first draw's input head_xs: u64, capacity: usize, @@ -57,16 +60,16 @@ pub const Seq = struct { gpa: std.mem.Allocator, /// Device bytes a stream of `capacity` positions takes. - pub fn bytes(g: c.Geometry, capacity: usize) usize { + pub fn bytes(g: c.Geometry, capacity: usize, kv8: bool) usize { var n: usize = std.mem.alignForward(usize, g.hidden * 2, 256) + std.mem.alignForward(usize, g.hidden / 64 * 4, 256); const a = std.mem.alignForward; - for (0..g.layers) |i| n += if (c.linear(i)) a(usize, g.deltaBytes(), 256) + a(usize, g.convBytes(), 256) else 2 * a(usize, capacity * g.kvInner() * 2, 256); + for (0..g.layers) |i| n += if (c.linear(i)) a(usize, g.deltaBytes(), 256) + a(usize, g.convBytes(), 256) else if (kv8) 2 * (a(usize, capacity * g.kvInner(), 256) + a(usize, capacity * g.kv_heads * 4, 256)) else 2 * a(usize, capacity * g.kvInner() * 2, 256); return n; } /// A fresh stream: zero recurrences and conv windows, caches for `capacity` positions. - pub fn init(gpa: std.mem.Allocator, ops: kern.Ops, g: c.Geometry, capacity: usize) !Seq { - var s: Seq = .{ .gpa = gpa, .arena = try Arena.init(ops.k.d, bytes(g, capacity)), .rec = &.{}, .conv = &.{}, .keys = &.{}, .values = &.{}, .head_in = 0, .head_xs = 0, .capacity = capacity }; + pub fn init(gpa: std.mem.Allocator, ops: kern.Ops, g: c.Geometry, capacity: usize, kv8: bool) !Seq { + var s: Seq = .{ .gpa = gpa, .arena = try Arena.init(ops.k.d, bytes(g, capacity, kv8)), .rec = &.{}, .conv = &.{}, .keys = &.{}, .values = &.{}, .kscale = &.{}, .vscale = &.{}, .kv8 = kv8, .head_in = 0, .head_xs = 0, .capacity = capacity }; errdefer s.arena.deinit(); s.rec = try gpa.alloc(u64, g.layers); errdefer gpa.free(s.rec); @@ -76,7 +79,11 @@ pub const Seq = struct { errdefer gpa.free(s.keys); s.values = try gpa.alloc(u64, g.layers); errdefer gpa.free(s.values); - const bf = 2; + s.kscale = try gpa.alloc(u64, g.layers); + errdefer gpa.free(s.kscale); + s.vscale = try gpa.alloc(u64, g.layers); + errdefer gpa.free(s.vscale); + const bf: usize = if (kv8) 1 else 2; s.head_in = try s.arena.take(g.hidden * 2); s.head_xs = try s.arena.take(g.hidden / 64 * 4); for (0..g.layers) |i| { @@ -84,6 +91,8 @@ pub const Seq = struct { s.conv[i] = 0; s.keys[i] = 0; s.values[i] = 0; + s.kscale[i] = 0; + s.vscale[i] = 0; const A = &s.arena; if (c.linear(i)) { s.rec[i] = try A.take(g.deltaBytes()); @@ -91,6 +100,10 @@ pub const Seq = struct { } else { s.keys[i] = try A.take(capacity * g.kvInner() * bf); s.values[i] = try A.take(capacity * g.kvInner() * bf); + if (kv8) { + s.kscale[i] = try A.take(capacity * g.kv_heads * 4); + s.vscale[i] = try A.take(capacity * g.kv_heads * 4); + } } } try s.reset(ops, g); @@ -103,6 +116,8 @@ pub const Seq = struct { s.gpa.free(s.conv); s.gpa.free(s.keys); s.gpa.free(s.values); + s.gpa.free(s.kscale); + s.gpa.free(s.vscale); s.* = undefined; } @@ -179,10 +194,12 @@ pub const Scratch = struct { paths: u64, depths: u64, offs: u64, - part_o: u64, + part_o: u64, // attention's partials, (slots, rows, heads, dim) fp32 and (slots, rows, heads) m and l, in `parts` part_m: u64, part_l: u64, - part_chunks: usize, + part_rows: usize, // the slot-rows `parts` holds: a round's most slots times its rows fit under this + parts: ?cuda.DeviceBuffer = null, + quant_items: u64, // --kv-cache fp8: a commit's or a prompt's kv_quant table (kern.Quant) origin: u64, // the bf16 origin cache offsets count from conv_tmp: u64, conv_old: u64, // a round's streams' conv rows that survive its commit, by stream and DeltaNet layer @@ -210,19 +227,49 @@ pub const Scratch = struct { s.arena = try Arena.init(d, s.arena.used); errdefer s.arena.deinit(); try s.layout(g, prompt_rows, capacity); + s.parts = null; + try s.fitPartials(d, g, initial_part_rows); return s; } + /// Partials for calibration's short windows until `fit` sizes them for the admitted streams. + pub const initial_part_rows = 4 * round_rows; + + /// Device bytes partials of `slot_rows` take. + pub fn partialBytes(g: c.Geometry, slot_rows: usize) usize { + const a = std.mem.alignForward; + return a(usize, slot_rows * g.query_heads * c.head_dim * 4, 256) + 2 * a(usize, slot_rows * g.query_heads * 4, 256); + } + + /// The slot-rows a stream of `capacity` positions may add to a round: its most slots (attention.slots of any + /// keys and window it can hold) times its widest window. + pub fn streamPartRows(capacity: usize) usize { + return ((capacity + max_rows + tri.chunk - 1) / tri.chunk + 1) * max_rows; + } + + /// Partials of `slot_rows` (at least the initial), replacing any held. + pub fn fitPartials(s: *Scratch, d: *const cuda.Driver, g: c.Geometry, slot_rows: usize) !void { + const rows = @max(slot_rows, initial_part_rows); + if (s.parts) |*b| b.free(); + s.parts = null; + var b = try cuda.DeviceBuffer.alloc(d, partialBytes(g, rows)); + errdefer b.free(); + var A: Arena = .{ .buf = b }; + s.part_o = try A.take(rows * g.query_heads * c.head_dim * 4); + s.part_m = try A.take(rows * g.query_heads * 4); + s.part_l = try A.take(rows * g.query_heads * 4); + s.part_rows = rows; + s.parts = b; + } + fn layout(s: *Scratch, g: c.Geometry, prompt_rows: usize, capacity: usize) !void { const R = @max(prompt_rows, round_rows); const W = round_rows; const bf = 2; - const chunks = (capacity + W + tri.chunk - 1) / tri.chunk; // attention.plan_host: a query tile's items per committed chunk and folded group const codes = capacity / tri.chunk + capacity / (tri.chunk * tri.group_chunks); const items = codes * ((W * (g.query_heads / g.kv_heads) + 15) / 16); s.rows = R; - s.part_chunks = chunks; s.arena.used = 0; const A = &s.arena; s.origin = try A.take(128); @@ -271,13 +318,11 @@ pub const Scratch = struct { s.attn_plan = try A.take((W + 4 + 3 * items + W + 12) * 4); // + each segment's 16-byte padding s.paths = try A.take(W * tri.max_nodes * 4); s.depths = try A.take(W * 4); - s.offs = try A.take(g.layers * max_streams * 2 * 8); - s.part_o = try A.take(chunks * W * g.query_heads * c.head_dim * 4); - s.part_m = try A.take(chunks * W * g.query_heads * 4); - s.part_l = try A.take(chunks * W * g.query_heads * 4); + s.offs = try A.take(g.layers * max_streams * 4 * 8); s.conv_tmp = try A.take((c.conv_taps - 1 + R) * g.convDim() * bf); s.conv_old = try A.take(max_streams * g.layers * (c.conv_taps - 1) * g.convDim() * bf); s.copy_items = try A.take(2 * copy_items * @sizeOf(kern.Copy)); + s.quant_items = try A.take(copy_items * @sizeOf(kern.Quant)); s.taps = try A.take(R * 5 * g.hidden * bf); s.replay_table = try A.take(g.layers * (4 + max_streams) * 8); s.replay_rows = try A.take(max_streams * (W + 1) * 4); @@ -301,6 +346,7 @@ pub const Scratch = struct { } pub fn deinit(s: *Scratch) void { + if (s.parts) |*b| b.free(); s.arena.deinit(); s.gpa.free(s.records); s.gpa.free(s.attn_records); diff --git a/zig/src/families/qwen27/cuda/triton.zig b/zig/src/families/qwen27/cuda/triton.zig index 5206ff382d..2ed4e7e748 100644 --- a/zig/src/families/qwen27/cuda/triton.zig +++ b/zig/src/families/qwen27/cuda/triton.zig @@ -118,6 +118,26 @@ pub const Tri = struct { p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), p("OUT", "*bf16", out), p("STREAM", "*i32", plan.streams), p("ROWS", "*i32", plan.rows), int("W", w), }, &.{ ci("H", a.heads), ci("D", a.dim), ci("G", g), ci("DS", merge_columns), ci("CH", chunk), ci("GR", group_chunks) }); } + + /// attention_kv8.py's attention8: attention over e4m3 caches, `offs` holding each stream's four offsets (key + /// and value bytes, their scales' fp32 elements) from `base`; the window's own keys and values stay bf16. + pub fn attention8(t: Tri, q: u64, kn: u64, vn: u64, base: u64, offs: u64, plan: Plan, part: Partials, out: u64, a: Attn) !void { + const g = a.heads / a.kv_heads; + const scale: f32 = @floatCast(std.math.pow(f64, @floatFromInt(a.dim), -0.5)); + const w = plan.width; + if (plan.n_items > 0) try t.run("_shared8", .{ u(plan.n_items * a.kv_heads), 1, 1 }, &.{ + p("Q", "*bf16", q), p("KC", "*fp8e4nv", base), p("VC", "*fp8e4nv", base), p("KS", "*fp32", base), p("VS", "*fp32", base), p("OFF", "*i64", offs), + p("STREAM", "*i32", plan.streams), p("ITEMS", "*i32", plan.items), p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), int("W", w), + }, &.{ ci("H", a.heads), ci("HK", a.kv_heads), ci("D", a.dim), ci("G", g), ci("CH", chunk), aot.cf("SCALE", scale), ci("GR", group_chunks) }); + const tails = 1 + (max_nodes + chunk - 1) / chunk; + try t.run("_tail8", .{ u(w), u(a.kv_heads), u(tails) }, &.{ + p("Q", "*bf16", q), p("KN", "*bf16", kn), p("VN", "*bf16", vn), p("KC", "*fp8e4nv", base), p("VC", "*fp8e4nv", base), p("KS", "*fp32", base), p("VS", "*fp32", base), p("OFF", "*i64", offs), + p("STREAM", "*i32", plan.streams), p("ROWS", "*i32", plan.rows), p("PATHS", "*i32", plan.paths), p("DEPTHS", "*i32", plan.depths), p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), int("W", w), + }, &.{ ci("H", a.heads), ci("HK", a.kv_heads), ci("D", a.dim), ci("G", g), ci("CH", chunk), ci("MAXD", max_nodes), aot.cf("SCALE", scale), ci("GR", group_chunks) }); + try t.run("_merge", .{ u(w), u(a.kv_heads), u(a.dim / merge_columns) }, &.{ + p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), p("OUT", "*bf16", out), p("STREAM", "*i32", plan.streams), p("ROWS", "*i32", plan.rows), int("W", w), + }, &.{ ci("H", a.heads), ci("D", a.dim), ci("G", g), ci("DS", merge_columns), ci("CH", chunk), ci("GR", group_chunks) }); + } }; /// attention.groups: whole committed 2048-key groups fold in their own programs only when they fill the GPU. diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index ba1c01688a..03cb15e17b 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -435,6 +435,13 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O } family_options.vision = .{ .image_tokens = v.image_tokens, .max_images = v.max_images }; } + if (o.kv8) { + if (!@hasField(F.Options, "kv8")) { + problem.* = try std.fmt.allocPrint(a, "--kv-cache fp8: the native CUDA engine keeps fp8 caches for Qwen3.8-27B only, not {s} checkpoints", .{o.model_type}); + return null; + } + family_options.kv8 = true; + } const loaded = F.open(gpa, io, &g.ctx, o.dir, kernels, family_options) catch |e| { problem.* = try std.fmt.allocPrint(a, "the native CUDA engine cannot load {s} with {s} glue kernels ({s})", .{ o.dir, kernels orelse "its own", @errorName(e) }); return null; @@ -452,13 +459,17 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O }; return null; }; + if (@hasDecl(F, "fit")) F.fit(loaded.ctx, streams) catch |e| { + problem.* = try std.fmt.allocPrint(a, "the native CUDA engine cannot size its attention scratch for {d} stream{s} ({s})", .{ streams, if (streams == 1) "" else "s", @errorName(e) }); + return null; + }; const h = try gpa.create(Host); errdefer gpa.destroy(h); h.* = .{ .gpa = gpa, .gpu = g, .family = loaded.ctx, .release = loaded.deinit, .inner = loaded.backend, .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .lone = loaded.lone }; // prompt-cache snapshots are Nemotron's (cuda_reuse.zig); a family without them serves without a cache const cache = if (@hasDecl(F, "snap_bytes")) budget.cacheBytes(o.prompt_cache_gib, room, loaded.stream_bytes * (streams -| free)) else 0; - h.startup = try std.fmt.allocPrint(gpa, "CUDA sm_{d} device {d} ({s}{s}): model {d:.2} GiB{s}; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window, of {d:.1} GiB left after a {d:.1} GiB reserve; prompts in {d}-row chunks{s}{s}; {s}", .{ - capability, device, name, if (after.unified) ", memory shared with the host" else "", toGib(model), if (loaded.learn_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for --slide's trainer", .{toGib(loaded.learn_bytes)}) else if (vision_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for the image tower's calls", .{toGib(vision_bytes)}) else "", streams, if (streams == 1) "" else "s", toGib(loaded.stream_bytes), window, toGib(room), toGib(after.reserve), F.prompt_rows, if (segments > 1) try std.fmt.allocPrint(a, ", {d} staggered segments a call", .{segments}) else "", + h.startup = try std.fmt.allocPrint(gpa, "CUDA sm_{d} device {d} ({s}{s}): model {d:.2} GiB{s}; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window{s}, of {d:.1} GiB left after a {d:.1} GiB reserve; prompts in {d}-row chunks{s}{s}; {s}", .{ + capability, device, name, if (after.unified) ", memory shared with the host" else "", toGib(model), if (loaded.learn_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for --slide's trainer", .{toGib(loaded.learn_bytes)}) else if (vision_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for the image tower's calls", .{toGib(vision_bytes)}) else "", streams, if (streams == 1) "" else "s", toGib(loaded.stream_bytes), window, if (o.kv8) " (fp8 caches)" else "", toGib(room), toGib(after.reserve), F.prompt_rows, if (segments > 1) try std.fmt.allocPrint(a, ", {d} staggered segments a call", .{segments}) else "", if (cache > 0) try std.fmt.allocPrint(a, ", a {d:.1} GiB prompt cache", .{toGib(cache)}) else ", no prompt cache", if (kernels) |dir| try std.fmt.allocPrint(a, "glue kernels captured at {s}", .{dir}) else "own glue kernels", }); errdefer gpa.free(h.startup); diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index a8e0283e6c..282d6055d5 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -100,6 +100,10 @@ const Host = struct { /// The engine for `o.dir`, or null with `problem` set when no Metal engine reads the checkpoint. pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { const dense = std.mem.eql(u8, o.model_type, "qwen3_5") and qwen27Engine(a, io, o.dir); + if (o.kv8) { + problem.* = "--kv-cache fp8: the CUDA engine keeps fp8 caches; the Metal engines keep bf16"; + return null; + } if (o.drafter != null and !dense) { problem.* = "--drafter is supported for Qwen3.8-27B-class checkpoints (qwen3_5 with its own output head)"; return null; diff --git a/zig/src/server/cli.zig b/zig/src/server/cli.zig index 02f7578161..ad3d9ffbdb 100644 --- a/zig/src/server/cli.zig +++ b/zig/src/server/cli.zig @@ -50,6 +50,7 @@ pub const flags = [_]Flag{ .{ .name = "--metrics-open", .kind = .store_true, .native = true }, .{ .name = "--dashboard", .kind = .store_true, .native = true }, .{ .name = "--vision", .kind = .store_true, .native = true }, + .{ .name = "--kv-cache", .choices = &.{ "bf16", "fp8" }, .native = true }, .{ .name = "--vision-urls", .kind = .store_true, .native = true }, .{ .name = "--vision-offload", .kind = .store_true }, .{ .name = "--vision-max-images", .native = true }, @@ -167,6 +168,7 @@ pub const Args = struct { master: []const u8 = "", master_port: u16 = 29551, policy: []const u8 = "", // every --policy joined by commas + kv_cache: []const u8 = "bf16", // fp8: e4m3 attention caches, a scale a row (about twice the context) vision: bool = false, // image input (GLM-5.3-Flash): data-URL image_url parts in user messages vision_urls: bool = false, // with --vision, public HTTPS image URLs too (media_fetch.zig) vision_max_images: u32 = 4, @@ -277,7 +279,7 @@ fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usa const n = try int(u, a, name, v); if (n < 0) return fail(u, a, "argument --compact-keep: expected a token count from 0: '{s}'", .{v}); out.compact_keep = @intCast(n); - } else if (is(name, "--compact-memory")) out.compact_memory = v else if (is(name, "--slide")) out.slide = true else if (is(name, "--slide-graph")) out.slide_graph = v else if (is(name, "--parallel")) out.parallel = v else if (is(name, "--backend")) out.backend = v else if (is(name, "--vision")) out.vision = true else if (is(name, "--vision-urls")) out.vision_urls = true else if (is(name, "--vision-max-images")) { + } else if (is(name, "--compact-memory")) out.compact_memory = v else if (is(name, "--slide")) out.slide = true else if (is(name, "--slide-graph")) out.slide_graph = v else if (is(name, "--parallel")) out.parallel = v else if (is(name, "--backend")) out.backend = v else if (is(name, "--vision")) out.vision = true else if (is(name, "--kv-cache")) out.kv_cache = v else if (is(name, "--vision-urls")) out.vision_urls = true else if (is(name, "--vision-max-images")) { const n = try int(u, a, name, v); if (n < 1 or n > 64) return fail(u, a, "argument --vision-max-images: expected 1 to 64 images: '{s}'", .{v}); out.vision_max_images = @intCast(n); @@ -377,6 +379,7 @@ pub fn request(a: Allocator, dir: []const u8, model_type: []const u8, args: Args .master = args.master, .master_port = args.master_port, .policy = args.policy, + .kv8 = std.mem.eql(u8, args.kv_cache, "fp8"), .vision = if (args.vision) .{ .image_tokens = args.vision_image_tokens, .max_images = args.vision_max_images } else null, }; } diff --git a/zig/tests/cuda/qwen27/attention_kv8.py b/zig/tests/cuda/qwen27/attention_kv8.py new file mode 100644 index 0000000000..386873d247 --- /dev/null +++ b/zig/tests/cuda/qwen27/attention_kv8.py @@ -0,0 +1,296 @@ +#!/usr/bin/env python3 +"""attention.attention over an fp8 (e4m3) key and value cache, for the native engine's --kv-cache fp8. + +The cache holds each (position, key head) row of 256 as e4m3 times one fp32 scale (the row's absolute max over 448). +_shared8 and _tail8 are attention.py's _shared and _tail with those loads: e4m3 widens to bf16 exactly, the key's +scale multiplies its scores and the value's scale its probabilities, so the dots stay bf16 tensor-core dots. The +window's own rows (KN, VN) are quantized in the kernel exactly as their commit will quantize them, so each key's +contribution is the same committed or not. Partials keep attention.py's layout, so its _merge folds them unchanged. + +``--out DIR`` checks both against attention.attention over the dequantized cache and records their launches for +triton_aot_manifest.py (one specialization each for W of 1, of a multiple of 16, and of anything else). +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +import torch +import triton +import triton.language as tl + +FP8_MAX = 448.0 + + +@triton.jit +def _tile8(q, k, v, ks, vs, m, l, o, valid, scale: tl.constexpr): + scores = tl.dot(q, tl.trans(k)).to(tl.float32) * ks[None, :] * scale + scores = tl.where(valid[None, :], scores, float("-inf")) + tile_m = tl.max(scores, 1) + active = tile_m != float("-inf") + next_m = tl.where(active, tl.maximum(m, tile_m), m) + alpha = tl.where(active, tl.where(m == float("-inf"), 0.0, tl.exp(m - next_m)), 1.0) + p = tl.where(valid[None, :] & active[:, None], tl.exp(scores - next_m[:, None]), 0.0) + o = o * alpha[:, None] + tl.dot((p * vs[None, :]).to(tl.bfloat16), v) + l = l * alpha + tl.sum(p, 1) + return next_m, l, o + + +@triton.jit +def _fold8(m, l, o, cm, cl, co): + active = cl > 0.0 + next_m = tl.where(active, tl.maximum(m, cm), m) + a = tl.where(active, tl.where(m == float("-inf"), 0.0, tl.exp(m - next_m)), 1.0) + b = tl.where(active, tl.exp(cm - next_m), 0.0) + return next_m, l * a + cl * b, o * a[:, None] + co * b[:, None] + + +@triton.jit +def _q8(x): + """Rows of bf16 as the cache keeps them: e4m3 of x * (448 / amax) widened back to bf16, and s = amax / 448 + (kv_quant's rule: two IEEE divisions a row, one IEEE product an element).""" + + x = x.to(tl.float32) + amax = tl.max(tl.abs(x), 1) + s = tl.where(amax > 0, tl.math.div_rn(amax, 448.0), 1.0) + inv = tl.where(amax > 0, tl.math.div_rn(448.0, amax), 1.0) + return (x * inv[:, None]).to(tl.float8e4nv).to(tl.bfloat16), s + + +@triton.jit +def _shared8(Q, KC, VC, KS, VS, OFF, STREAM, ITEMS, PO, PM, PL, W, H: tl.constexpr, HK: tl.constexpr, + D: tl.constexpr, G: tl.constexpr, CH: tl.constexpr, SCALE: tl.constexpr, GR: tl.constexpr): + """_shared over the fp8 cache; OFF holds four offsets a stream: keys and values (bytes), their scales (fp32).""" + + item = tl.program_id(0) // HK + hk = tl.program_id(0) % HK + s = tl.load(ITEMS + item * 3) + first = tl.load(ITEMS + item * 3 + 1) + code = tl.load(ITEMS + item * 3 + 2) + start = tl.load(STREAM + s * 4) + rows = tl.load(STREAM + s * 4 + 1) + p = tl.load(STREAM + s * 4 + 2) + groups = ((p + rows + CH - 1) // CH - tl.load(STREAM + s * 4 + 3)) // (GR - 1) + whole = code >= 0 + chunk = tl.where(whole, code * GR, groups * GR - 1 - code) + n = tl.where(whole, GR, 1) + slot = tl.where(whole, code, chunk - groups * (GR - 1)) + if ((chunk + n) * CH <= p) & (code < groups): + koff = tl.multiple_of(tl.load(OFF + s * 4), 16) + voff = tl.multiple_of(tl.load(OFF + s * 4 + 1), 16) + ksoff = tl.load(OFF + s * 4 + 2) + vsoff = tl.load(OFF + s * 4 + 3) + rr = first + tl.arange(0, 16) + ok = rr < rows * G + node = start + rr // G + head = hk * G + rr % G + d = tl.arange(0, D) + q = tl.load(Q + (node[:, None] * H + head[:, None]) * D + d[None, :], mask=ok[:, None], + other=0).to(tl.bfloat16) + gm = tl.full((16,), float("-inf"), tl.float32) + gl = tl.zeros((16,), tl.float32) + go = tl.zeros((16, D), tl.float32) + m, l, o = gm, gl, go + for c in range(n): + key = (chunk + c) * CH + tl.arange(0, 64) + m = tl.full((16,), float("-inf"), tl.float32) + l = tl.zeros((16,), tl.float32) + o = tl.zeros((16, D), tl.float32) + for t in range(CH // 64): + ki = key + t * 64 + kk = tl.load(KC + koff + (ki[:, None] * HK + hk) * D + d[None, :]).to(tl.bfloat16) + vv = tl.load(VC + voff + (ki[:, None] * HK + hk) * D + d[None, :]).to(tl.bfloat16) + ks = tl.load(KS + ksoff + ki * HK + hk) + vs = tl.load(VS + vsoff + ki * HK + hk) + m, l, o = _tile8(q, kk, vv, ks, vs, m, l, o, ki < p, SCALE) + gm, gl, go = _fold8(gm, gl, go, m, l, o) + if not whole: + gm, gl, go = m, l, o + base = (slot * W + node) * H + head + tl.store(PO + base[:, None] * D + d[None, :], go, mask=ok[:, None]) + tl.store(PM + base, gm, mask=ok) + tl.store(PL + base, gl, mask=ok) + + +@triton.jit +def _tail8(Q, KN, VN, KC, VC, KS, VS, OFF, STREAM, ROWS, PATHS, DEPTHS, PO, PM, PL, W, H: tl.constexpr, + HK: tl.constexpr, D: tl.constexpr, G: tl.constexpr, CH: tl.constexpr, MAXD: tl.constexpr, + SCALE: tl.constexpr, GR: tl.constexpr): + """_tail over the fp8 cache; the row's own path quantized as its commit will, so a key's bits never depend on + whether it is committed or in the window (nor on drafts, or how streams share a round).""" + + node = tl.program_id(0) + hk = tl.program_id(1) + s = tl.load(ROWS + node) + p = tl.load(STREAM + s * 4 + 2) + nch = (p + tl.load(STREAM + s * 4 + 1) + CH - 1) // CH + groups = (nch - tl.load(STREAM + s * 4 + 3)) // (GR - 1) + chunk = p // CH + tl.program_id(2) + if chunk < nch: + koff = tl.multiple_of(tl.load(OFF + s * 4), 16) + voff = tl.multiple_of(tl.load(OFF + s * 4 + 1), 16) + ksoff = tl.load(OFF + s * 4 + 2) + vsoff = tl.load(OFF + s * 4 + 3) + gg = tl.arange(0, 16) + d = tl.arange(0, D) + q = tl.load(Q + (node * H + hk * G + gg[:, None]) * D + d[None, :], mask=gg[:, None] < G, other=0).to(tl.bfloat16) + depth = tl.load(DEPTHS + node) + m = tl.full((16,), float("-inf"), tl.float32) + l = tl.zeros((16,), tl.float32) + o = tl.zeros((16, D), tl.float32) + key = chunk * CH + tl.arange(0, 64) + for t in range(CH // 64): + logical = key + t * 64 + committed = logical < p + path_slot = logical - p + on_path = (path_slot >= 0) & (path_slot < depth) + path_node = tl.load(PATHS + node * MAXD + path_slot, mask=on_path, other=0) + kc = tl.load(KC + koff + (logical[:, None] * HK + hk) * D + d[None, :], mask=committed[:, None], other=0.0) + vc = tl.load(VC + voff + (logical[:, None] * HK + hk) * D + d[None, :], mask=committed[:, None], other=0.0) + ks = tl.load(KS + ksoff + logical * HK + hk, mask=committed, other=1.0) + vs = tl.load(VS + vsoff + logical * HK + hk, mask=committed, other=1.0) + kn = tl.zeros((64, D), tl.bfloat16) + vn = tl.zeros((64, D), tl.bfloat16) + kns = tl.full((64,), 1.0, tl.float32) + vns = tl.full((64,), 1.0, tl.float32) + if tl.max(on_path.to(tl.int32), 0) > 0: # a tile of committed keys only skips the quantizing + kn, kns = _q8(tl.load(KN + (path_node[:, None] * HK + hk) * D + d[None, :], mask=on_path[:, None], other=0)) + vn, vns = _q8(tl.load(VN + (path_node[:, None] * HK + hk) * D + d[None, :], mask=on_path[:, None], other=0)) + kk = tl.where(committed[:, None], kc.to(tl.bfloat16), kn) + vv = tl.where(committed[:, None], vc.to(tl.bfloat16), vn) + ks = tl.where(committed, ks, kns) + vs = tl.where(committed, vs, vns) + m, l, o = _tile8(q, kk, vv, ks, vs, m, l, o, committed | on_path, SCALE) + base = ((chunk - groups * (GR - 1)) * W + node) * H + hk * G + gg + tl.store(PO + base[:, None] * D + d[None, :], o, mask=gg[:, None] < G) + tl.store(PM + base, m, mask=gg < G) + tl.store(PL + base, l, mask=gg < G) + + +def quantize(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """(n, HK, D) bf16 rows as e4m3 and one fp32 scale a row: the native kv_quant kernel's rule.""" + + amax = x.float().abs().amax(-1) + # tensor by tensor: IEEE division, as kv_quant's __fdiv_rn (torch divides by a Python float as a reciprocal) + full = torch.full_like(amax, FP8_MAX) + scale = torch.where(amax > 0, amax / full, torch.ones_like(amax)) + inv = torch.where(amax > 0, full / amax, torch.ones_like(amax)) + q = (x.float() * inv[..., None]).clamp(-FP8_MAX, FP8_MAX).to(torch.float8_e4m3fn) + return q, scale + + +def attention8(q, kn, vn, origin, kc8, vc8, ks, vs, p: "A.Plan", scale: float): + """attention.attention with the fp8 cache of one stream (offsets from ``origin``, as the engine passes them).""" + + import tensorfold.cuda.kernels.attention as A + + w, h, d = q.shape + hk = kn.shape[1] + g = h // hk + o8 = origin.view(torch.float8_e4m3fn) + of = origin.view(torch.float32) + b = origin.data_ptr() + offs = torch.tensor([[kc8.data_ptr() - b, vc8.data_ptr() - b, (ks.data_ptr() - b) // 4, (vs.data_ptr() - b) // 4]], + dtype=torch.int64, device=q.device) + po = torch.empty((p.chunks, w, h, d), dtype=torch.float32, device=q.device) + pm = torch.empty((p.chunks, w, h), dtype=torch.float32, device=q.device) + pl = torch.empty_like(pm) + if p.items.shape[0]: + _shared8[(p.items.shape[0] * hk,)](q, o8, o8, of, of, offs, p.streams, p.items, po, pm, pl, w, H=h, HK=hk, D=d, + G=g, CH=A.CHUNK, SCALE=scale, GR=A.GROUP, num_warps=4, num_stages=1) + tails = 1 + -(-A.MAX_NODES // A.CHUNK) + _tail8[(w, hk, tails)](q, kn, vn, o8, o8, of, of, offs, p.streams, p.rows, p.paths, p.depths, po, pm, pl, w, H=h, + HK=hk, D=d, G=g, CH=A.CHUNK, MAXD=A.MAX_NODES, SCALE=scale, GR=A.GROUP, num_warps=4, + num_stages=1) + out = torch.empty_like(q) + A._merge[(w, hk, d // A.MERGE_COLUMNS)](po, pm, pl, out, p.streams, p.rows, w, H=h, D=d, G=g, DS=A.MERGE_COLUMNS, + CH=A.CHUNK, GR=A.GROUP, num_warps=4) + return out + + +def check(p_len: int, parents: list[int], dev) -> float: + """attention8 against attention.attention over the dequantized cache: the worst row's cosine.""" + + import tensorfold.cuda.kernels.attention as A + + torch.manual_seed(p_len * 131 + len(parents)) + h, hk, d = 24, 4, 256 + w = len(parents) + cap = p_len + 64 + k = torch.randn((cap, hk, d), device=dev).mul(3).to(torch.bfloat16) + v = torch.randn((cap, hk, d), device=dev).to(torch.bfloat16) + k8, ks = quantize(k) + v8, vs = quantize(v) + kd = (k8.float() * ks[..., None]).to(torch.bfloat16) + vd = (v8.float() * vs[..., None]).to(torch.bfloat16) + q = torch.randn((w, h, d), device=dev).to(torch.bfloat16) + kn = torch.randn((w, hk, d), device=dev).mul(3).to(torch.bfloat16) + vn = torch.randn((w, hk, d), device=dev).to(torch.bfloat16) + plan = A.plan([parents], [p_len], h // hk, dev) + scale = d ** -0.5 + kq, kqs = quantize(kn) + vq, vqs = quantize(vn) + knd = (kq.float() * kqs[..., None]).to(torch.bfloat16) + vnd = (vq.float() * vqs[..., None]).to(torch.bfloat16) + ref = A.attention(q, knd, vnd, torch.tensor([A.offsets([(kd, vd)], dev)], dtype=torch.int64, device=dev), plan, + scale=scale) + got = attention8(q, kn, vn, A.base(dev).view(torch.uint8), k8, v8, ks, vs, plan, scale) + cos = torch.nn.functional.cosine_similarity(ref.float().view(w * h, d), got.float().view(w * h, d), dim=1) + if parents == list(range(-1, w - 1)) and w > 1: + # a chain's first row committed instead: the other rows' outputs must keep their bits + k8b = torch.cat([k8[:p_len], kq[:1], k8[p_len + 1:]]) + ksb = torch.cat([ks[:p_len], kqs[:1], ks[p_len + 1:]]) + v8b = torch.cat([v8[:p_len], vq[:1], v8[p_len + 1:]]) + vsb = torch.cat([vs[:p_len], vqs[:1], vs[p_len + 1:]]) + plan_b = A.plan([list(range(-1, w - 2))], [p_len + 1], h // hk, dev) + got_b = attention8(q[1:].contiguous(), kn[1:].contiguous(), vn[1:].contiguous(), A.base(dev).view(torch.uint8), + k8b, v8b, ksb, vsb, plan_b, scale) + same = torch.equal(got[1:], got_b) + print(f" committed vs in-window keys: {'bit-identical' if same else 'DIFFER'}", flush=True) + if not same: + return 0.0 + return float(cos.min()) + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--out", required=True) + ap.add_argument("--tools", required=True, help="folder of triton_aot_manifest.py") + a = ap.parse_args() + sys.path.insert(0, a.tools) + import triton_aot_manifest as aot + + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + rec = aot.Recorder().install() + rec.detail = True + dev = torch.device("cuda:0") + worst = 1.0 + # W of 1 (decode), 16 (a divisible verify window), 7 and 33 (neither); committed keys under and over a group + cases = [(0, [-1]), (700, [-1]), (5000, [-1]), (9000, list(range(-1, 15))), (3000, [-1, 0, 1, 1, 3, 4, 2]), + (20000, [-1] + list(range(32))), (300, list(range(-1, 15)))] + for p_len, parents in cases: + c = check(p_len, parents, dev) + worst = min(worst, c) + print(f"p={p_len} w={len(parents)}: worst row cosine {c:.6f}", flush=True) + rec.dump(out / "launches.json") + from triton.runtime.jit import JITFunction + import gc + + spec = {} + for fn in gc.get_objects(): + if isinstance(fn, JITFunction): + spec[f"{fn.fn.__module__}.{fn.fn.__qualname__}"] = { + "params": [x.name for x in fn.params], + "do_not_specialize": [x.name for x in fn.params if x.do_not_specialize], + "no_align": [x.name for x in fn.params if x.do_not_specialize_on_alignment]} + (out / "jit.json").write_text(json.dumps(spec, indent=1, sort_keys=True) + "\n") + print(f"worst {worst:.6f}") + return 0 if worst > 0.995 else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) From 06cc8115601c9599598d6309d0124264a7bfec0c Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 12 Oct 2026 12:42:06 +0000 Subject: [PATCH 10/17] qwen27 CUDA: a prompt cache, so a chat's next turn resumes its kept state The 27B serves the shared prompt cache (core/prompt_cache.zig) as Nemotron does, its copies in pinned host memory: a long window's caches leave the device no room for them. - reuse.zig: a kept state is a stream's DeltaNet recurrences and conv windows whole and its attention rows (and fp8 scales) through the mark, about 275 MiB at 4,096 tokens under fp8 - with a cache, prompts cut the zero-anchored 4,096-row grid (engine.Chunks), so a pass resumed or kept at a grid point computes what a fresh pass of the same prompt does; without one (--prompt-cache-gib 0, and tf-qwen27-cuda) the even splits stay, bit-exact against 0.6.6 - prefillFrom (engine, lone): a restored stream's pass from its grid point, stopping at the lane host's marks; a resumed drafting stream's context holds only the rows it read (drafts change no token) - image prompts neither resume nor keep (their rows' positions are the tower's) - native/cuda.zig: each family's snapshot vtable, and a host-memory budget (8 GiB or --prompt-cache-gib, at most half of MemAvailable) for a family whose copies live there - zig fmt over native/cuda.zig and qwen27/cuda/triton.zig (the fmt check) The qwen suite's soak check: 60/60 replies equal to the same request alone and 60/60 turns resumed (0/60 resumed before), in 117 s against 244 s; drafts, concurrent and behaviour unchanged. --- zig/src/families/qwen27/cuda.zig | 2 + zig/src/families/qwen27/cuda/engine.zig | 70 +++++++++++-- zig/src/families/qwen27/cuda/lanes.zig | 36 ++++++- zig/src/families/qwen27/cuda/lone.zig | 23 +++-- zig/src/families/qwen27/cuda/native.zig | 20 +++- zig/src/families/qwen27/cuda/reuse.zig | 126 ++++++++++++++++++++++++ zig/src/families/qwen27/cuda/triton.zig | 6 +- zig/src/native/cuda.zig | 34 ++++--- 8 files changed, 283 insertions(+), 34 deletions(-) create mode 100644 zig/src/families/qwen27/cuda/reuse.zig diff --git a/zig/src/families/qwen27/cuda.zig b/zig/src/families/qwen27/cuda.zig index 650f1748ef..3e10f18896 100644 --- a/zig/src/families/qwen27/cuda.zig +++ b/zig/src/families/qwen27/cuda.zig @@ -16,6 +16,7 @@ pub const lone = @import("cuda/lone.zig"); pub const drafts = @import("cuda/drafts.zig"); pub const vision = @import("cuda/vision.zig"); pub const image = @import("cuda/image.zig"); +pub const reuse = @import("cuda/reuse.zig"); test { _ = config; @@ -34,4 +35,5 @@ test { _ = native; _ = vision; _ = image; + _ = reuse; } diff --git a/zig/src/families/qwen27/cuda/engine.zig b/zig/src/families/qwen27/cuda/engine.zig index de2c8ddd5c..af3c6594b4 100644 --- a/zig/src/families/qwen27/cuda/engine.zig +++ b/zig/src/families/qwen27/cuda/engine.zig @@ -20,6 +20,45 @@ pub fn chunkBounds(start: usize, end: usize, size: usize, j: usize) [2]usize { return .{ start + (end - start) * j / n, start + (end - start) * (j + 1) / n }; } +/// A prompt's chunks from `from`: even splits of the whole prompt (0.6.6's PrefillPlan), or under a prompt cache the +/// zero-anchored grid, so a pass resumed or kept at a grid point cuts where a fresh pass of the same prompt does. +pub const Chunks = struct { + len: usize, + grid: bool, + at: usize, + j: usize = 0, + + pub fn init(len: usize, from: usize, grid: bool) Chunks { + return .{ .len = len, .grid = grid, .at = from }; + } + + pub fn next(x: *Chunks) ?[2]usize { + if (x.at >= x.len) return null; + const b: [2]usize = if (x.grid) .{ x.at, @min(x.len, x.at - x.at % prompt_rows + prompt_rows) } else chunkBounds(0, x.len, prompt_rows, x.j); + x.at = b[1]; + x.j += 1; + return b; + } +}; + +/// A state the cache may resume: a grid point inside the prompt. +pub fn resumable(from: usize, len: usize) bool { + return from > 0 and from < len and from % prompt_rows == 0; +} + +/// Where a prompt pass stops to let the cache copy its state (ascending grid points), and who copies it. +pub const Keep = struct { + at: []const u32, + ctx: *anyopaque, + call: *const fn (ctx: *anyopaque, at: u32) void, + + /// Call the keep for a chunk that ended at `end`. + pub fn after(k: ?Keep, end: usize) void { + const x = k orelse return; + for (x.at) |m| if (m == end) x.call(x.ctx, m); + } +}; + pub const Options = struct { context: usize, kv8: bool = false }; pub const Engine = struct { @@ -31,6 +70,7 @@ pub const Engine = struct { scratch: st.Scratch, context: usize, kv8: bool, // --kv-cache fp8: every stream's attention caches e4m3 with a scale a row + grid: bool = false, // a prompt cache: prompts in zero-anchored chunks (Chunks), not even splits pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: []const u8, o: Options) !*Engine { const cfg = try c.Config.read(gpa, io, dir); @@ -87,21 +127,25 @@ pub const Engine = struct { /// prefill with an image prompt's rows and positions (null: text); its decode offset stays on the stream. pub fn prefillMedia(e: *Engine, seq: *st.Seq, prompt: []const u32, media: ?*const vision.Media) !void { + return e.prefillFrom(seq, prompt, 0, media, null); + } + + /// The prompt from `from` (0, or a grid point the stream's state was restored at), keeping states at `keep`'s marks. + pub fn prefillFrom(e: *Engine, seq: *st.Seq, prompt: []const u32, from: usize, media: ?*const vision.Media, keep: ?Keep) !void { if (prompt.len == 0) return error.EmptyPrompt; if (prompt.len >= seq.capacity) return error.PromptTooLong; - try seq.reset(e.ops(), e.w.g); + if (from == 0) try seq.reset(e.ops(), e.w.g) else if (from != seq.pos or !resumable(from, prompt.len)) return error.BadReuse; seq.media = media; defer seq.media = null; var f = e.forward(); - const n = (prompt.len + prompt_rows - 1) / prompt_rows; - for (0..n) |j| { - const b = chunkBounds(0, prompt.len, prompt_rows, j); - try f.chunk(prompt[b[0]..b[1]], seq, j == n - 1); + var it = Chunks.init(prompt.len, from, e.grid); + while (it.next()) |b| { + try f.chunk(prompt[b[0]..b[1]], seq, b[1] == prompt.len); + Keep.after(keep, b[1]); } if (media) |m| seq.rope_delta = m.delta; } - /// decode.serial_decode, greedy: one-row windows from `pending` until `count` tokens or an end token. pub fn decode(e: *Engine, seq: *st.Seq, pending: u32, count: usize, out: *std.ArrayList(u32)) !void { var f = e.forward(); try out.append(e.gpa, pending); @@ -128,6 +172,20 @@ pub const Engine = struct { } }; +test "a cached prompt cuts the zero-anchored grid, resumed or not" { + var it = Chunks.init(9000, 0, true); + try std.testing.expectEqual([2]usize{ 0, 4096 }, it.next().?); + try std.testing.expectEqual([2]usize{ 4096, 8192 }, it.next().?); + try std.testing.expectEqual([2]usize{ 8192, 9000 }, it.next().?); + try std.testing.expectEqual(@as(?[2]usize, null), it.next()); + var resumed = Chunks.init(9000, 4096, true); + try std.testing.expectEqual([2]usize{ 4096, 8192 }, resumed.next().?); + var even = Chunks.init(5078, 0, false); + try std.testing.expectEqual([2]usize{ 0, 2539 }, even.next().?); + try std.testing.expectEqual([2]usize{ 2539, 5078 }, even.next().?); + try std.testing.expect(resumable(4096, 5000) and !resumable(4096, 4096) and !resumable(3000, 5000) and !resumable(0, 5000)); +} + test "prefill.chunks splits evenly" { try std.testing.expectEqual([2]usize{ 0, 2539 }, chunkBounds(0, 5078, 4096, 0)); try std.testing.expectEqual([2]usize{ 2539, 5078 }, chunkBounds(0, 5078, 4096, 1)); diff --git a/zig/src/families/qwen27/cuda/lanes.zig b/zig/src/families/qwen27/cuda/lanes.zig index d88d43baf6..adae5d4913 100644 --- a/zig/src/families/qwen27/cuda/lanes.zig +++ b/zig/src/families/qwen27/cuda/lanes.zig @@ -7,7 +7,9 @@ const st = @import("state.zig"); const Engine = @import("engine.zig").Engine; const Part = @import("forward.zig").Part; const Forward = @import("forward.zig").Forward; -const prompt_rows = @import("engine.zig").prompt_rows; +const eng = @import("engine.zig"); +const prompt_rows = eng.prompt_rows; +const reuse = @import("reuse.zig"); const dl = @import("draft_load.zig"); const dr = @import("draft.zig"); const drafts = @import("drafts.zig"); @@ -228,7 +230,8 @@ pub const Cuda = struct { try x.prefillOpened(s, seq); } - /// prefill_state into an opened stream: the prompt in chunks, a drafting stream's last window of taps absorbed. + /// prefill_state into an opened stream: the prompt in chunks, a drafting stream's last window of taps absorbed. A + /// kept state the lane host found is restored first, and the pass stops at its marks for the cache to copy. fn prefillOpened(x: *Cuda, s: *lanes.Stream, seq: *st.Seq) !void { // an image prompt: the tower's rows and the prompt's three positions for its pass (EncodedVision) const media: ?*vision.Media = if (s.images.len == 0) null else blk: { @@ -237,11 +240,36 @@ pub const Cuda = struct { break :blk try vision.Media.init(x.gpa, tower, gpu, s.prompt(), s.images, prompt_rows); }; defer if (media) |m| m.deinit(); + const from = x.restoreKept(s, seq, media != null); + // an image prompt keeps nothing: its rows' positions are the tower's, not the tokens' + const marks: ?eng.Keep = if (s.reuse.marks.len == 0 or media != null) null else .{ .at = s.reuse.marks, .ctx = s, .call = keptAt }; if (x.drafter) |d| if (s.drafts) { const ds = try x.draftingOf(s); - return lone.prefillMedia(x.e, seq, &ds.ctx, d, s.prompt(), media); + return lone.prefillFrom(x.e, seq, &ds.ctx, d, s.prompt(), from, media, marks); }; - try x.e.prefillMedia(seq, s.prompt(), media); + try x.e.prefillFrom(seq, s.prompt(), from, media, marks); + } + + /// The stream's kept state restored on its sequence: where its prompt pass starts (0: none, off the grid, failed). + fn restoreKept(x: *Cuda, s: *lanes.Stream, seq: *st.Seq, image: bool) usize { + s.cached = 0; + const saved = s.reuse.saved orelse return 0; + if (image or !x.e.grid or !eng.resumable(s.reuse.at, s.prompt().len)) { + s.reuse_failed = true; + return 0; + } + reuse.restoreSeq(x.e, seq, saved) catch { + s.reuse_failed = true; + return 0; + }; + s.cached = s.reuse.at; + return s.reuse.at; + } + + /// The prompt pass stands at a mark: the lane host copies the stream's state there. + fn keptAt(ctx: *anyopaque, at: u32) void { + const s: *lanes.Stream = @ptrCast(@alignCast(ctx)); + if (s.reuse.hook) |k| k.at(k.ptr, s, at); } /// prefill_batch: prompts in shared passes of at most a chunk's rows (a longer one alone, in its chunks). diff --git a/zig/src/families/qwen27/cuda/lone.zig b/zig/src/families/qwen27/cuda/lone.zig index 6aa91e3fe3..bb384e9ce4 100644 --- a/zig/src/families/qwen27/cuda/lone.zig +++ b/zig/src/families/qwen27/cuda/lone.zig @@ -8,7 +8,8 @@ const tree = @import("tree.zig"); const kern = @import("kernels.zig"); const dr = @import("draft.zig"); const dl = @import("draft_load.zig"); -const Engine = @import("engine.zig").Engine; +const eng = @import("engine.zig"); +const Engine = eng.Engine; const Forward = @import("forward.zig").Forward; const Part = @import("forward.zig").Part; const Lanes = @import("lanes.zig").Cuda; @@ -77,7 +78,14 @@ pub fn prefill(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, promp /// prefill with an image prompt's rows and positions (null: text); its decode offset stays on the stream. pub fn prefillMedia(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, prompt: []const u32, media: ?*const @import("vision.zig").Media) !void { - try seq.reset(e.ops(), e.w.g); + return prefillFrom(e, seq, ctx, d, prompt, 0, media, null); +} + +/// prefillMedia from `from` (0, or the grid point a kept state was restored at), keeping states at `keep`'s marks. A +/// resumed pass's context holds only the rows it read: drafts change no token, so a reply is the same either way. +pub fn prefillFrom(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, prompt: []const u32, from: usize, media: ?*const @import("vision.zig").Media, keep: ?eng.Keep) !void { + if (prompt.len >= seq.capacity) return error.PromptTooLong; + if (from == 0) try seq.reset(e.ops(), e.w.g) else if (from != seq.pos or !eng.resumable(from, prompt.len)) return error.BadReuse; seq.media = media; defer seq.media = null; defer if (media) |m| { @@ -85,15 +93,14 @@ pub fn prefillMedia(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, }; ctx.len = 0; ctx.end = 0; - const tap_from = prompt.len -| dl.window; + const tap_from = @max(from, prompt.len -| dl.window); ctx.skip(tap_from); var f = e.forward(); f.taps = e.scratch.taps; - const rows = @import("engine.zig").prompt_rows; - const chunks = (prompt.len + rows - 1) / rows; - for (0..chunks) |j| { - const b = @import("engine.zig").chunkBounds(0, prompt.len, rows, j); - try f.chunk(prompt[b[0]..b[1]], seq, j == chunks - 1); + var it = eng.Chunks.init(prompt.len, from, e.grid); + while (it.next()) |b| { + try f.chunk(prompt[b[0]..b[1]], seq, b[1] == prompt.len); + eng.Keep.after(keep, b[1]); if (b[1] <= tap_from) continue; const skip = tap_from -| b[0]; try d.absorb(ctx, e.scratch.taps + skip * taps_width * bf, b[1] - b[0] - skip); diff --git a/zig/src/families/qwen27/cuda/native.zig b/zig/src/families/qwen27/cuda/native.zig index 32833fe00c..0add28111d 100644 --- a/zig/src/families/qwen27/cuda/native.zig +++ b/zig/src/families/qwen27/cuda/native.zig @@ -10,6 +10,7 @@ const Lanes = @import("lanes.zig").Cuda; const dr = @import("draft.zig"); const vision = @import("vision.zig"); const image = @import("image.zig"); +const reuse = @import("reuse.zig"); pub const model_type = "qwen3_5"; pub const formats: []const []const u8 = &.{"mlx-q4g64"}; @@ -17,6 +18,20 @@ pub const default_context: i64 = 32768; pub const max_segments: u32 = 1; pub const prompt_rows: u32 = engine.prompt_rows; +/// Prompt-cache copies (reuse.zig), kept in pinned host memory; a state ends where its prompt pass stands. +pub const snap_bytes = reuse.bytes; +pub const snap_save = reuse.save; +pub const snap_restore = reuse.restore; +pub const snap_drop = reuse.drop; +pub const snap_host = true; +pub const snap_lookahead: u32 = 0; + +/// The server keeps prompt states: prompts cut the zero-anchored grid, where kept states resume. +pub fn useCache(p: *anyopaque) void { + const own: *Owned = @ptrCast(@alignCast(p)); + own.e.grid = true; +} + pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, drafter: ?[]const u8 = null, vision: ?Vision = null, kv8: bool = false }; /// --vision's limits: the visual tokens a request's images share, and its images. @@ -50,9 +65,10 @@ pub const Loaded = struct { ctx: *anyopaque, deinit: *const fn (*anyopaque) void, lone: ?LoneRun = null, + target: *reuse.Target, // what the prompt cache copies (reuse.zig) }; -const Owned = struct { gpa: std.mem.Allocator, e: *engine.Engine, lanes: Lanes, draft: ?*dr.DFlash2 = null, tower: ?*vision.Tower = null }; +const Owned = struct { gpa: std.mem.Allocator, e: *engine.Engine, lanes: Lanes, target: reuse.Target = undefined, draft: ?*dr.DFlash2 = null, tower: ?*vision.Tower = null }; /// The drafter the Python engine pairs with the 27B once pulled (z-lab/Qwen3.8-27B-DFlash2). const drafter_repo = "models--z-lab--Qwen3.8-27B-DFlash2"; @@ -89,6 +105,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ errdefer gpa.destroy(own); own.* = .{ .gpa = gpa, .e = e, .lanes = try Lanes.init(gpa, e, most_streams) }; errdefer own.lanes.deinit(); + own.target = .{ .e = e, .seqs = &own.lanes.seqs }; if (o.drafts) if (try drafterDir(gpa, io, o.drafter)) |draft_dir| { defer gpa.free(draft_dir); const f = e.forward(); @@ -115,6 +132,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ .vision_bytes = vision_bytes, .ctx = own, .deinit = release, + .target = &own.target, }; } diff --git a/zig/src/families/qwen27/cuda/reuse.zig b/zig/src/families/qwen27/cuda/reuse.zig new file mode 100644 index 0000000000..750569c852 --- /dev/null +++ b/zig/src/families/qwen27/cuda/reuse.zig @@ -0,0 +1,126 @@ +//! Qwen3.8-27B CUDA prompt states for the shared cache: a stream's DeltaNet recurrences, conv windows and its attention +//! rows so far, copied to pinned host memory (a long window's caches leave the device no room for copies). + +const std = @import("std"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const c = @import("shape.zig"); +const st = @import("state.zig"); +const Engine = @import("engine.zig").Engine; + +/// One kept state: the copy and the position it holds. +pub const Copy = struct { + host: cuda.HostBuffer, + at: usize, +}; + +/// The engine and the streams' states a save copies. The native host keeps one of these for the loaded model. +pub const Target = struct { + e: *Engine, + seqs: *std.AutoHashMapUnmanaged(*lanes.Stream, *st.Seq), +}; + +/// One piece of a stream's state: its device address and length. +const Piece = struct { dev: u64, len: usize }; + +/// The pieces a state at `at` holds, in their order in a copy: each DeltaNet layer's recurrence and conv window, each +/// attention layer's first `at` key and value rows (and their scales under kv8). `seq` null: lengths only. +fn pieces(g: c.Geometry, kv8: bool, seq: ?*const st.Seq, at: usize, out: []Piece) []Piece { + var n: usize = 0; + const row: usize = g.kvInner() * @as(usize, if (kv8) 1 else 2); + for (0..g.layers) |i| { + if (c.linear(i)) { + out[n] = .{ .dev = if (seq) |s| s.rec[i] else 0, .len = g.deltaBytes() }; + out[n + 1] = .{ .dev = if (seq) |s| s.conv[i] else 0, .len = g.convBytes() }; + n += 2; + continue; + } + out[n] = .{ .dev = if (seq) |s| s.keys[i] else 0, .len = at * row }; + out[n + 1] = .{ .dev = if (seq) |s| s.values[i] else 0, .len = at * row }; + n += 2; + if (kv8) { + out[n] = .{ .dev = if (seq) |s| s.kscale[i] else 0, .len = at * g.kv_heads * 4 }; + out[n + 1] = .{ .dev = if (seq) |s| s.vscale[i] else 0, .len = at * g.kv_heads * 4 }; + n += 2; + } + } + return out[0..n]; +} + +const max_pieces = 4 * 128; + +fn total(g: c.Geometry, kv8: bool, at: usize) u64 { + var buf: [max_pieces]Piece = undefined; + var n: u64 = 0; + for (pieces(g, kv8, null, at, &buf)) |p| n += p.len; + return n; +} + +/// Host bytes a save at `at` takes. +pub fn bytes(ptr: *anyopaque, at: u32) u64 { + const t: *Target = @ptrCast(@alignCast(ptr)); + return total(t.e.w.g, t.e.kv8, at); +} + +/// Copy the stream's state after `at` prompt tokens. Its pass stands there. +pub fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { + const t: *Target = @ptrCast(@alignCast(ptr)); + const s: *lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoStream)); + const seq = t.seqs.get(s) orelse return error.UnknownStream; + if (seq.pos != at or seq.rope_delta != 0) return error.NotAtMark; + const e = t.e; + const copy = try e.gpa.create(Copy); + errdefer e.gpa.destroy(copy); + copy.* = .{ .host = try cuda.HostBuffer.alloc(e.ctx.d, total(e.w.g, e.kv8, at)), .at = at }; + errdefer copy.host.free(); + var buf: [max_pieces]Piece = undefined; + var off: usize = 0; + for (pieces(e.w.g, e.kv8, seq, at, &buf)) |p| { + try e.ops().download(copy.host.bytes[off..][0..p.len], p.dev); + off += p.len; + } + try e.s.synchronize(); + return copy; +} + +/// Make `seq` the kept state's: the next prompt chunk starts at its position. +pub fn restoreSeq(e: *Engine, seq: *st.Seq, saved: *anyopaque) !void { + const copy: *Copy = @ptrCast(@alignCast(saved)); + if (copy.at >= seq.capacity) return error.BadReuse; + var buf: [max_pieces]Piece = undefined; + var off: usize = 0; + for (pieces(e.w.g, e.kv8, seq, copy.at, &buf)) |p| { + try e.ops().upload(p.dev, copy.host.bytes[off..][0..p.len]); + off += p.len; + } + try e.s.synchronize(); // the host copy may be dropped once this returns + seq.pos = copy.at; + seq.rope_delta = 0; + seq.media = null; +} + +/// The store's restore: the owner's state made the kept one's. +pub fn restore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void { + const t: *Target = @ptrCast(@alignCast(ptr)); + const s: *lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoStream)); + return restoreSeq(t.e, t.seqs.get(s) orelse return error.UnknownStream, saved); +} + +/// Free a kept state's host copy. +pub fn drop(ptr: *anyopaque, saved: *anyopaque) void { + const t: *Target = @ptrCast(@alignCast(ptr)); + const copy: *Copy = @ptrCast(@alignCast(saved)); + copy.host.free(); + t.e.gpa.destroy(copy); +} + +test "a kept state holds the recurrences whole and the attention rows it read" { + const g = c.the_27b; + var buf: [max_pieces]Piece = undefined; + try std.testing.expectEqual(@as(usize, 48 * 2 + 16 * 2), pieces(g, false, null, 1, &buf).len); + try std.testing.expectEqual(@as(usize, 48 * 2 + 16 * 4), pieces(g, true, null, 1, &buf).len); + const fixed = total(g, false, 0); + try std.testing.expectEqual(fixed, 48 * (g.deltaBytes() + g.convBytes())); + try std.testing.expectEqual(fixed + 16 * 2 * 1000 * g.kvInner() * 2, total(g, false, 1000)); + try std.testing.expectEqual(fixed + 16 * 2 * 1000 * (g.kvInner() + g.kv_heads * 4), total(g, true, 1000)); +} diff --git a/zig/src/families/qwen27/cuda/triton.zig b/zig/src/families/qwen27/cuda/triton.zig index 2ed4e7e748..fcab03c8ef 100644 --- a/zig/src/families/qwen27/cuda/triton.zig +++ b/zig/src/families/qwen27/cuda/triton.zig @@ -126,13 +126,13 @@ pub const Tri = struct { const scale: f32 = @floatCast(std.math.pow(f64, @floatFromInt(a.dim), -0.5)); const w = plan.width; if (plan.n_items > 0) try t.run("_shared8", .{ u(plan.n_items * a.kv_heads), 1, 1 }, &.{ - p("Q", "*bf16", q), p("KC", "*fp8e4nv", base), p("VC", "*fp8e4nv", base), p("KS", "*fp32", base), p("VS", "*fp32", base), p("OFF", "*i64", offs), + p("Q", "*bf16", q), p("KC", "*fp8e4nv", base), p("VC", "*fp8e4nv", base), p("KS", "*fp32", base), p("VS", "*fp32", base), p("OFF", "*i64", offs), p("STREAM", "*i32", plan.streams), p("ITEMS", "*i32", plan.items), p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), int("W", w), }, &.{ ci("H", a.heads), ci("HK", a.kv_heads), ci("D", a.dim), ci("G", g), ci("CH", chunk), aot.cf("SCALE", scale), ci("GR", group_chunks) }); const tails = 1 + (max_nodes + chunk - 1) / chunk; try t.run("_tail8", .{ u(w), u(a.kv_heads), u(tails) }, &.{ - p("Q", "*bf16", q), p("KN", "*bf16", kn), p("VN", "*bf16", vn), p("KC", "*fp8e4nv", base), p("VC", "*fp8e4nv", base), p("KS", "*fp32", base), p("VS", "*fp32", base), p("OFF", "*i64", offs), - p("STREAM", "*i32", plan.streams), p("ROWS", "*i32", plan.rows), p("PATHS", "*i32", plan.paths), p("DEPTHS", "*i32", plan.depths), p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), int("W", w), + p("Q", "*bf16", q), p("KN", "*bf16", kn), p("VN", "*bf16", vn), p("KC", "*fp8e4nv", base), p("VC", "*fp8e4nv", base), p("KS", "*fp32", base), p("VS", "*fp32", base), p("OFF", "*i64", offs), + p("STREAM", "*i32", plan.streams), p("ROWS", "*i32", plan.rows), p("PATHS", "*i32", plan.paths), p("DEPTHS", "*i32", plan.depths), p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), int("W", w), }, &.{ ci("H", a.heads), ci("HK", a.kv_heads), ci("D", a.dim), ci("G", g), ci("CH", chunk), ci("MAXD", max_nodes), aot.cf("SCALE", scale), ci("GR", group_chunks) }); try t.run("_merge", .{ u(w), u(a.kv_heads), u(a.dim / merge_columns) }, &.{ p("PO", "*fp32", part.o), p("PM", "*fp32", part.m), p("PL", "*fp32", part.l), p("OUT", "*bf16", out), p("STREAM", "*i32", plan.streams), p("ROWS", "*i32", plan.rows), int("W", w), diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 03cb15e17b..d089a10e8b 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -13,13 +13,12 @@ const Pool = budget.Pool; /// CUDA families provide metadata, open their lane backend and explain their refusals. const registry = .{ nemotron.native, qwen27.native }; -/// Nemotron's prompt-cache copies. A file-level value so the store's pointer stays valid for the process. -const nemotron_snaps: api.prompt_cache.Snapshots.VTable = .{ - .bytes = nemotron.native.snap_bytes, - .save = nemotron.native.snap_save, - .restore = nemotron.native.snap_restore, - .drop = nemotron.native.snap_drop, -}; +/// A family's prompt-cache copies. A comptime value per family, so the store's pointer stays valid for the process. +fn Snaps(comptime F: type) type { + return struct { + const vtable: api.prompt_cache.Snapshots.VTable = .{ .bytes = F.snap_bytes, .save = F.snap_save, .restore = F.snap_restore, .drop = F.snap_drop }; + }; +} pub const backends: []const []const u8 = &.{"cuda"}; pub const families: []const api.Family = blk: { @@ -466,19 +465,22 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O const h = try gpa.create(Host); errdefer gpa.destroy(h); h.* = .{ .gpa = gpa, .gpu = g, .family = loaded.ctx, .release = loaded.deinit, .inner = loaded.backend, .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .lone = loaded.lone }; - // prompt-cache snapshots are Nemotron's (cuda_reuse.zig); a family without them serves without a cache - const cache = if (@hasDecl(F, "snap_bytes")) budget.cacheBytes(o.prompt_cache_gib, room, loaded.stream_bytes * (streams -| free)) else 0; + // a family with prompt-cache snapshots keeps them in device room (Nemotron) or in pinned host memory (the 27B, whose + // long window leaves the device none); a family without them serves without a cache + const cache = if (!@hasDecl(F, "snap_bytes")) 0 else if (@hasDecl(F, "snap_host")) hostCacheBytes(a, io, o.prompt_cache_gib) else budget.cacheBytes(o.prompt_cache_gib, room, loaded.stream_bytes * (streams -| free)); h.startup = try std.fmt.allocPrint(gpa, "CUDA sm_{d} device {d} ({s}{s}): model {d:.2} GiB{s}; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window{s}, of {d:.1} GiB left after a {d:.1} GiB reserve; prompts in {d}-row chunks{s}{s}; {s}", .{ - capability, device, name, if (after.unified) ", memory shared with the host" else "", toGib(model), if (loaded.learn_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for --slide's trainer", .{toGib(loaded.learn_bytes)}) else if (vision_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for the image tower's calls", .{toGib(vision_bytes)}) else "", streams, if (streams == 1) "" else "s", toGib(loaded.stream_bytes), window, if (o.kv8) " (fp8 caches)" else "", toGib(room), toGib(after.reserve), F.prompt_rows, if (segments > 1) try std.fmt.allocPrint(a, ", {d} staggered segments a call", .{segments}) else "", - if (cache > 0) try std.fmt.allocPrint(a, ", a {d:.1} GiB prompt cache", .{toGib(cache)}) else ", no prompt cache", if (kernels) |dir| try std.fmt.allocPrint(a, "glue kernels captured at {s}", .{dir}) else "own glue kernels", + capability, device, name, if (after.unified) ", memory shared with the host" else "", toGib(model), if (loaded.learn_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for --slide's trainer", .{toGib(loaded.learn_bytes)}) else if (vision_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for the image tower's calls", .{toGib(vision_bytes)}) else "", streams, if (streams == 1) "" else "s", toGib(loaded.stream_bytes), window, if (o.kv8) " (fp8 caches)" else "", toGib(room), toGib(after.reserve), F.prompt_rows, if (segments > 1) try std.fmt.allocPrint(a, ", {d} staggered segments a call", .{segments}) else "", + if (cache > 0) try std.fmt.allocPrint(a, ", a {d:.1} GiB prompt cache{s}", .{ toGib(cache), if (@hasDecl(F, "snap_host")) " in host memory" else "" }) else ", no prompt cache", if (kernels) |dir| try std.fmt.allocPrint(a, "glue kernels captured at {s}", .{dir}) else "own glue kernels", }); errdefer gpa.free(h.startup); if (@hasDecl(F, "snap_bytes") and cache > 0) { const pc = api.prompt_cache; const store = try gpa.create(pc.Store); // states kept and resumed on the family's grid, where a cache-off pass cuts; the head reads one token on - store.* = pc.Store.init(gpa, .{ .ptr = loaded.target, .vtable = &nemotron_snaps }, .{ .lookahead = 1, .planned = true, .grid = F.prompt_rows }, cache); + // Nemotron's head reads one token on (lookahead 1); the 27B's states end where its prompt pass stands + store.* = pc.Store.init(gpa, .{ .ptr = loaded.target, .vtable = &Snaps(F).vtable }, .{ .lookahead = if (@hasDecl(F, "snap_lookahead")) F.snap_lookahead else 1, .planned = true, .grid = F.prompt_rows }, cache); h.store = store; + if (@hasDecl(F, "useCache")) F.useCache(loaded.ctx); } errdefer if (h.store) |store| { store.deinit(); @@ -522,6 +524,14 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O return .{ .engine = h.host.engine(), .close = Host.close, .ctx = h }; } +/// A host-memory prompt cache: --prompt-cache-gib, else 8 GiB, at most half the host's available memory. +fn hostCacheBytes(a: Allocator, io: std.Io, asked: ?f64) u64 { + const want: u64 = if (asked) |g| (if (g > 0) std.math.lossyCast(u64, g * gib) else 0) else 8 << 30; + const text = procText(a, io, "/proc/meminfo") orelse return 0; + const m = budget.meminfo(text) orelse return 0; + return @min(want, m.available / 2); +} + fn toGib(bytes: u64) f64 { return @as(f64, @floatFromInt(bytes)) / gib; } From d49a906ffc168d707f62be598d329bf8dd8f5e2d Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:08:50 +0000 Subject: [PATCH 11/17] qwen27 CUDA: no tooling that imports the Python engine in the tree attention_kv8.py (which records the fp8 attention launches) and qwen_vision_fixtures.py (which records the vision fixtures) import tensorfold, so they move out of the tree; their recordings stay fixture files, made once outside it. --- tools/zig/qwen_vision_fixtures.py | 103 --------- zig/src/cli/qwen27_cuda.zig | 5 +- zig/src/families/qwen27/cuda/triton.zig | 5 +- zig/tests/cuda/qwen27/attention_kv8.py | 296 ------------------------ 4 files changed, 6 insertions(+), 403 deletions(-) delete mode 100644 tools/zig/qwen_vision_fixtures.py delete mode 100644 zig/tests/cuda/qwen27/attention_kv8.py diff --git a/tools/zig/qwen_vision_fixtures.py b/tools/zig/qwen_vision_fixtures.py deleted file mode 100644 index 5f989a42ef..0000000000 --- a/tools/zig/qwen_vision_fixtures.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python3 -"""Fixtures for the native Qwen vision path, from TensorFold 0.6.6's --vision frontend and tower on CUDA. - -For a fixed image set: each image's file, its decoded RGB (images.py), its patches and grid (QwenImageProcessor's -processor at 0.6.6's per-image cap), and the tower's merged rows (QwenCudaVision, bf16, flash attention). The Zig -checks compare their own decode, patches and rows against these: ``tf-qwen27-cuda vision MODEL --fixtures DIR``. -""" - -from __future__ import annotations - -import argparse -import io -import json -from pathlib import Path - -import numpy as np - - -def images(): - """(name, encoded bytes) for the set: PNG layouts, sizes from tiny to large, an EXIF-rotated JPEG.""" - from PIL import Image, ImageDraw - - out = [] - shapes = Image.new("RGB", (517, 389), "white") - d = ImageDraw.Draw(shapes) - d.ellipse((30, 40, 230, 240), fill=(220, 20, 20)) - d.rectangle((280, 60, 490, 260), fill=(20, 60, 220)) - d.text((60, 300), "ORANGE 7351", fill="black") - rng = np.random.default_rng(7) - y, x = np.mgrid[0:768, 0:1024] - photo = np.stack([(x / 4) % 256, (y / 3) % 256, ((x + y) / 7) % 256], -1) + rng.normal(0, 12, (768, 1024, 3)) - photo = Image.fromarray(np.clip(photo, 0, 255).astype(np.uint8)) - large = photo.resize((2000, 1500)) - tiny = shapes.resize((20, 15)) - logo = Image.new("RGBA", (96, 96), (0, 0, 0, 0)) - ImageDraw.Draw(logo).ellipse((8, 8, 88, 88), fill=(30, 160, 90, 200)) - palette = shapes.convert("P", palette=Image.Palette.ADAPTIVE, colors=16) - palette.info["transparency"] = 0 - gray = photo.convert("L") - - def png(img, **kw): - b = io.BytesIO() - img.save(b, "PNG", **kw) - return b.getvalue() - - def jpeg(img, exif=None): - b = io.BytesIO() - img.save(b, "JPEG", quality=90, **({"exif": exif} if exif else {})) - return b.getvalue() - - exif = Image.Exif() - exif[0x0112] = 6 # rotate 90 on display - out += [("shapes.png", png(shapes)), ("photo.png", png(photo)), ("large.png", png(large)), - ("tiny.png", png(tiny)), ("logo.png", png(logo)), ("palette.png", png(palette)), ("gray.png", png(gray)), - ("photo.jpg", jpeg(photo)), ("rotated.jpg", jpeg(shapes, exif.tobytes()))] - return out - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument("--model", required=True) - ap.add_argument("--out", required=True) - a = ap.parse_args() - import torch - from torch.nn.attention import SDPBackend, sdpa_kernel - from tensorfold.vision.images import _decode, DEFAULT_LIMITS - from tensorfold.vision.qwen_cuda import QwenCudaVision, TOKENS_PER_IMAGE - - out = Path(a.out) - out.mkdir(parents=True, exist_ok=True) - vision = QwenCudaVision(a.model, torch.device("cuda:0")) - proc = vision.frontend.processor - factor = vision.config["patch_size"] * vision.config["spatial_merge_size"] - cap = min(int(getattr(proc, "max_pixels", TOKENS_PER_IMAGE * factor**2)), TOKENS_PER_IMAGE * factor**2) - floor = min(int(getattr(proc, "min_pixels", factor**2)), cap) - entries = [] - for name, data in images(): - stem = name.replace(".", "_") - (out / name).write_bytes(data) - decoded = _decode(data, "auto", DEFAULT_LIMITS, DEFAULT_LIMITS.max_pixels) - pil = decoded.to_pil() - rgb = np.asarray(pil, dtype=np.uint8) - (out / f"{stem}.rgb").write_bytes(rgb.tobytes()) - result = proc(images=[pil], max_pixels=cap, min_pixels=floor) - pixels = np.asarray(result["pixel_values"], dtype=np.float32) - t, h, w = (int(v) for v in np.asarray(result["image_grid_thw"])[0]) - (out / f"{stem}.f32").write_bytes(pixels.tobytes()) - with torch.inference_mode(), sdpa_kernel([SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION]): - feats = vision.tower(torch.tensor(pixels, dtype=torch.bfloat16, device="cuda:0"), - grid_thw=torch.tensor([[t, h, w]], device="cuda:0"), return_dict=True).pooler_output - feats = feats.to(torch.bfloat16).contiguous().cpu() - (out / f"{stem}.bf16").write_bytes(feats.view(torch.int16).numpy().tobytes()) - entries.append({"name": name, "file": name, "rgb": f"{stem}.rgb", "size": [rgb.shape[1], rgb.shape[0]], - "grid": [h, w], "pixels": f"{stem}.f32", "features": f"{stem}.bf16", - "tokens": h * w // 4}) - print(f"{name}: {rgb.shape[1]}x{rgb.shape[0]} -> grid {h}x{w}, {h * w // 4} tokens", flush=True) - (out / "manifest.json").write_text(json.dumps({"images": entries, "cap_pixels": cap, "min_pixels": floor}, - indent=1) + "\n") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/zig/src/cli/qwen27_cuda.zig b/zig/src/cli/qwen27_cuda.zig index 2cb255d077..84c8bda959 100644 --- a/zig/src/cli/qwen27_cuda.zig +++ b/zig/src/cli/qwen27_cuda.zig @@ -19,7 +19,7 @@ const usage = \\ 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). + \\ The image tower on recorded 0.6.6 fixtures' patches: each image's rows against 0.6.6's (cosine, max error). \\ ; @@ -547,7 +547,8 @@ fn runMulti(gpa: std.mem.Allocator, a: std.mem.Allocator, io: std.Io, e: *qwen.E return if (bad == 0 and round == want_rounds.len) 0 else 1; } -/// The tower against qwen_vision_fixtures.py's manifest: per image, the features' row cosines and largest error. +/// The tower against a manifest recorded from 0.6.6 outside the tree (qwen_vision_fixtures.py): per image, the +/// features' row cosines and largest error. fn checkVision(gpa: std.mem.Allocator, arena: std.mem.Allocator, io: std.Io, model: []const u8, dir: []const u8) !u8 { const V = qwen.vision; const manifest = try readJson(arena, io, try std.fs.path.join(arena, &.{ dir, "manifest.json" })); diff --git a/zig/src/families/qwen27/cuda/triton.zig b/zig/src/families/qwen27/cuda/triton.zig index fcab03c8ef..bc737a39ec 100644 --- a/zig/src/families/qwen27/cuda/triton.zig +++ b/zig/src/families/qwen27/cuda/triton.zig @@ -119,8 +119,9 @@ pub const Tri = struct { }, &.{ ci("H", a.heads), ci("D", a.dim), ci("G", g), ci("DS", merge_columns), ci("CH", chunk), ci("GR", group_chunks) }); } - /// attention_kv8.py's attention8: attention over e4m3 caches, `offs` holding each stream's four offsets (key - /// and value bytes, their scales' fp32 elements) from `base`; the window's own keys and values stay bf16. + /// attention8 (attention_kv8.py, captured outside the tree like the rest of the set): attention over e4m3 + /// caches, `offs` holding each stream's four offsets (key and value bytes, their scales' fp32 elements) from + /// `base`; the window's own keys and values stay bf16. pub fn attention8(t: Tri, q: u64, kn: u64, vn: u64, base: u64, offs: u64, plan: Plan, part: Partials, out: u64, a: Attn) !void { const g = a.heads / a.kv_heads; const scale: f32 = @floatCast(std.math.pow(f64, @floatFromInt(a.dim), -0.5)); diff --git a/zig/tests/cuda/qwen27/attention_kv8.py b/zig/tests/cuda/qwen27/attention_kv8.py deleted file mode 100644 index 386873d247..0000000000 --- a/zig/tests/cuda/qwen27/attention_kv8.py +++ /dev/null @@ -1,296 +0,0 @@ -#!/usr/bin/env python3 -"""attention.attention over an fp8 (e4m3) key and value cache, for the native engine's --kv-cache fp8. - -The cache holds each (position, key head) row of 256 as e4m3 times one fp32 scale (the row's absolute max over 448). -_shared8 and _tail8 are attention.py's _shared and _tail with those loads: e4m3 widens to bf16 exactly, the key's -scale multiplies its scores and the value's scale its probabilities, so the dots stay bf16 tensor-core dots. The -window's own rows (KN, VN) are quantized in the kernel exactly as their commit will quantize them, so each key's -contribution is the same committed or not. Partials keep attention.py's layout, so its _merge folds them unchanged. - -``--out DIR`` checks both against attention.attention over the dequantized cache and records their launches for -triton_aot_manifest.py (one specialization each for W of 1, of a multiple of 16, and of anything else). -""" - -from __future__ import annotations - -import argparse -import json -import sys -from pathlib import Path - -import torch -import triton -import triton.language as tl - -FP8_MAX = 448.0 - - -@triton.jit -def _tile8(q, k, v, ks, vs, m, l, o, valid, scale: tl.constexpr): - scores = tl.dot(q, tl.trans(k)).to(tl.float32) * ks[None, :] * scale - scores = tl.where(valid[None, :], scores, float("-inf")) - tile_m = tl.max(scores, 1) - active = tile_m != float("-inf") - next_m = tl.where(active, tl.maximum(m, tile_m), m) - alpha = tl.where(active, tl.where(m == float("-inf"), 0.0, tl.exp(m - next_m)), 1.0) - p = tl.where(valid[None, :] & active[:, None], tl.exp(scores - next_m[:, None]), 0.0) - o = o * alpha[:, None] + tl.dot((p * vs[None, :]).to(tl.bfloat16), v) - l = l * alpha + tl.sum(p, 1) - return next_m, l, o - - -@triton.jit -def _fold8(m, l, o, cm, cl, co): - active = cl > 0.0 - next_m = tl.where(active, tl.maximum(m, cm), m) - a = tl.where(active, tl.where(m == float("-inf"), 0.0, tl.exp(m - next_m)), 1.0) - b = tl.where(active, tl.exp(cm - next_m), 0.0) - return next_m, l * a + cl * b, o * a[:, None] + co * b[:, None] - - -@triton.jit -def _q8(x): - """Rows of bf16 as the cache keeps them: e4m3 of x * (448 / amax) widened back to bf16, and s = amax / 448 - (kv_quant's rule: two IEEE divisions a row, one IEEE product an element).""" - - x = x.to(tl.float32) - amax = tl.max(tl.abs(x), 1) - s = tl.where(amax > 0, tl.math.div_rn(amax, 448.0), 1.0) - inv = tl.where(amax > 0, tl.math.div_rn(448.0, amax), 1.0) - return (x * inv[:, None]).to(tl.float8e4nv).to(tl.bfloat16), s - - -@triton.jit -def _shared8(Q, KC, VC, KS, VS, OFF, STREAM, ITEMS, PO, PM, PL, W, H: tl.constexpr, HK: tl.constexpr, - D: tl.constexpr, G: tl.constexpr, CH: tl.constexpr, SCALE: tl.constexpr, GR: tl.constexpr): - """_shared over the fp8 cache; OFF holds four offsets a stream: keys and values (bytes), their scales (fp32).""" - - item = tl.program_id(0) // HK - hk = tl.program_id(0) % HK - s = tl.load(ITEMS + item * 3) - first = tl.load(ITEMS + item * 3 + 1) - code = tl.load(ITEMS + item * 3 + 2) - start = tl.load(STREAM + s * 4) - rows = tl.load(STREAM + s * 4 + 1) - p = tl.load(STREAM + s * 4 + 2) - groups = ((p + rows + CH - 1) // CH - tl.load(STREAM + s * 4 + 3)) // (GR - 1) - whole = code >= 0 - chunk = tl.where(whole, code * GR, groups * GR - 1 - code) - n = tl.where(whole, GR, 1) - slot = tl.where(whole, code, chunk - groups * (GR - 1)) - if ((chunk + n) * CH <= p) & (code < groups): - koff = tl.multiple_of(tl.load(OFF + s * 4), 16) - voff = tl.multiple_of(tl.load(OFF + s * 4 + 1), 16) - ksoff = tl.load(OFF + s * 4 + 2) - vsoff = tl.load(OFF + s * 4 + 3) - rr = first + tl.arange(0, 16) - ok = rr < rows * G - node = start + rr // G - head = hk * G + rr % G - d = tl.arange(0, D) - q = tl.load(Q + (node[:, None] * H + head[:, None]) * D + d[None, :], mask=ok[:, None], - other=0).to(tl.bfloat16) - gm = tl.full((16,), float("-inf"), tl.float32) - gl = tl.zeros((16,), tl.float32) - go = tl.zeros((16, D), tl.float32) - m, l, o = gm, gl, go - for c in range(n): - key = (chunk + c) * CH + tl.arange(0, 64) - m = tl.full((16,), float("-inf"), tl.float32) - l = tl.zeros((16,), tl.float32) - o = tl.zeros((16, D), tl.float32) - for t in range(CH // 64): - ki = key + t * 64 - kk = tl.load(KC + koff + (ki[:, None] * HK + hk) * D + d[None, :]).to(tl.bfloat16) - vv = tl.load(VC + voff + (ki[:, None] * HK + hk) * D + d[None, :]).to(tl.bfloat16) - ks = tl.load(KS + ksoff + ki * HK + hk) - vs = tl.load(VS + vsoff + ki * HK + hk) - m, l, o = _tile8(q, kk, vv, ks, vs, m, l, o, ki < p, SCALE) - gm, gl, go = _fold8(gm, gl, go, m, l, o) - if not whole: - gm, gl, go = m, l, o - base = (slot * W + node) * H + head - tl.store(PO + base[:, None] * D + d[None, :], go, mask=ok[:, None]) - tl.store(PM + base, gm, mask=ok) - tl.store(PL + base, gl, mask=ok) - - -@triton.jit -def _tail8(Q, KN, VN, KC, VC, KS, VS, OFF, STREAM, ROWS, PATHS, DEPTHS, PO, PM, PL, W, H: tl.constexpr, - HK: tl.constexpr, D: tl.constexpr, G: tl.constexpr, CH: tl.constexpr, MAXD: tl.constexpr, - SCALE: tl.constexpr, GR: tl.constexpr): - """_tail over the fp8 cache; the row's own path quantized as its commit will, so a key's bits never depend on - whether it is committed or in the window (nor on drafts, or how streams share a round).""" - - node = tl.program_id(0) - hk = tl.program_id(1) - s = tl.load(ROWS + node) - p = tl.load(STREAM + s * 4 + 2) - nch = (p + tl.load(STREAM + s * 4 + 1) + CH - 1) // CH - groups = (nch - tl.load(STREAM + s * 4 + 3)) // (GR - 1) - chunk = p // CH + tl.program_id(2) - if chunk < nch: - koff = tl.multiple_of(tl.load(OFF + s * 4), 16) - voff = tl.multiple_of(tl.load(OFF + s * 4 + 1), 16) - ksoff = tl.load(OFF + s * 4 + 2) - vsoff = tl.load(OFF + s * 4 + 3) - gg = tl.arange(0, 16) - d = tl.arange(0, D) - q = tl.load(Q + (node * H + hk * G + gg[:, None]) * D + d[None, :], mask=gg[:, None] < G, other=0).to(tl.bfloat16) - depth = tl.load(DEPTHS + node) - m = tl.full((16,), float("-inf"), tl.float32) - l = tl.zeros((16,), tl.float32) - o = tl.zeros((16, D), tl.float32) - key = chunk * CH + tl.arange(0, 64) - for t in range(CH // 64): - logical = key + t * 64 - committed = logical < p - path_slot = logical - p - on_path = (path_slot >= 0) & (path_slot < depth) - path_node = tl.load(PATHS + node * MAXD + path_slot, mask=on_path, other=0) - kc = tl.load(KC + koff + (logical[:, None] * HK + hk) * D + d[None, :], mask=committed[:, None], other=0.0) - vc = tl.load(VC + voff + (logical[:, None] * HK + hk) * D + d[None, :], mask=committed[:, None], other=0.0) - ks = tl.load(KS + ksoff + logical * HK + hk, mask=committed, other=1.0) - vs = tl.load(VS + vsoff + logical * HK + hk, mask=committed, other=1.0) - kn = tl.zeros((64, D), tl.bfloat16) - vn = tl.zeros((64, D), tl.bfloat16) - kns = tl.full((64,), 1.0, tl.float32) - vns = tl.full((64,), 1.0, tl.float32) - if tl.max(on_path.to(tl.int32), 0) > 0: # a tile of committed keys only skips the quantizing - kn, kns = _q8(tl.load(KN + (path_node[:, None] * HK + hk) * D + d[None, :], mask=on_path[:, None], other=0)) - vn, vns = _q8(tl.load(VN + (path_node[:, None] * HK + hk) * D + d[None, :], mask=on_path[:, None], other=0)) - kk = tl.where(committed[:, None], kc.to(tl.bfloat16), kn) - vv = tl.where(committed[:, None], vc.to(tl.bfloat16), vn) - ks = tl.where(committed, ks, kns) - vs = tl.where(committed, vs, vns) - m, l, o = _tile8(q, kk, vv, ks, vs, m, l, o, committed | on_path, SCALE) - base = ((chunk - groups * (GR - 1)) * W + node) * H + hk * G + gg - tl.store(PO + base[:, None] * D + d[None, :], o, mask=gg[:, None] < G) - tl.store(PM + base, m, mask=gg < G) - tl.store(PL + base, l, mask=gg < G) - - -def quantize(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: - """(n, HK, D) bf16 rows as e4m3 and one fp32 scale a row: the native kv_quant kernel's rule.""" - - amax = x.float().abs().amax(-1) - # tensor by tensor: IEEE division, as kv_quant's __fdiv_rn (torch divides by a Python float as a reciprocal) - full = torch.full_like(amax, FP8_MAX) - scale = torch.where(amax > 0, amax / full, torch.ones_like(amax)) - inv = torch.where(amax > 0, full / amax, torch.ones_like(amax)) - q = (x.float() * inv[..., None]).clamp(-FP8_MAX, FP8_MAX).to(torch.float8_e4m3fn) - return q, scale - - -def attention8(q, kn, vn, origin, kc8, vc8, ks, vs, p: "A.Plan", scale: float): - """attention.attention with the fp8 cache of one stream (offsets from ``origin``, as the engine passes them).""" - - import tensorfold.cuda.kernels.attention as A - - w, h, d = q.shape - hk = kn.shape[1] - g = h // hk - o8 = origin.view(torch.float8_e4m3fn) - of = origin.view(torch.float32) - b = origin.data_ptr() - offs = torch.tensor([[kc8.data_ptr() - b, vc8.data_ptr() - b, (ks.data_ptr() - b) // 4, (vs.data_ptr() - b) // 4]], - dtype=torch.int64, device=q.device) - po = torch.empty((p.chunks, w, h, d), dtype=torch.float32, device=q.device) - pm = torch.empty((p.chunks, w, h), dtype=torch.float32, device=q.device) - pl = torch.empty_like(pm) - if p.items.shape[0]: - _shared8[(p.items.shape[0] * hk,)](q, o8, o8, of, of, offs, p.streams, p.items, po, pm, pl, w, H=h, HK=hk, D=d, - G=g, CH=A.CHUNK, SCALE=scale, GR=A.GROUP, num_warps=4, num_stages=1) - tails = 1 + -(-A.MAX_NODES // A.CHUNK) - _tail8[(w, hk, tails)](q, kn, vn, o8, o8, of, of, offs, p.streams, p.rows, p.paths, p.depths, po, pm, pl, w, H=h, - HK=hk, D=d, G=g, CH=A.CHUNK, MAXD=A.MAX_NODES, SCALE=scale, GR=A.GROUP, num_warps=4, - num_stages=1) - out = torch.empty_like(q) - A._merge[(w, hk, d // A.MERGE_COLUMNS)](po, pm, pl, out, p.streams, p.rows, w, H=h, D=d, G=g, DS=A.MERGE_COLUMNS, - CH=A.CHUNK, GR=A.GROUP, num_warps=4) - return out - - -def check(p_len: int, parents: list[int], dev) -> float: - """attention8 against attention.attention over the dequantized cache: the worst row's cosine.""" - - import tensorfold.cuda.kernels.attention as A - - torch.manual_seed(p_len * 131 + len(parents)) - h, hk, d = 24, 4, 256 - w = len(parents) - cap = p_len + 64 - k = torch.randn((cap, hk, d), device=dev).mul(3).to(torch.bfloat16) - v = torch.randn((cap, hk, d), device=dev).to(torch.bfloat16) - k8, ks = quantize(k) - v8, vs = quantize(v) - kd = (k8.float() * ks[..., None]).to(torch.bfloat16) - vd = (v8.float() * vs[..., None]).to(torch.bfloat16) - q = torch.randn((w, h, d), device=dev).to(torch.bfloat16) - kn = torch.randn((w, hk, d), device=dev).mul(3).to(torch.bfloat16) - vn = torch.randn((w, hk, d), device=dev).to(torch.bfloat16) - plan = A.plan([parents], [p_len], h // hk, dev) - scale = d ** -0.5 - kq, kqs = quantize(kn) - vq, vqs = quantize(vn) - knd = (kq.float() * kqs[..., None]).to(torch.bfloat16) - vnd = (vq.float() * vqs[..., None]).to(torch.bfloat16) - ref = A.attention(q, knd, vnd, torch.tensor([A.offsets([(kd, vd)], dev)], dtype=torch.int64, device=dev), plan, - scale=scale) - got = attention8(q, kn, vn, A.base(dev).view(torch.uint8), k8, v8, ks, vs, plan, scale) - cos = torch.nn.functional.cosine_similarity(ref.float().view(w * h, d), got.float().view(w * h, d), dim=1) - if parents == list(range(-1, w - 1)) and w > 1: - # a chain's first row committed instead: the other rows' outputs must keep their bits - k8b = torch.cat([k8[:p_len], kq[:1], k8[p_len + 1:]]) - ksb = torch.cat([ks[:p_len], kqs[:1], ks[p_len + 1:]]) - v8b = torch.cat([v8[:p_len], vq[:1], v8[p_len + 1:]]) - vsb = torch.cat([vs[:p_len], vqs[:1], vs[p_len + 1:]]) - plan_b = A.plan([list(range(-1, w - 2))], [p_len + 1], h // hk, dev) - got_b = attention8(q[1:].contiguous(), kn[1:].contiguous(), vn[1:].contiguous(), A.base(dev).view(torch.uint8), - k8b, v8b, ksb, vsb, plan_b, scale) - same = torch.equal(got[1:], got_b) - print(f" committed vs in-window keys: {'bit-identical' if same else 'DIFFER'}", flush=True) - if not same: - return 0.0 - return float(cos.min()) - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument("--out", required=True) - ap.add_argument("--tools", required=True, help="folder of triton_aot_manifest.py") - a = ap.parse_args() - sys.path.insert(0, a.tools) - import triton_aot_manifest as aot - - out = Path(a.out) - out.mkdir(parents=True, exist_ok=True) - rec = aot.Recorder().install() - rec.detail = True - dev = torch.device("cuda:0") - worst = 1.0 - # W of 1 (decode), 16 (a divisible verify window), 7 and 33 (neither); committed keys under and over a group - cases = [(0, [-1]), (700, [-1]), (5000, [-1]), (9000, list(range(-1, 15))), (3000, [-1, 0, 1, 1, 3, 4, 2]), - (20000, [-1] + list(range(32))), (300, list(range(-1, 15)))] - for p_len, parents in cases: - c = check(p_len, parents, dev) - worst = min(worst, c) - print(f"p={p_len} w={len(parents)}: worst row cosine {c:.6f}", flush=True) - rec.dump(out / "launches.json") - from triton.runtime.jit import JITFunction - import gc - - spec = {} - for fn in gc.get_objects(): - if isinstance(fn, JITFunction): - spec[f"{fn.fn.__module__}.{fn.fn.__qualname__}"] = { - "params": [x.name for x in fn.params], - "do_not_specialize": [x.name for x in fn.params if x.do_not_specialize], - "no_align": [x.name for x in fn.params if x.do_not_specialize_on_alignment]} - (out / "jit.json").write_text(json.dumps(spec, indent=1, sort_keys=True) + "\n") - print(f"worst {worst:.6f}") - return 0 if worst > 0.995 else 1 - - -if __name__ == "__main__": - raise SystemExit(main()) From bcd433c03fe2ab5edc5dc35249773ca8f1196d90 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:58:19 +0000 Subject: [PATCH 12/17] Lean rule: one-line comments and docstrings, and a vendored-source exemption Main's new lean check (94ab8f8a) found 666 problems this branch adds: - 548 in zig/vendor/stb/stb_image.h, the third-party decoder kept as its authors wrote it. lean_check.py now skips zig/vendor/, as it skips generator outputs. - 118 in our own code. Each multi-line comment or docstring is now one line of at most 120 columns. Only comment and docstring text changes. - The vision fixture check moves from cli/qwen27_cuda.zig (635 lines) to cli/qwen27_vision_check.zig. The lean check against main now reports 0 new problems. --- tools/zig/glm_vision_fixtures.py | 16 +--- tools/zig/lean_check.py | 4 +- tools/zig/vision_served.py | 17 +---- tools/zig/vision_urls_served.py | 12 +-- zig/kernels/cuda/prefill_attention.cu | 6 +- zig/kernels/cuda/qwen_ops.cu | 5 +- zig/kernels/cuda/qwen_vision.cu | 18 ++--- zig/kernels/metal/glm_vision.metal | 10 +-- zig/src/cli/qwen27_cuda.zig | 92 +---------------------- zig/src/cli/qwen27_vision_check.zig | 95 ++++++++++++++++++++++++ zig/src/core/engine_api.zig | 5 +- zig/src/core/lanes/stream.zig | 3 +- zig/src/families/glm/engine.zig | 3 +- zig/src/families/glm/forward.zig | 2 +- zig/src/families/glm/image.zig | 18 ++--- zig/src/families/glm/slot_images.zig | 6 +- zig/src/families/glm/vision.zig | 20 ++--- zig/src/families/qwen27/cuda/engine.zig | 5 +- zig/src/families/qwen27/cuda/image.zig | 26 ++----- zig/src/families/qwen27/cuda/kernels.zig | 3 +- zig/src/families/qwen27/cuda/lanes.zig | 3 +- zig/src/families/qwen27/cuda/lone.zig | 3 +- zig/src/families/qwen27/cuda/reuse.zig | 6 +- zig/src/families/qwen27/cuda/round.zig | 7 +- zig/src/families/qwen27/cuda/state.zig | 3 +- zig/src/families/qwen27/cuda/triton.zig | 4 +- zig/src/families/qwen27/cuda/vision.zig | 27 ++----- zig/src/native/cuda.zig | 6 +- zig/src/server/images.zig | 16 ++-- zig/src/server/media_fetch.zig | 28 ++----- zig/src/server/messages.zig | 5 +- zig/src/server/model_text.zig | 2 +- zig/src/server/prompt.zig | 8 +- 33 files changed, 183 insertions(+), 301 deletions(-) create mode 100644 zig/src/cli/qwen27_vision_check.zig diff --git a/tools/zig/glm_vision_fixtures.py b/tools/zig/glm_vision_fixtures.py index ee17c15eb5..72e222fe93 100644 --- a/tools/zig/glm_vision_fixtures.py +++ b/tools/zig/glm_vision_fixtures.py @@ -1,18 +1,4 @@ -"""GLM-5.3-Flash image input against the Python frontend, on a fixed image set (#565's gate). - - python -I tools/zig/glm_vision_fixtures.py --model DIR --out DIR [--tower zig-out/bin/tf-glm-vision] - -Draws the image set (each case a preprocessing path: padding only, an antialiased downscale, an upscale, alpha over -white, a palette with a transparent entry, gray with alpha, EXIF orientation, baseline JPEG), then for each image -writes what TensorFold 0.6.6's --vision gives (vision/images.py's decode: EXIF orientation, alpha over white; then -mlx-vlm's Glm5NextImageProcessor and tower, the code 0.6.6 serves): - patches.f32 (grid_h*grid_w, 1176) normalized patches, temporal frames duplicated - embed.f32 / block0.f32 / blocks.f32 / features.f32 the tower's stages, features the rows that replace <|image|> -and meta.json. With --tower it then runs tf-glm-vision on each image: the native patches compared value by value, -the native tower's rows by cosine (bf16 against bf16). - -Needs TensorFold 0.6.6 with its vision extra (mlx-vlm 0.7.x) and Pillow. Loads only model.visual.* (about 1 GB). -""" +"""GLM-5.3-Flash image input against the Python frontend, on a fixed image set (#565's gate).""" from __future__ import annotations diff --git a/tools/zig/lean_check.py b/tools/zig/lean_check.py index a97aa37701..a5928f867b 100644 --- a/tools/zig/lean_check.py +++ b/tools/zig/lean_check.py @@ -19,6 +19,8 @@ "zig/src/families/flashnext/roles_gen.zig", "zig/kernels/metal/flashnext/sources_gen.zig", ) +# Third-party sources kept as their authors wrote them (stb_image.h) are skipped too. +VENDORED = "zig/vendor/" def generator_output(path: Path) -> bool: @@ -31,7 +33,7 @@ def generator_output(path: Path) -> bool: def problems(path: Path) -> list[str]: """Every rule break in one file, as 'path:line: reason'.""" - if generator_output(path): + if generator_output(path) or path.relative_to(ROOT).as_posix().startswith(VENDORED): return [] lines = path.read_text(errors="replace").splitlines() rel, found = path.relative_to(ROOT), [] diff --git a/tools/zig/vision_served.py b/tools/zig/vision_served.py index c58a4b5bf6..8d9a645e7f 100644 --- a/tools/zig/vision_served.py +++ b/tools/zig/vision_served.py @@ -1,14 +1,4 @@ -"""Image input served end to end on a running ``tensorfold-native --vision`` (#565's served checks). - - python tools/zig/vision_served.py --url http://127.0.0.1:8000 --images DIR - -DIR holds PNG and JPEG test images. Checks: an image request answers, and text or a tool result that quotes the -model's image marker beside a real image is ordinary text (images come from the request's image parts, #511); drafted -equals ``"draft": false`` and concurrent equals alone with images; an image conversation's next turn resumes past -its image, and another image under the same placeholders resumes none of the first one's rows; and the refusals (WebP by name, other formats, an image outside a -user or tool message, too many images, remote URLs without --vision-urls, bad data URLs, a bad detail); tools/zig/vision_urls_served.py -checks a server started with --vision-urls. -""" +"""Image input served end to end on a running ``tensorfold-native --vision`` (#565's served checks).""" from __future__ import annotations @@ -117,9 +107,7 @@ def check(label: str, ok: bool, detail: str = "") -> None: same = sum(x == y for x, y in zip(alone, together)) check("concurrent image requests equal their runs alone", same == len(runs), f"{same} of {len(runs)}") - # the prompt cache keeps a turn's state at its planned cuts (GLM: the shared system cut, and a reply of 256+ tokens), - # so a conversation's third turn resumes past an image its second turn kept. Image B under the same text and - # placeholder ids resumes at most the text before its image, and answers as a server with nothing kept + # the prompt cache keeps state at planned cuts (system, a 256+ token reply): turn three resumes past turn 2's image system = {"role": "system", "content": " ".join(f"Rule {i}: describe what you see plainly and briefly." for i in range(120))} q, q2, q3 = "What is shown?", "Say that again in three words.", "And once more." head = ask([system, user(text(q))], tokens=1)[1]["usage"]["prompt_tokens"] # the text alone: past where an image starts @@ -137,6 +125,7 @@ def turns(url: str) -> tuple[list, list]: code, ra = ask(three_a, tokens=24) cached_a = ra.get("usage", {}).get("prompt_tokens_details", {}).get("cached_tokens", 0) if code == 200 else -1 check("an image conversation's later turn resumes past its image", code == 200 and cached_a > head, f"cached {cached_a} of {ra.get('usage', {}).get('prompt_tokens')}; the text alone is {head}") + # image B under the same text and placeholder ids resumes at most the text before its image code, rb = ask(three_b, tokens=24) cached_b = rb.get("usage", {}).get("prompt_tokens_details", {}).get("cached_tokens", 0) if code == 200 else -1 check("another image under the same placeholders resumes only the text before it", code == 200 and cached_b < head, diff --git a/tools/zig/vision_urls_served.py b/tools/zig/vision_urls_served.py index f383eabbf6..3ab3c5773a 100644 --- a/tools/zig/vision_urls_served.py +++ b/tools/zig/vision_urls_served.py @@ -1,14 +1,4 @@ -"""Image URLs served end to end on a running ``tensorfold-native --vision --vision-urls`` (#565's URL checks). - - python tools/zig/vision_urls_served.py --url http://127.0.0.1:8000 - -Checks, against public hosts: an HTTPS image URL answers exactly as the same bytes sent as a data URL (the prompt's -tokens and the greedy reply), and so does a URL that redirects to it; a URL and a data URL in one request; and the -refusals images_http.py gave, before any token (HTTP status, content type, a host that resolves to a private -address, a name that is never public, an address literal that isn't public, TLS that doesn't verify, a scheme, port, -credentials or fragment the URL rules refuse, an unresolvable host). The fetch's own rules (redirect limits, -lengths, chunking, encodings, deadlines) are the unit tests in zig/src/server/media_fetch.zig. -""" +"""Image URLs served end to end on a running ``tensorfold-native --vision --vision-urls`` (#565's URL checks).""" from __future__ import annotations diff --git a/zig/kernels/cuda/prefill_attention.cu b/zig/kernels/cuda/prefill_attention.cu index fe241822e3..c304af66e8 100644 --- a/zig/kernels/cuda/prefill_attention.cu +++ b/zig/kernels/cuda/prefill_attention.cu @@ -57,8 +57,7 @@ __device__ __forceinline__ float rowsum(const float (&c)[8]) { __fadd_rn(__fadd_rn(w[1], w[5]), __fadd_rn(w[3], w[7]))); } -// 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. +// F8: e4m3 cache rows (kc, vc) with an fp32 scale a row (ks, vs); staging widens them to bf16, so the rest is bf16's. template __device__ __forceinline__ void pattn_body(const __nv_bfloat16* __restrict__ q, const void* __restrict__ kc, const void* __restrict__ vc, const float* __restrict__ ks, @@ -74,8 +73,7 @@ __device__ __forceinline__ void pattn_body(const __nv_bfloat16* __restrict__ q, 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 + // F8: fetch loads an item's e4m3 words and scales a step ahead, put widens them into its slot, hiding the loads constexpr int PER = (HALF * C + THREADS - 1) / THREADS; uint2 pre[F8 ? PER : 1]; float pre_s[F8 ? PER : 1]; diff --git a/zig/kernels/cuda/qwen_ops.cu b/zig/kernels/cuda/qwen_ops.cu index 34b025326d..2c57e4355d 100644 --- a/zig/kernels/cuda/qwen_ops.cu +++ b/zig/kernels/cuda/qwen_ops.cu @@ -23,10 +23,9 @@ struct TfQuant { 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. +// --kv-cache fp8: each 256-wide row as e4m3 of x * (448 / amax), scale amax / 448 (1 for zeros), as attention_kv8.py extern "C" __global__ void __launch_bounds__(256) tf_kv_quant(const TfQuant* __restrict__ items) { + // a warp a row, eight rows a block, items on y const TfQuant it = items[blockIdx.y]; const unsigned long long row = static_cast(blockIdx.x) * 8 + threadIdx.x / 32; if (row >= it.rows) return; diff --git a/zig/kernels/cuda/qwen_vision.cu b/zig/kernels/cuda/qwen_vision.cu index fe3999a5b3..4163d5306c 100644 --- a/zig/kernels/cuda/qwen_vision.cu +++ b/zig/kernels/cuda/qwen_vision.cu @@ -1,6 +1,4 @@ -// The Qwen3.5 vision tower's kernels (transformers' Qwen3_5VisionModel, as 0.6.6's --vision runs it in bf16). -// The tower's Linears run on cuBLASLt with fp32 output; each epilogue here adds the bias and rounds to bf16 once, -// where torch's bf16 Linear rounds, before the op that follows. +// Qwen3.5 vision tower kernels (0.6.6's --vision in bf16); epilogues add the bias to cuBLASLt's fp32, round once. #include #include @@ -67,9 +65,7 @@ extern "C" __global__ void __launch_bounds__(256) tf_qv_layernorm(const __nv_bfl y[row * D + i] = __float2bfloat16_rn((bf(xr[i]) - mean) * r * bf(w[i]) + bf(b[i])); } -// qkv = bf16(acc + b) split into q, k, v [heads][rows][hd]; q and k rotated by the axial 2-D rotary in fp32 -// (apply_rotary_pos_emb_vision): angle j of a head is h * inv[j % half'] for the first quarter's frequencies and -// w * inv[...] for the second, repeated over both halves; rotate_half pairs j with j +- hd/2. +// qkv = bf16(acc + b) split into q, k, v [heads][rows][hd]; q and k get the axial 2-D rotary in fp32 (h, then w). extern "C" __global__ void __launch_bounds__(128) tf_qv_qkv_rope(const float* __restrict__ acc, const __nv_bfloat16* __restrict__ bias, const int* __restrict__ hw, @@ -87,6 +83,7 @@ extern "C" __global__ void __launch_bounds__(128) tf_qv_qkv_rope(const float* __ const long long o = (static_cast(head) * rows + row) * hd; for (int j = threadIdx.x; j < hd; j += blockDim.x) { const int c = head * hd + j; + // rotate_half pairs j with j +- hd/2; angle h * inv[jj] for the first quarter's frequencies, w * inv after const int pj = j < half ? j + half : j - half; const int pc = head * hd + pj; const int jj = j % half; @@ -101,8 +98,7 @@ extern "C" __global__ void __launch_bounds__(128) tf_qv_qkv_rope(const float* __ } } -// Bidirectional attention within one image: rows [s0, s0 + n) of q, k, v [heads][rows][HD] attend to each other; -// out [rows][heads * HD]. A thread a query row with an online softmax in fp32; keys and values in 64-row tiles. +// Attention within one image's rows [s0, s0 + n); a thread a query row, online softmax in fp32, 64-row key tiles. template __device__ void qv_attention(const __nv_bfloat16* __restrict__ q, const __nv_bfloat16* __restrict__ k, const __nv_bfloat16* __restrict__ v, __nv_bfloat16* __restrict__ out, int rows, @@ -207,10 +203,7 @@ extern "C" __global__ void __launch_bounds__(256) tf_qv_splice(__nv_bfloat16* __ for (int i = threadIdx.x; i < D; i += blockDim.x) x[row * D + i] = features[static_cast(s) * D + i]; } -// glue._attn_prep with MROPE (0.6.6's Triton kernel, three position rows): each head's q (from the [q | gate] rows) -// or k RMS-normed to bf16, then rotate-half over the first 2 * HALF dims, frequency i taking the t, h or w position -// by Qwen's interleaved sections (axis 1 where i % 3 == 1 and i < 3 * hsec, axis 2 where i % 3 == 2 and -// i < 3 * wsec, else axis 0). A block of D threads a (row, head); pos is [3][rows]. +// glue._attn_prep with MROPE: q or k RMS-normed to bf16, then rotate-half by t, h or w position; a block a (row, head). extern "C" __global__ void __launch_bounds__(256) tf_qv_attn_prep_mrope( const __nv_bfloat16* __restrict__ qg, const __nv_bfloat16* __restrict__ kv, const __nv_bfloat16* __restrict__ qn, const __nv_bfloat16* __restrict__ kn, const int* __restrict__ pos, const float* __restrict__ inv, @@ -239,6 +232,7 @@ extern "C" __global__ void __launch_bounds__(256) tf_qv_attn_prep_mrope( float out = xn; if (d < 2 * HALF) { const int i = d < HALF ? d : d - HALF; + // Qwen's interleaved sections: axis 1 where i % 3 == 1 and i < 3 * hsec, 2 where i % 3 == 2 and i < 3 * wsec const int axis = (i % 3 == 1 && i < 3 * hsec) ? 1 : ((i % 3 == 2 && i < 3 * wsec) ? 2 : 0); const float ang = static_cast(pos[axis * rows + row]) * inv[i]; const float cs = cosf(ang), sn = sinf(ang); diff --git a/zig/kernels/metal/glm_vision.metal b/zig/kernels/metal/glm_vision.metal index c0fcc513e4..cf79f43b03 100644 --- a/zig/kernels/metal/glm_vision.metal +++ b/zig/kernels/metal/glm_vision.metal @@ -1,6 +1,4 @@ -// GLM-5.3-Flash's image tower (GLM5-Next vision: 24 pre-norm blocks of 1024, 16 heads of 64, 2-D rotary, a 2x2 merge -// and a SwiGLU merger to the language model's 4096). Compiled after prefill/gemm_nax.metal, whose tfp::gemm_nax runs -// every projection; the rest is MLX's per-op arithmetic as mlx-vlm's glm5_next/vision.py runs it in bf16. +// GLM-5.3-Flash's image tower, MLX's per-op bf16 arithmetic as mlx-vlm runs it; needs prefill/gemm_nax.metal first. // ---- the projections and attention products: tfp::gemm_nax (bm64 bn128 bk256 wm2 wn4) by operand layout ---- #define GLMV_GEMM(NAME, T, TA, TB, AM, AN) \ @@ -110,9 +108,7 @@ struct GlmvQkv { float eps; // the q and k norms' }; -// One simdgroup per (row, head, q|k|v) of qkv [L, 3, 16, 64]: q and k RMS-normed, rotated by the row's 2-D angles -// (cos and sin [L, 64]: the height's 16 frequencies, then the width's, twice), and written head-major in fp32 -// ([16, L, 64], each value a bf16 as MLX hands its attention); v as stored. +// A simdgroup a (row, head, q|k|v) of qkv [L, 3, 16, 64]: q and k RMS-normed and 2-D rotated; out head-major fp32. [[kernel]] void glmv_qkv(const device bfloat* qkv [[buffer(0)]], const device bfloat* qn [[buffer(1)]], const device bfloat* kn [[buffer(2)]], const device float* cs [[buffer(3)]], const device float* sn [[buffer(4)]], device float* Q [[buffer(5)]], @@ -132,6 +128,7 @@ struct GlmvQkv { const float inv = metal::precise::rsqrt(simd_sum(a * a + b * b) / 64.0f + p.eps); const float na = glmv_bf(float(w[lane]) * glmv_bf(a * inv)); const float nb = glmv_bf(float(w[lane + 32]) * glmv_bf(b * inv)); + // cos and sin [L, 64]: the height's 16 frequencies, then the width's, twice const device float* c = cs + ulong(r) * 64; const device float* s = sn + ulong(r) * 64; device float* dst = which == 0 ? Q : K; @@ -177,7 +174,6 @@ struct GlmvQkv { } // The vision MLP's and merger's gate: silu(min(g, limit)) * clip(u, -limit, limit), each op rounded as MLX does. -// gu: g then u, `width` each, a row at a time (stride 2 * width); act [rows, width]. [[kernel]] void glmv_swiglu(const device bfloat* g [[buffer(0)]], const device bfloat* u [[buffer(1)]], device bfloat* act [[buffer(2)]], constant float& limit [[buffer(3)]], uint i [[thread_position_in_grid]]) { diff --git a/zig/src/cli/qwen27_cuda.zig b/zig/src/cli/qwen27_cuda.zig index 84c8bda959..a45ee50316 100644 --- a/zig/src/cli/qwen27_cuda.zig +++ b/zig/src/cli/qwen27_cuda.zig @@ -47,7 +47,7 @@ pub fn main(init: std.process.Init) !u8 { 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]); + return @import("qwen27_vision_check.zig").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 or kvcompare)) { std.debug.print("{s}", .{usage}); return 2; @@ -134,8 +134,7 @@ fn argmaxOf(x: []const f64) u32 { 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. +/// kvcompare: bf16 and fp8 streams fed bf16's greedy tokens; per step top-1 agreement, KL and bf16's pick's logprob. 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); @@ -546,90 +545,3 @@ fn runMulti(gpa: std.mem.Allocator, a: std.mem.Allocator, io: std.Io, e: *qwen.E std.debug.print("{d} rounds (python {d}), {d} windows differ from Python's, {d} replies differ; {d:.1} tok/s\n", .{ round, want_rounds.len, differ, bad, @as(f64, @floatFromInt(produced)) / secs }); return if (bad == 0 and round == want_rounds.len) 0 else 1; } - -/// The tower against a manifest recorded from 0.6.6 outside the tree (qwen_vision_fixtures.py): per image, the -/// features' row cosines and largest error. -fn checkVision(gpa: std.mem.Allocator, arena: std.mem.Allocator, io: std.Io, model: []const u8, dir: []const u8) !u8 { - const V = qwen.vision; - const manifest = try readJson(arena, io, try std.fs.path.join(arena, &.{ dir, "manifest.json" })); - var driver = try cuda.Driver.open(); - defer driver.close(); - var ctx = try cuda.Context.init(&driver, 0); - defer ctx.deinit(); - var stream = try cuda.Stream.init(&driver, true); - defer stream.deinit(); - const gpu: V.Gpu = .{ .d = &driver, .s = stream, .discrete = try ctx.attribute(.integrated) == 0 }; - const clock = std.Io.Clock.awake; - var t0 = clock.now(io).toNanoseconds(); - const tower = try V.Tower.load(gpa, io, gpu, model); - defer tower.deinit(); - std.debug.print("tower loaded in {d:.1}s, {d:.2} GiB\n", .{ @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e9, @as(f64, @floatFromInt(tower.weight_bytes)) / (1 << 30) }); - var worst: f64 = 1; - for (manifest.object.get("images").?.array.items) |img| { - const name = img.object.get("name").?.string; - const grid = img.object.get("grid").?.array.items; - const g: V.Grid = .{ .h = @intCast(grid[0].integer), .w = @intCast(grid[1].integer) }; - const px_bytes = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("pixels").?.string }), arena, .limited(1 << 30)); - const want_bytes = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("features").?.string }), arena, .limited(1 << 30)); - const px = try arena.alloc(f32, px_bytes.len / 4); - @memcpy(std.mem.sliceAsBytes(px), px_bytes[0 .. px.len * 4]); - { // our decode and patches from the image's file, against 0.6.6's - const file = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("file").?.string }), arena, .limited(1 << 30)); - const want_rgb = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("rgb").?.string }), arena, .limited(1 << 30)); - const rgb = try qwen.image.decode(gpa, file); - defer rgb.deinit(gpa); - var px_diff: usize = 0; - if (rgb.px.len == want_rgb.len) { - for (rgb.px, want_rgb) |a, b| px_diff += @intFromBool(a != b); - } else px_diff = std.math.maxInt(usize); - const prep = try qwen.image.prepare(gpa, file, 4096); - defer gpa.free(prep.pixels); - var patch_diff: usize = 0; - if (prep.gh == g.h and prep.gw == g.w and prep.pixels.len == px.len) { - for (prep.pixels, px) |a, b| patch_diff += @intFromBool(@as(u32, @bitCast(a)) != @as(u32, @bitCast(b))); - } else patch_diff = std.math.maxInt(usize); - std.debug.print("{s}: decode {d}x{d}, {d} of {d} bytes differ from PIL's; patches grid {d}x{d}, {d} of {d} values differ\n", .{ name, rgb.w, rgb.h, px_diff, want_rgb.len, prep.gh, prep.gw, patch_diff, px.len }); - } - const rows = @as(usize, g.h) * g.w / 4; - var out = try cuda.DeviceBuffer.alloc(&driver, rows * V.out_hidden * 2); - defer out.free(); - t0 = clock.now(io).toNanoseconds(); - try tower.encode(gpu, px, &.{g}, out.ptr); - const ms = @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e6; - const got = try arena.alloc(u16, rows * V.out_hidden); - try driver.check(driver.api.cuMemcpyDtoH_v2(@ptrCast(got.ptr), out.ptr, got.len * 2), "cuMemcpyDtoH"); - const want: []align(1) const u16 = std.mem.bytesAsSlice(u16, want_bytes); - if (want.len != got.len) { - std.debug.print("{s}: {d} features, 0.6.6 has {d}\n", .{ name, got.len, want.len }); - return 1; - } - var min_cos: f64 = 1; - var sum_cos: f64 = 0; - var max_err: f64 = 0; - var equal: usize = 0; - for (0..rows) |r| { - var dot: f64 = 0; - var na: f64 = 0; - var nb: f64 = 0; - for (0..V.out_hidden) |c| { - const a = bf(got[r * V.out_hidden + c]); - const b = bf(want[r * V.out_hidden + c]); - if (got[r * V.out_hidden + c] == want[r * V.out_hidden + c]) equal += 1; - dot += a * b; - na += a * a; - nb += b * b; - max_err = @max(max_err, @abs(a - b)); - } - const cs = dot / @sqrt(na * nb); - min_cos = @min(min_cos, cs); - sum_cos += cs; - } - worst = @min(worst, min_cos); - std.debug.print("{s}: grid {d}x{d}, {d} rows in {d:.1} ms; row cosine min {d:.5} mean {d:.5}; max error {d:.4}; {d:.1}% values equal\n", .{ name, g.h, g.w, rows, ms, min_cos, sum_cos / @as(f64, @floatFromInt(rows)), max_err, 100 * @as(f64, @floatFromInt(equal)) / @as(f64, @floatFromInt(got.len)) }); - } - return if (worst > 0.98) 0 else 1; -} - -fn bf(v: u16) f64 { - return @as(f32, @bitCast(@as(u32, v) << 16)); -} diff --git a/zig/src/cli/qwen27_vision_check.zig b/zig/src/cli/qwen27_vision_check.zig new file mode 100644 index 0000000000..cbedfc6859 --- /dev/null +++ b/zig/src/cli/qwen27_vision_check.zig @@ -0,0 +1,95 @@ +//! `tf-qwen27-cuda vision`: the vision tower, image decode and patches against a manifest recorded from 0.6.6. +const std = @import("std"); +const cuda = @import("cuda"); +const qwen = @import("qwen27"); + +/// The tower against a 0.6.6 manifest recorded outside the tree: per image, the row cosines and largest error. +pub fn checkVision(gpa: std.mem.Allocator, arena: std.mem.Allocator, io: std.Io, model: []const u8, dir: []const u8) !u8 { + const V = qwen.vision; + const manifest = try readJson(arena, io, try std.fs.path.join(arena, &.{ dir, "manifest.json" })); + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var stream = try cuda.Stream.init(&driver, true); + defer stream.deinit(); + const gpu: V.Gpu = .{ .d = &driver, .s = stream, .discrete = try ctx.attribute(.integrated) == 0 }; + const clock = std.Io.Clock.awake; + var t0 = clock.now(io).toNanoseconds(); + const tower = try V.Tower.load(gpa, io, gpu, model); + defer tower.deinit(); + std.debug.print("tower loaded in {d:.1}s, {d:.2} GiB\n", .{ @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e9, @as(f64, @floatFromInt(tower.weight_bytes)) / (1 << 30) }); + var worst: f64 = 1; + for (manifest.object.get("images").?.array.items) |img| { + const name = img.object.get("name").?.string; + const grid = img.object.get("grid").?.array.items; + const g: V.Grid = .{ .h = @intCast(grid[0].integer), .w = @intCast(grid[1].integer) }; + const px_bytes = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("pixels").?.string }), arena, .limited(1 << 30)); + const want_bytes = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("features").?.string }), arena, .limited(1 << 30)); + const px = try arena.alloc(f32, px_bytes.len / 4); + @memcpy(std.mem.sliceAsBytes(px), px_bytes[0 .. px.len * 4]); + { // our decode and patches from the image's file, against 0.6.6's + const file = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("file").?.string }), arena, .limited(1 << 30)); + const want_rgb = try std.Io.Dir.cwd().readFileAlloc(io, try std.fs.path.join(arena, &.{ dir, img.object.get("rgb").?.string }), arena, .limited(1 << 30)); + const rgb = try qwen.image.decode(gpa, file); + defer rgb.deinit(gpa); + var px_diff: usize = 0; + if (rgb.px.len == want_rgb.len) { + for (rgb.px, want_rgb) |a, b| px_diff += @intFromBool(a != b); + } else px_diff = std.math.maxInt(usize); + const prep = try qwen.image.prepare(gpa, file, 4096); + defer gpa.free(prep.pixels); + var patch_diff: usize = 0; + if (prep.gh == g.h and prep.gw == g.w and prep.pixels.len == px.len) { + for (prep.pixels, px) |a, b| patch_diff += @intFromBool(@as(u32, @bitCast(a)) != @as(u32, @bitCast(b))); + } else patch_diff = std.math.maxInt(usize); + std.debug.print("{s}: decode {d}x{d}, {d} of {d} bytes differ from PIL's; patches grid {d}x{d}, {d} of {d} values differ\n", .{ name, rgb.w, rgb.h, px_diff, want_rgb.len, prep.gh, prep.gw, patch_diff, px.len }); + } + const rows = @as(usize, g.h) * g.w / 4; + var out = try cuda.DeviceBuffer.alloc(&driver, rows * V.out_hidden * 2); + defer out.free(); + t0 = clock.now(io).toNanoseconds(); + try tower.encode(gpu, px, &.{g}, out.ptr); + const ms = @as(f64, @floatFromInt(clock.now(io).toNanoseconds() - t0)) / 1e6; + const got = try arena.alloc(u16, rows * V.out_hidden); + try driver.check(driver.api.cuMemcpyDtoH_v2(@ptrCast(got.ptr), out.ptr, got.len * 2), "cuMemcpyDtoH"); + const want: []align(1) const u16 = std.mem.bytesAsSlice(u16, want_bytes); + if (want.len != got.len) { + std.debug.print("{s}: {d} features, 0.6.6 has {d}\n", .{ name, got.len, want.len }); + return 1; + } + var min_cos: f64 = 1; + var sum_cos: f64 = 0; + var max_err: f64 = 0; + var equal: usize = 0; + for (0..rows) |r| { + var dot: f64 = 0; + var na: f64 = 0; + var nb: f64 = 0; + for (0..V.out_hidden) |c| { + const a = bf(got[r * V.out_hidden + c]); + const b = bf(want[r * V.out_hidden + c]); + if (got[r * V.out_hidden + c] == want[r * V.out_hidden + c]) equal += 1; + dot += a * b; + na += a * a; + nb += b * b; + max_err = @max(max_err, @abs(a - b)); + } + const cs = dot / @sqrt(na * nb); + min_cos = @min(min_cos, cs); + sum_cos += cs; + } + worst = @min(worst, min_cos); + std.debug.print("{s}: grid {d}x{d}, {d} rows in {d:.1} ms; row cosine min {d:.5} mean {d:.5}; max error {d:.4}; {d:.1}% values equal\n", .{ name, g.h, g.w, rows, ms, min_cos, sum_cos / @as(f64, @floatFromInt(rows)), max_err, 100 * @as(f64, @floatFromInt(equal)) / @as(f64, @floatFromInt(got.len)) }); + } + return if (worst > 0.98) 0 else 1; +} + +fn bf(v: u16) f64 { + return @as(f32, @bitCast(@as(u32, v) << 16)); +} + +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, .{})); +} diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index c9a53716ce..2b0915bca4 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -91,7 +91,7 @@ pub const Request = struct { logprobs: ?u8 = null, /// Rows for each prompt token after the first, with ranks and this many best tokens, when ``Info.prompt_logprobs``. prompt_logprobs: ?u8 = null, - /// Images whose rows replace placeholder tokens of ``prompt``, in order; only an engine whose ``Info.vision`` is set. + /// Images whose rows replace placeholder tokens of ``prompt``, in order; only when ``Info.vision`` is set. images: []const Image = &.{}, /// The prompt as the prompt cache matches it (each image's placeholders by its content); empty: ``prompt``. cache_key: []const u32 = &.{}, @@ -110,8 +110,7 @@ pub const Request = struct { /// An image prepared for the engine's tower (``Vision.prepare``): patches, patch grid, tokens and a content hash. pub const PreparedImage = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 }; -/// Image input an engine serves (``Info.vision``): how the server turns an image's bytes into tower input and what -/// a request may hold. +/// Image input an engine serves (``Info.vision``): image bytes to tower input, and what a request may hold. pub const Vision = struct { ctx: *anyopaque, /// The image's bytes (any format the platform decodes) at most ``max_tokens`` tokens; allocated in ``a``. diff --git a/zig/src/core/lanes/stream.zig b/zig/src/core/lanes/stream.zig index e9ad2b7215..5c7edbd003 100644 --- a/zig/src/core/lanes/stream.zig +++ b/zig/src/core/lanes/stream.zig @@ -97,8 +97,7 @@ pub const Held = struct { parents: ?[]i32 = null, }; -/// One image of a prompt: the tower's input (patches [gh * gw, width], the family's layout) and the `tokens` -/// placeholder rows from `at` its output replaces. +/// One image of a prompt: tower input (patches [gh * gw, width]) for the `tokens` placeholder rows from `at`. pub const Image = struct { pixels: []const f32, gh: u32, gw: u32, at: u32, tokens: u32 }; pub const Spec = struct { diff --git a/zig/src/families/glm/engine.zig b/zig/src/families/glm/engine.zig index 77a8d56f4b..9b33850a46 100644 --- a/zig/src/families/glm/engine.zig +++ b/zig/src/families/glm/engine.zig @@ -102,8 +102,7 @@ pub const Engine = struct { return loadWith(gpa, dir, cap, if (std.c.getenv("GLM_EP")) |v| std.mem.span(v) else null, false, null); } - /// `load` with expert parallel over the link in `ep_path` (this Mac's settings), or on one Mac when null. - /// `vision`: the image tower too, with scratch and rows for that many image tokens a prompt. + /// `load` with expert parallel over `ep_path`'s link (one Mac when null) and `vision`'s image tower and rows. pub fn loadWith(gpa: std.mem.Allocator, dir: []const u8, cap: u32, ep_path: ?[]const u8, learn: bool, vision: ?vision_mod.Limits) !*Engine { const e = try gpa.create(Engine); // undefined memory: every field is set below errdefer gpa.destroy(e); diff --git a/zig/src/families/glm/forward.zig b/zig/src/families/glm/forward.zig index 76ad8e07f4..5d1801caee 100644 --- a/zig/src/families/glm/forward.zig +++ b/zig/src/families/glm/forward.zig @@ -38,7 +38,7 @@ pub const Ctx = struct { pub const Inject = struct { rows: Ref, spans: []const Span }; pub const Span = struct { at: u32, n: u32, row: u32 }; -/// The image rows among `rows` embedding rows (prompt positions pos..) written over `out`; nothing without an injection. +/// The image rows among `rows` embedding rows (positions pos..) written over `out`; nothing without an injection. pub fn inject(x: *const Ctx, e: mtl.ComputeEncoder, out: Ref, rows: u32, pos: u32) void { const inj = x.inject orelse return; const D: usize = x.c.hidden; diff --git a/zig/src/families/glm/image.zig b/zig/src/families/glm/image.zig index 4da98c4f4e..0ff08383ca 100644 --- a/zig/src/families/glm/image.zig +++ b/zig/src/families/glm/image.zig @@ -1,8 +1,4 @@ -//! An image's bytes to GLM5-Next vision patches as TensorFold 0.6.6's --vision makes them: decoded as its -//! vision/images.py does with PIL (ImageIO here: the stored values, no colour management; EXIF orientation applied; -//! alpha composited over white with PIL's integer blend), then mlx-vlm's Glm5NextImageProcessor: sized under the -//! token budget, resized with PIL's 8-bit bicubic resampler, padded with black, normalized, and cut into 2x2 windows -//! of 14x14 patches, each patch's frame given twice (temporal_patch_size 2). +//! An image's bytes to GLM5-Next vision patches as TensorFold 0.6.6's --vision makes them (PIL, then mlx-vlm). const std = @import("std"); const vision = @import("vision.zig"); @@ -70,8 +66,7 @@ const order_32_little: u32 = 0x2000; const order_16_little: u32 = 0x1000; const float_components: u32 = 0x100; -/// A PNG, JPEG, GIF, WebP, HEIC or any other single-frame image ImageIO reads, as 8-bit RGB: upright by its EXIF -/// orientation (PIL's exif_transpose) and over white where it has alpha (images.py's paste onto a white canvas). +/// Any single-frame image ImageIO reads as 8-bit RGB, upright by its EXIF orientation and over white where alpha. pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) Error!Rgb { if (bytes.len == 0) return error.BadImage; if (bytes.len > max_bytes) return error.ImageTooLarge; @@ -108,8 +103,7 @@ fn orientation(src: CF) u32 { return if (v < 1) 1 else @intCast(v); } -/// PIL's exif_transpose: orientation 2-8 as FLIP_LEFT_RIGHT, ROTATE_180, FLIP_TOP_BOTTOM, TRANSPOSE, ROTATE_270, -/// TRANSVERSE, ROTATE_90; each output pixel read from its source pixel. +/// PIL's exif_transpose: EXIF orientation 2-8 applied, each output pixel read from its source pixel. pub fn orient(gpa: std.mem.Allocator, src: Rgb, o: u32) Error!Rgb { const w: usize = src.w; const h: usize = src.h; @@ -216,8 +210,7 @@ fn alignUp(v: u64, f: u64) u64 { return (v + f - 1) / f * f; } -/// smart_resize and _resize_geometry (num_frames = temporal_patch_size, as _process_one calls it): the padded canvas -/// under `max_tokens` (at least `min_tokens`), and the content size the image is resized to inside it. +/// smart_resize and _resize_geometry: the padded canvas under `max_tokens` (at least `min_tokens`), the content size. pub fn geometry(h: u32, w: u32, min_tokens: u32, max_tokens: u32) Error!Geometry { const factor: u64 = vision.patch * vision.merge; const frames: u64 = vision.temporal; @@ -365,8 +358,7 @@ pub fn resize(gpa: std.mem.Allocator, src: Rgb, w: u32, h: u32) Error!Rgb { return cur; } -/// The content (already resized) padded with black to the canvas, scaled by 1/255, normalized by channel, cut into -/// 2x2 windows of 14x14 patches in row-major window order, each patch [channel, frame (twice), row, column]. +/// The resized content padded with black, scaled, normalized and cut into 2x2 windows of 14x14 patches, row-major. pub fn patchify(gpa: std.mem.Allocator, content: Rgb, g: Geometry, mean: [3]f32, sd: [3]f32) Error![]f32 { const P = vision.patch; const M = vision.merge; diff --git a/zig/src/families/glm/slot_images.zig b/zig/src/families/glm/slot_images.zig index f3a0697e48..8b41b53d05 100644 --- a/zig/src/families/glm/slot_images.zig +++ b/zig/src/families/glm/slot_images.zig @@ -1,13 +1,11 @@ -//! A stream's images through the tower into the engine's image rows, which its prompt chunks inject over their -//! placeholders (forward.zig's `inject`); the tower remembers whose rows it holds until the pass ends. +//! A stream's images through the tower into the engine's image rows, injected over placeholders by its prompt chunks. const std = @import("std"); const mtl = @import("metal"); const vision_mod = @import("vision.zig"); const Slots = @import("slots.zig").Slots; const Image = @import("lanes").stream.Image; -/// Slot `i`'s images through the tower into the engine's image rows, injected over their placeholders by the chunks -/// that follow until `end`. One image a command buffer: the tower's host-written scratch is shared. +/// Slot `i`'s images into the engine's image rows, one image a command buffer: the tower's host scratch is shared. pub fn encode(sl: *Slots, i: u32, imgs: []const Image) !void { const e = sl.e; const v = e.vision orelse return error.NoVision; diff --git a/zig/src/families/glm/vision.zig b/zig/src/families/glm/vision.zig index 8a5a410de3..50021c8a05 100644 --- a/zig/src/families/glm/vision.zig +++ b/zig/src/families/glm/vision.zig @@ -1,7 +1,4 @@ -//! GLM-5.3-Flash's image tower on the GPU: an image's patches to the rows that replace its `<|image|>` placeholders. -//! mlx-vlm's glm5_next/vision.py (what TensorFold 0.6.6's --vision serves) in bf16: a patch projection, 24 pre-norm -//! blocks (2-D rotary attention over the image's own patches, a clipped SwiGLU), a final norm, the 2x2 merge as a -//! projection of four neighbouring patches, and the merger's projection, layer norm, GELU and clipped SwiGLU. +//! GLM-5.3-Flash's image tower on the GPU (mlx-vlm's glm5_next/vision.py in bf16): patches to `<|image|>` rows. const std = @import("std"); const mtl = @import("metal"); const sources = @import("kernel_sources"); @@ -27,7 +24,7 @@ pub const merge = 2; pub const patch_width = 3 * temporal * patch * patch; // 1176: a patch's values, channel by frame by row by column pub const patches_per_token = merge * merge; -/// --vision's limits: image tokens a prompt may hold in all (the tower's scratch and rows are sized for them), and images. +/// --vision's limits: image tokens a prompt may hold in all (scratch and rows are sized for them), and images. pub const Limits = struct { image_tokens: u32 = 4096, max_images: u32 = 4 }; pub const Config = struct { @@ -225,9 +222,7 @@ pub const Vision = struct { return .{ v.w.buf, v.scratch }; } - /// One image's patches ([gh * gw, 1176] fp32, the processor's order) into its tokens' rows `out` ([gh * gw / 4, - /// 4096] bf16). The host writes the scratch: the caller has no work of this tower in flight. `stop`: after the - /// patch projection (0) or block `stop` (1-24), the residual stream is left in `x` and nothing more runs. + /// One image's patches ([gh * gw, 1176] fp32) into its rows `out`; `stop`: end after that block, residual in `x`. pub fn encode(v: *Vision, enc: mtl.ComputeEncoder, pixels: []const f32, gh: u32, gw: u32, out: Ref, stop: ?u32) !void { const P: u32 = gh * gw; if (P == 0 or gh % merge != 0 or gw % merge != 0) return error.ImageGrid; @@ -308,7 +303,7 @@ pub const Vision = struct { v.gemm(enc, 0, x, w, y, M, N, K, K, K, N, 1, 0, 0, 0); } - /// tfp::gemm_nax: d [batch, M, N] = a x b (kind 0: bf16 a b^T, 1: fp32 a b^T, 2: fp32 a b), batches `s*` elements apart. + /// tfp::gemm_nax: d [batch, M, N] = a x b (kind 0: bf16 a b^T, 1: fp32 a b^T, 2: fp32 a b), batches `s*` apart. fn gemm(v: *Vision, enc: mtl.ComputeEncoder, kind: usize, a: Ref, b: Ref, d: Ref, M: u32, N: u32, K: u32, lda: u32, ldb: u32, ldd: u32, batch: u32, sa: usize, sb: usize, sd: usize) void { const tn = (N + 127) / 128; const tm = (M + 63) / 64; @@ -372,9 +367,7 @@ pub fn bf16(x: f32) u16 { return @truncate((b + 0x7fff + ((b >> 16) & 1)) >> 16); } -/// Each patch's 2-D rotary angles as vision.py builds them: the patch's row then column in the image's patch grid -/// (patches come in 2x2 merge windows, row-major windows), times the 16 frequencies 10000^(-k/16), cos and sin of -/// [h * f, w * f] twice over a head's 64 values. +/// Each patch's 2-D rotary cos and sin: its row and column in the patch grid times the 16 frequencies 10000^(-k/16). fn rotary(v: *Vision, gh: u32, gw: u32) void { var inv: [16]f32 = undefined; for (&inv, 0..) |*f, k| f.* = 1.0 / @as(f32, @floatCast(std.math.pow(f64, 10000.0, @as(f64, @floatFromInt(2 * k)) / 32.0))); @@ -514,8 +507,7 @@ fn loadWeights(gpa: std.mem.Allocator, device: mtl.Device, dir: []const u8) !Wei return w; } -/// `e` reads images: the tower loaded beside its weights (about 0.9 GiB with scratch for `lim.image_tokens` image -/// tokens a prompt) and the rows a prompt's images fill; `config` is the checkpoint's config.json. +/// `e` reads images: the tower loaded beside its weights (about 0.9 GiB with scratch) and the rows images fill. pub fn attach(e: *Engine, gpa: std.mem.Allocator, dir: []const u8, config: []const u8, lim: Limits) !void { if (e.ep != null) return error.VisionOnPair; const pj: ?mtl.MappedFile = blk: { diff --git a/zig/src/families/qwen27/cuda/engine.zig b/zig/src/families/qwen27/cuda/engine.zig index af3c6594b4..91b8103d2c 100644 --- a/zig/src/families/qwen27/cuda/engine.zig +++ b/zig/src/families/qwen27/cuda/engine.zig @@ -20,8 +20,7 @@ pub fn chunkBounds(start: usize, end: usize, size: usize, j: usize) [2]usize { return .{ start + (end - start) * j / n, start + (end - start) * (j + 1) / n }; } -/// A prompt's chunks from `from`: even splits of the whole prompt (0.6.6's PrefillPlan), or under a prompt cache the -/// zero-anchored grid, so a pass resumed or kept at a grid point cuts where a fresh pass of the same prompt does. +/// Chunks from `from`: even splits, or with a prompt cache the zero-anchored grid so resumed passes cut alike. pub const Chunks = struct { len: usize, grid: bool, @@ -130,7 +129,7 @@ pub const Engine = struct { return e.prefillFrom(seq, prompt, 0, media, null); } - /// The prompt from `from` (0, or a grid point the stream's state was restored at), keeping states at `keep`'s marks. + /// The prompt from `from` (0, or a grid point its state was restored at), keeping states at `keep`'s marks. pub fn prefillFrom(e: *Engine, seq: *st.Seq, prompt: []const u32, from: usize, media: ?*const vision.Media, keep: ?Keep) !void { if (prompt.len == 0) return error.EmptyPrompt; if (prompt.len >= seq.capacity) return error.PromptTooLong; diff --git a/zig/src/families/qwen27/cuda/image.zig b/zig/src/families/qwen27/cuda/image.zig index 736e6960c1..8dddeb9e25 100644 --- a/zig/src/families/qwen27/cuda/image.zig +++ b/zig/src/families/qwen27/cuda/image.zig @@ -1,10 +1,4 @@ -//! An image's bytes to Qwen3.5 vision patches as TensorFold 0.6.6's --vision makes them on CUDA: decoded as its -//! vision/images.py does with PIL (stb_image here: the stored values, no colour management; EXIF orientation applied; -//! alpha composited over white with PIL's integer blend), then transformers' Qwen2VLImageProcessorPil at the caps -//! 0.6.6 passes it: smart_resize to multiples of 32 within [32^2, tokens * 32^2] pixels, PIL's 8-bit bicubic -//! resampler, x / 255 in float64 rounded to float32, (x - 0.5) / 0.5, and 16x16 patches in 2x2 merge order with each -//! patch's frame given twice. JPEGs go through libjpeg-turbo (PIL's decoder) when libturbojpeg.so.0 loads, else -//! stb_image, whose IDCT may differ from PIL's by a level. +//! An image's bytes to Qwen3.5 vision patches as 0.6.6's --vision makes them: PIL's decode, smart_resize and bicubic. const std = @import("std"); const vision = @import("vision.zig"); @@ -54,8 +48,7 @@ pub fn prepareRgb(gpa: std.mem.Allocator, img: Rgb, hash: u64, max_tokens: u32) pub const Size = struct { h: u32, w: u32 }; -/// transformers' smart_resize: both sides multiples of `factor` (Python's round, half to even), the pixels within -/// [min_pixels, max_pixels], the aspect ratio kept as well as that allows. +/// transformers' smart_resize: sides multiples of `factor` (half-to-even), pixels within [min_pixels, max_pixels]. pub fn smartResize(height: u32, width: u32, min_pixels: u64, max_pixels_: u64) Error!Size { const h: f64 = @floatFromInt(height); const w: f64 = @floatFromInt(width); @@ -80,8 +73,7 @@ fn roundEven(x: f64) f64 { return if (@abs(x - @trunc(x)) == 0.5 and @mod(r, 2) != 0) r - std.math.sign(x) else r; } -/// The resized image scaled by 1/255 (in float64, then float32), normalized by mean 0.5 and std 0.5, cut into -/// 16x16 patches in 2x2 merge order, each patch [channel, frame (twice), row, column]. +/// The resized image as x / 255 (float64 to float32), normalized by 0.5 and 0.5, in 16x16 patches of 2x2 merge order. pub fn patchify(gpa: std.mem.Allocator, img: Rgb) Error![]f32 { const P = vision.patch; const M = vision.merge; @@ -145,8 +137,7 @@ const tjpf_rgb = 0; const tjcs_cmyk = 3; const tjcs_ycck = 4; -/// A JPEG through libjpeg-turbo as PIL decodes it (accurate integer IDCT, fancy upsampling) into RGB rows; null -/// when TurboJPEG is absent or the image is CMYK (PIL converts those itself). +/// A JPEG through libjpeg-turbo as PIL decodes it to RGB rows; null without TurboJPEG or for CMYK (PIL converts those). fn turboJpeg(gpa: std.mem.Allocator, bytes: []const u8) Error!?Rgb { const t = Turbo.get() orelse return null; const h = t.init() orelse return null; @@ -167,8 +158,7 @@ fn turboJpeg(gpa: std.mem.Allocator, bytes: []const u8) Error!?Rgb { return .{ .w = @intCast(W), .h = @intCast(H), .px = out }; } -/// A single-frame PNG or JPEG as 8-bit RGB: upright by its EXIF orientation, alpha composited over white, 16-bit -/// gray clipped to 255 and other 16-bit layouts cut to their high byte (what PIL's convert("RGB") gives). +/// A single-frame PNG or JPEG as 8-bit RGB: upright by EXIF, alpha over white, as PIL's convert("RGB") gives. pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) Error!Rgb { if (bytes.len < 8 or bytes.len > std.math.maxInt(c_int)) return error.BadImage; const n: c_int = @intCast(bytes.len); @@ -272,11 +262,9 @@ fn tiffOrientation(t: []const u8) u32 { return 1; } -// The functions below are the ones GLM's image.zig (families/glm) has for its Metal path: the same PIL arithmetic, -// kept here because the CUDA module cannot import that family's files. +// Below: GLM's image.zig (families/glm) PIL arithmetic, copied since the CUDA module cannot import that family's files. -/// PIL's exif_transpose: orientation 2-8 as FLIP_LEFT_RIGHT, ROTATE_180, FLIP_TOP_BOTTOM, TRANSPOSE, ROTATE_270, -/// TRANSVERSE, ROTATE_90; each output pixel read from its source pixel. +/// PIL's exif_transpose for orientations 2-8; each output pixel read from its source pixel. pub fn orient(gpa: std.mem.Allocator, src: Rgb, o: u32) Error!Rgb { const w: usize = src.w; const h: usize = src.h; diff --git a/zig/src/families/qwen27/cuda/kernels.zig b/zig/src/families/qwen27/cuda/kernels.zig index 964eb4536b..c43f19aacb 100644 --- a/zig/src/families/qwen27/cuda/kernels.zig +++ b/zig/src/families/qwen27/cuda/kernels.zig @@ -45,8 +45,7 @@ pub const pattn_smem: u32 = 98304; // two 32-key slots of 256 dims beside eight /// One item of a batched copy: 16-byte aligned pointers, a multiple of 16 bytes. pub const Copy = extern struct { dst: u64, src: u64, bytes: u64 }; -/// One item of qwen_ops.cu's kv_quant (--kv-cache fp8): `rows` bf16 rows of 256 from src, as e4m3 rows at dst and -/// one fp32 scale a row at scale. +/// One item of qwen_ops.cu's kv_quant (--kv-cache fp8): `rows` bf16 rows of 256 to e4m3 rows plus an fp32 scale each. pub const Quant = extern struct { src: u64, dst: u64, scale: u64, rows: u64 }; /// A tiled 4-bit projection: packed words, (kg, npad) scales and biases, n outputs from k inputs. diff --git a/zig/src/families/qwen27/cuda/lanes.zig b/zig/src/families/qwen27/cuda/lanes.zig index adae5d4913..acbd27a1c1 100644 --- a/zig/src/families/qwen27/cuda/lanes.zig +++ b/zig/src/families/qwen27/cuda/lanes.zig @@ -230,8 +230,7 @@ pub const Cuda = struct { try x.prefillOpened(s, seq); } - /// prefill_state into an opened stream: the prompt in chunks, a drafting stream's last window of taps absorbed. A - /// kept state the lane host found is restored first, and the pass stops at its marks for the cache to copy. + /// prefill_state into an opened stream: a found kept state restored, then the prompt in chunks to the cache marks. fn prefillOpened(x: *Cuda, s: *lanes.Stream, seq: *st.Seq) !void { // an image prompt: the tower's rows and the prompt's three positions for its pass (EncodedVision) const media: ?*vision.Media = if (s.images.len == 0) null else blk: { diff --git a/zig/src/families/qwen27/cuda/lone.zig b/zig/src/families/qwen27/cuda/lone.zig index bb384e9ce4..9f55fe1fca 100644 --- a/zig/src/families/qwen27/cuda/lone.zig +++ b/zig/src/families/qwen27/cuda/lone.zig @@ -81,8 +81,7 @@ pub fn prefillMedia(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, return prefillFrom(e, seq, ctx, d, prompt, 0, media, null); } -/// prefillMedia from `from` (0, or the grid point a kept state was restored at), keeping states at `keep`'s marks. A -/// resumed pass's context holds only the rows it read: drafts change no token, so a reply is the same either way. +/// prefillMedia from `from` (0, or a restored grid point), keeping states at `keep`'s marks; drafts change no token. pub fn prefillFrom(e: *Engine, seq: *st.Seq, ctx: *dr.Context, d: *dr.DFlash2, prompt: []const u32, from: usize, media: ?*const @import("vision.zig").Media, keep: ?eng.Keep) !void { if (prompt.len >= seq.capacity) return error.PromptTooLong; if (from == 0) try seq.reset(e.ops(), e.w.g) else if (from != seq.pos or !eng.resumable(from, prompt.len)) return error.BadReuse; diff --git a/zig/src/families/qwen27/cuda/reuse.zig b/zig/src/families/qwen27/cuda/reuse.zig index 750569c852..c8e36ded25 100644 --- a/zig/src/families/qwen27/cuda/reuse.zig +++ b/zig/src/families/qwen27/cuda/reuse.zig @@ -1,5 +1,4 @@ -//! Qwen3.8-27B CUDA prompt states for the shared cache: a stream's DeltaNet recurrences, conv windows and its attention -//! rows so far, copied to pinned host memory (a long window's caches leave the device no room for copies). +//! Qwen3.8-27B CUDA prompt states for the shared cache: DeltaNet recurrences, conv windows and attention rows on host. const std = @import("std"); const cuda = @import("cuda"); @@ -23,8 +22,7 @@ pub const Target = struct { /// One piece of a stream's state: its device address and length. const Piece = struct { dev: u64, len: usize }; -/// The pieces a state at `at` holds, in their order in a copy: each DeltaNet layer's recurrence and conv window, each -/// attention layer's first `at` key and value rows (and their scales under kv8). `seq` null: lengths only. +/// A state at `at`'s pieces in copy order (DeltaNet state, conv windows, `at` K/V rows, kv8 scales); seq null: lengths. fn pieces(g: c.Geometry, kv8: bool, seq: ?*const st.Seq, at: usize, out: []Piece) []Piece { var n: usize = 0; const row: usize = g.kvInner() * @as(usize, if (kv8) 1 else 2); diff --git a/zig/src/families/qwen27/cuda/round.zig b/zig/src/families/qwen27/cuda/round.zig index 7fd0b2f770..0d355ce181 100644 --- a/zig/src/families/qwen27/cuda/round.zig +++ b/zig/src/families/qwen27/cuda/round.zig @@ -56,9 +56,7 @@ pub fn parentsOf(p: Part, buf: []i32) []const i32 { return buf[0..p.tokens.len]; } -/// attention.plan_host: rows, (first, rows, keys, slots) per stream, items, then window parents (global rows). -/// Where attnPlan put its segments, in ints from the plan's first: each starts on a 16-byte boundary, so the -/// attention kernels' plan pointers are the aligned ones Triton's captured variants were compiled for. +/// Segment offsets in ints of attnPlan's plan_host, each on a 16-byte boundary for Triton's aligned plan pointers. const AttnAt = struct { n_items: usize, streams: usize, items: usize, parents: usize }; fn pad16(out: *std.ArrayList(i32), gpa: std.mem.Allocator, from: usize) !usize { @@ -108,8 +106,7 @@ fn offsetOf(s: *const st.Scratch, ptr: u64) i64 { return @divExact(@as(i64, @bitCast(ptr -% s.origin)), bf); } -/// Layer `i`'s cache offsets for a stream: bf16 elements of keys and values, or under kv8 e4m3 bytes of keys and -/// values and fp32 elements of their scales. +/// Layer `i`'s cache offsets for a stream: bf16 elements of keys and values, or under kv8 e4m3 bytes plus fp32 scales. fn cacheOffsets(s: *const st.Scratch, seq: *const st.Seq, i: usize, out: *std.ArrayList(i64), gpa: std.mem.Allocator) !void { if (!seq.kv8) return out.appendSlice(gpa, &.{ offsetOf(s, seq.keys[i]), offsetOf(s, seq.values[i]) }); const d = struct { diff --git a/zig/src/families/qwen27/cuda/state.zig b/zig/src/families/qwen27/cuda/state.zig index e85f68a5b5..433102b490 100644 --- a/zig/src/families/qwen27/cuda/state.zig +++ b/zig/src/families/qwen27/cuda/state.zig @@ -241,8 +241,7 @@ pub const Scratch = struct { return a(usize, slot_rows * g.query_heads * c.head_dim * 4, 256) + 2 * a(usize, slot_rows * g.query_heads * 4, 256); } - /// The slot-rows a stream of `capacity` positions may add to a round: its most slots (attention.slots of any - /// keys and window it can hold) times its widest window. + /// The slot-rows a stream of `capacity` positions may add to a round: its most slots times its widest window. pub fn streamPartRows(capacity: usize) usize { return ((capacity + max_rows + tri.chunk - 1) / tri.chunk + 1) * max_rows; } diff --git a/zig/src/families/qwen27/cuda/triton.zig b/zig/src/families/qwen27/cuda/triton.zig index bc737a39ec..d52e14174b 100644 --- a/zig/src/families/qwen27/cuda/triton.zig +++ b/zig/src/families/qwen27/cuda/triton.zig @@ -119,9 +119,7 @@ pub const Tri = struct { }, &.{ ci("H", a.heads), ci("D", a.dim), ci("G", g), ci("DS", merge_columns), ci("CH", chunk), ci("GR", group_chunks) }); } - /// attention8 (attention_kv8.py, captured outside the tree like the rest of the set): attention over e4m3 - /// caches, `offs` holding each stream's four offsets (key and value bytes, their scales' fp32 elements) from - /// `base`; the window's own keys and values stay bf16. + /// attention8 (attention_kv8.py): e4m3 cache attention at `base` plus each stream's `offs`; window K/V stay bf16. pub fn attention8(t: Tri, q: u64, kn: u64, vn: u64, base: u64, offs: u64, plan: Plan, part: Partials, out: u64, a: Attn) !void { const g = a.heads / a.kv_heads; const scale: f32 = @floatCast(std.math.pow(f64, @floatFromInt(a.dim), -0.5)); diff --git a/zig/src/families/qwen27/cuda/vision.zig b/zig/src/families/qwen27/cuda/vision.zig index 951cff63d0..c455e25bbb 100644 --- a/zig/src/families/qwen27/cuda/vision.zig +++ b/zig/src/families/qwen27/cuda/vision.zig @@ -1,7 +1,4 @@ -//! The Qwen3.5 vision tower on CUDA (transformers' Qwen3_5VisionModel, as 0.6.6's --vision runs it in bf16): patch -//! embedding, the learned position grid resampled bilinearly to each image, 27 pre-norm blocks of axial 2-D rotary -//! attention within each image, and the 2x2 merger to the language model's width. Linears on cuBLASLt (fp32 out), -//! the rest in qwen_vision.cu. +//! The Qwen3.5 vision tower on CUDA as 0.6.6's --vision runs it in bf16: patch embed, 27 rotary blocks, 2x2 merger. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -86,8 +83,7 @@ pub const Tower = struct { inv: u64 = 0, weight_bytes: usize = 0, - /// The checkpoint's vision_tower tensors (bf16), every one used; the patch convolution's weight as rows of - /// [channel, frame, y, x], the order the patches come in. + /// The checkpoint's vision_tower tensors (bf16); the patch convolution's weight as [channel, frame, y, x] rows. pub fn load(gpa: std.mem.Allocator, io: std.Io, ops: Gpu, dir: []const u8) !*Tower { const t = try gpa.create(Tower); errdefer gpa.destroy(t); @@ -212,8 +208,7 @@ pub const Tower = struct { workspace_bytes; } - /// Images' patches (fp32 rows of `patch_width`, each image's in its grid's merge order) to their merged rows - /// (bf16 [sum(h * w) / 4, out_hidden]) at `out`; every image attends only to itself. + /// Images' patches (fp32, merge order) to merged bf16 [sum(h * w) / 4, out_hidden] at `out`, each image on its own. pub fn encode(t: *Tower, ops: Gpu, pixels: []const f32, grids: []const Grid, out: u64) !void { var n: usize = 0; for (grids) |g| { @@ -299,8 +294,7 @@ pub const Tower = struct { try ops.s.synchronize(); } - /// A prompt chunk's embeddings `x` (rows bf16 of the language width) take image rows: row r takes `features` - /// row src[r] (device int32) where src[r] >= 0. + /// Splices image rows into a chunk's embeddings `x`: row r takes `features` row src[r] where src[r] >= 0. pub fn splice(t: *Tower, ops: Gpu, x: u64, features: u64, src: u64, rows: usize) !void { try t.go(ops, t.f.splice, rows, 1, 256, .{ x, features, src, int(out_hidden) }); } @@ -360,8 +354,7 @@ pub fn invFreq(out: []f32) void { } } -/// One image's patches in merge order: each patch's (row, column) for the rotary, and its 4 bilinear taps (with -/// align_corners) into the 48x48 learned grid with their fp32 weights, as transformers' vision_utils computes them. +/// One image's patches in merge order: each one's (row, column) for the rotary and 4 bilinear taps into the 48x48 grid. pub fn positions(g: Grid, hw: []i32, idx: []i32, wts: []f32) void { const bw = g.w / merge; const n = @as(usize, g.h) * g.w; @@ -409,8 +402,7 @@ test "bilinear taps match align_corners resampling at the ends and middle" { try std.testing.expectEqual(@as(f32, 1), b.w[0]); } -/// An image prompt's rows for its prompt pass (0.6.6's EncodedVision): the tower's rows on the GPU, each prompt row's -/// feature row (or -1), the three rotary positions of every prompt row and the decode offset after the prompt. +/// An image prompt's rows for its prompt pass (0.6.6's EncodedVision): tower rows, feature rows, positions. pub const Media = struct { gpa: std.mem.Allocator, tower: *Tower, @@ -420,9 +412,7 @@ pub const Media = struct { delta: i32, dev: cuda.DeviceBuffer, // a chunk's src and [3][rows] positions - /// Encodes `images` (Image.at: the first of its tokens' rows) and lays out the prompt's positions as - /// transformers' get_rope_index does: text counts up on all three axes; an image sits at the next position with - /// its merged rows and columns on the h and w axes; text after it resumes past its larger side. + /// Encodes `images` and lays out the prompt's positions as transformers' get_rope_index does (see `layout`). pub fn init(gpa: std.mem.Allocator, tower: *Tower, ops: Gpu, prompt: []const u32, images: anytype, chunk_rows: usize) !*Media { const n = prompt.len; const m = try gpa.create(Media); @@ -479,8 +469,7 @@ pub const Media = struct { } }; -/// The prompt's three rotary positions ([3][n]) and each placeholder row's feature row (src, -1 for text), as -/// transformers' get_rope_index lays them out; returns the decode offset (rope_delta). +/// The prompt's rotary positions ([3][n]) and feature rows (src, -1 for text) per get_rope_index; returns rope_delta. pub fn layout(prompt: []const u32, images: anytype, src: []i32, pos: []i32) !i32 { const n = prompt.len; @memset(src, -1); diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 16c2542444..f80b52f047 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -369,8 +369,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O const h = try gpa.create(Host); errdefer gpa.destroy(h); h.* = .{ .gpa = gpa, .gpu = g, .family = loaded.ctx, .release = loaded.deinit, .inner = loaded.backend, .vtable = undefined, .cfg = undefined, .clock = undefined, .core = undefined, .host = undefined, .lone = loaded.lone }; - // a family with prompt-cache snapshots keeps them in device room (Nemotron) or in pinned host memory (the 27B, whose - // long window leaves the device none); a family without them serves without a cache + // prompt-cache snapshots live in device room (Nemotron) or pinned host memory (the 27B); none means no cache const cache = if (!@hasDecl(F, "snap_bytes")) 0 else if (@hasDecl(F, "snap_host")) hostCacheBytes(a, io, o.prompt_cache_gib) else budget.cacheBytes(o.prompt_cache_gib, room, loaded.stream_bytes * (streams -| free)); h.startup = try std.fmt.allocPrint(gpa, "CUDA sm_{d} device {d} ({s}{s}): model {d:.2} GiB{s}; {d} stream{s} at once, {d:.2} GiB each at a {d}-token window{s}, of {d:.1} GiB left after a {d:.1} GiB reserve; prompts in passes of up to {d} rows{s}{s}; {s}", .{ capability, device, name, if (after.unified) ", memory shared with the host" else "", toGib(model), if (loaded.learn_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for --slide's trainer", .{toGib(loaded.learn_bytes)}) else if (vision_bytes > 0) try std.fmt.allocPrint(a, " and {d:.2} GiB kept for the image tower's calls", .{toGib(vision_bytes)}) else "", streams, if (streams == 1) "" else "s", toGib(loaded.stream_bytes), window, if (o.kv8) " (fp8 caches)" else "", toGib(room), toGib(after.reserve), F.prompt_rows, if (segments > 1) try std.fmt.allocPrint(a, ", {d} staggered segments a call", .{segments}) else "", @@ -380,8 +379,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O if (@hasDecl(F, "snap_bytes") and cache > 0) { const pc = api.prompt_cache; const store = try gpa.create(pc.Store); - // Nemotron: a row's bits ignore the cuts and a kept row costs no call, so states keep at any row; its head reads - // one token on. The 27B: states on its zero-anchored grid, where a cache-off pass cuts, ending where the pass stands. + // Nemotron keeps states at any row, head one token on; the 27B on its zero-anchored grid where cache-off cuts const rules: pc.Rules = if (@hasDecl(F, "snap_host")) .{ .lookahead = F.snap_lookahead, .planned = true, .grid = F.prompt_rows } else .{ .lookahead = 1, .min_prompt = 0, .warm = .waits }; const ready: u64 = if (@hasDecl(F, "snap_ready")) try F.snap_ready(loaded.target, cache) else 0; store.* = pc.Store.init(gpa, .{ .ptr = loaded.target, .vtable = &Snaps(F).vtable }, rules, cache - ready); diff --git a/zig/src/server/images.zig b/zig/src/server/images.zig index d99b121300..a4823c4610 100644 --- a/zig/src/server/images.zig +++ b/zig/src/server/images.zig @@ -1,5 +1,4 @@ -//! Image input (--vision): a request's image_url parts to the engine's tower input, and the rendered prompt's -//! placeholders expanded to each image's tokens, as TensorFold 0.6.6's vision path does for GLM-5.3-Flash. +//! Image input (--vision): image_url parts to the engine's tower input, the prompt's placeholders to image tokens. const std = @import("std"); const api = @import("engine_api"); const json = @import("json.zig"); @@ -58,8 +57,7 @@ pub const Fetch = struct { } }; -/// An image part's bytes, at most `limit`: a data URL's, or with --vision-urls (`fetch`) a public HTTPS URL's, fetched -/// before `deadline` (images.py _check_source and load_images). +/// An image part's bytes, at most `limit`: a data URL's, or with --vision-urls a public HTTPS URL's before `deadline`. pub fn sourceBytes(cx: *Cx, fetch: ?Fetch, url: []const u8, limit: usize, deadline: std.Io.Timestamp) errors.Refused![]const u8 { if (std.ascii.startsWithIgnoreCase(url, "data:")) { const bytes = try dataBytes(cx, url); @@ -151,8 +149,7 @@ pub fn markerText(text: model_text.Text, a: std.mem.Allocator, v: api.Vision) ![ return out.items; } -/// `messages` with each marker the text spells (a user's words, a tool's output) replaced by its sentinel, so only -/// the template's own markers, one wrapper per image part, render as the image tokens (#511). +/// `messages` with each marker the text spells replaced by its sentinel, so only the template's become images (#511). pub fn shield(a: std.mem.Allocator, v: Value, markers: []const []const u8) !Value { return switch (v) { .string => |s| .{ .string = try shieldText(a, s, markers) }, @@ -189,8 +186,7 @@ fn shieldText(a: std.mem.Allocator, s: []const u8, markers: []const []const u8) return if (changed) out.items else s; } -/// The rendered prompt's ids: its text as the tokenizer reads it, each sentinel's marker as ordinary text tokens. -/// Added tokens split the text anyway, so a prompt without quoted markers gets exactly `encode`'s ids. +/// The rendered prompt's ids, each sentinel's marker as ordinary text tokens; otherwise exactly `encode`'s ids. pub fn encodeShielded(text: model_text.Text, a: std.mem.Allocator, rendered: []const u8, markers: []const []const u8) model_text.Error![]u32 { var ids: std.ArrayList(u32) = .empty; var rest = rendered; @@ -211,9 +207,7 @@ pub fn encodeShielded(text: model_text.Text, a: std.mem.Allocator, rendered: []c return ids.items; } -/// The prompt with each image's placeholder expanded to its tokens, the images for the engine and the prompt as the -/// cache matches it; null when the engine reads no images. Images are counted from the request's image parts; the -/// rendered placeholders are the template's alone (text that spells a marker was shielded), one per part. +/// The prompt with each image's placeholder expanded to its tokens, the images and the cache key; null without vision. pub fn expand(vision: ?api.Vision, fetch: ?Fetch, cx: *Cx, messages: Value, ids: []const u32, history_len: usize) errors.Refused!?Expanded { const v = vision orelse return null; const ps = try parts(cx, messages); diff --git a/zig/src/server/media_fetch.zig b/zig/src/server/media_fetch.zig index d642ce0b2e..6183039a74 100644 --- a/zig/src/server/media_fetch.zig +++ b/zig/src/server/media_fetch.zig @@ -1,8 +1,4 @@ -//! Public HTTPS images for --vision-urls, as TensorFold 0.6.6's server fetched them (vision/images_http.py): an https -//! URL on port 443 without credentials or a fragment, its host resolved and every address checked public, a TLS -//! connection verified for the host on an address that was checked, GET with identity encoding, up to 3 redirects -//! (each checked the same way), a declared media type the caller accepts, the bytes within the caller's limit, all -//! inside a deadline. +//! Public HTTPS images for --vision-urls as TensorFold 0.6.6 fetched them: every address and redirect checked public. const std = @import("std"); const Io = std.Io; const net = std.Io.net; @@ -26,8 +22,7 @@ fn fail(f: *Failure, text: []const u8) Error { return error.Media; } -/// Python ipaddress: is_global and not multicast or reserved, nor 192.0.0.0/24 or 168.63.129.16; no IPv6 address -/// that embeds an IPv4 one (mapped, 6to4, Teredo). +/// Python ipaddress is_global, less multicast, reserved, 192.0.0.0/24, 168.63.129.16 and IPv6 embedding an IPv4 one. pub fn publicIp(a: net.IpAddress) bool { switch (a) { .ip4 => |v| { @@ -46,8 +41,7 @@ pub fn publicIp(a: net.IpAddress) bool { }, .ip6 => |v| { const b = v.bytes; - // global unicast 2000::/3 only, less documentation (2001:db8::/32), the 2001::/23 IETF block (Teredo - // 2001::/32 among it) and 6to4 (2002::/16) + // global unicast 2000::/3 less documentation, the 2001::/23 IETF block (Teredo among it) and 6to4 if (b[0] & 0xe0 != 0x20) return false; if (b[0] == 0x20 and b[1] == 0x01 and b[2] == 0x0d and b[3] == 0xb8) return false; if (b[0] == 0x20 and b[1] == 0x01 and b[2] < 0x02) return false; @@ -59,9 +53,7 @@ pub fn publicIp(a: net.IpAddress) bool { /// A URL as a request takes it: the lowercased host and the percent-quoted path and query. pub const Url = struct { host: []const u8, target: []const u8 }; -/// images_http._url: https, a host, port 443, no credentials, fragment, backslash, whitespace or controls. A host -/// that isn't ASCII (an IDNA name) or is an IPv6 literal is refused: std has no IDNA encoder, and TLS here verifies -/// names. +/// images_http._url: https, port 443, no credentials, fragment, backslash, whitespace, controls, IDNA or IPv6 host. pub fn parseUrl(a: std.mem.Allocator, value: []const u8, f: *Failure) Error!Url { if (value.len > max_url_chars) return fail(f, "image URL is too long or contains whitespace/control characters"); for (value) |c| if (c <= 32 or c == 127) return fail(f, "image URL is too long or contains whitespace/control characters"); @@ -103,8 +95,7 @@ pub fn parseUrl(a: std.mem.Allocator, value: []const u8, f: *Failure) Error!Url return .{ .host = lower, .target = t.items }; } -/// The location a redirect names, resolved against `base` (urljoin's absolute, scheme-relative, absolute-path and -/// relative forms). +/// The location a redirect names, resolved against `base` (urljoin's absolute, scheme-relative and relative forms). pub fn join(a: std.mem.Allocator, base: []const u8, location: []const u8) ![]const u8 { if (std.ascii.startsWithIgnoreCase(location, "https://") or std.ascii.startsWithIgnoreCase(location, "http://")) return a.dupe(u8, location); if (std.mem.startsWith(u8, location, "//")) return std.fmt.allocPrint(a, "https:{s}", .{location}); @@ -129,8 +120,7 @@ pub const Body = struct { data: []u8, media: []const u8 }; /// What one request gave: the body, or a redirect's location. pub const Got = union(enum) { body: Body, redirect: []const u8 }; -/// The bytes of `url` and its media type (one of `media_types`), at most `max_bytes`, before `deadline` and within -/// one download's seconds, redirects followed and each checked again. +/// `url`'s bytes and media type (one of `media_types`), at most `max_bytes`, before `deadline`, redirects rechecked. pub fn fetch(a: std.mem.Allocator, io: Io, url: []const u8, max_bytes: usize, deadline: Io.Timestamp, media_types: []const []const u8, f: *Failure) Error!Body { return fetchVia(a, io, url, max_bytes, deadline, media_types, f, Network{}); } @@ -159,8 +149,7 @@ pub fn ask(w: *Io.Writer, u: Url, accept: []const u8) Io.Writer.Error!void { try w.flush(); } -/// The response read from `r`: a redirect's location, or a 200's body when its encoding, declared type and length -/// pass (Content-Length or chunked, else to the end of the stream). +/// The response from `r`: a redirect's location, or a 200's body when its encoding, declared type and length pass. pub fn answer(a: std.mem.Allocator, io: Io, r: *Io.Reader, max_bytes: usize, deadline: Io.Timestamp, media_types: []const []const u8, f: *Failure) Error!Got { const broke = "image download failed or timed out"; const too_big = "image response exceeds the encoded byte limit"; @@ -247,8 +236,7 @@ fn readInto(a: std.mem.Allocator, io: Io, r: *Io.Reader, data: *std.ArrayList(u8 } } -/// A TCP connection to the checked address on port 443, its connect bounded by `ms` (std's connect has no timeout -/// yet: a nonblocking connect and poll) and its sends and reads by the socket's timeouts. +/// A TCP connection to the checked address on port 443, its connect bounded by `ms` (std's connect has no timeout). fn connect(addr: net.IpAddress, ms: i64, f: *Failure) Error!net.Stream { const c = std.c; const failed = "image download failed or timed out"; diff --git a/zig/src/server/messages.zig b/zig/src/server/messages.zig index 48a0d77f6c..21806820bb 100644 --- a/zig/src/server/messages.zig +++ b/zig/src/server/messages.zig @@ -50,8 +50,7 @@ fn imagePart(cx: *Cx, part: Value) errors.Refused!Value { return .{ .object = out }; } -/// `normalize`, and with `images` (an engine that reads them) a user or tool message's image_url parts kept beside its -/// text parts, in order, for the template's image markers; a message without image parts is joined text as before. +/// `normalize`, and with `images` a user or tool message's image_url parts kept in order beside its text parts. pub fn normalizeWith(cx: *Cx, messages: ?Value, late_system: []const u8, needs_user_after_tool: bool, images: bool) errors.Refused!Value { const list = messages orelse return cx.refuse("messages must be a non-empty list"); if (list != .array or list.array.len == 0) return cx.refuse("messages must be a non-empty list"); @@ -71,7 +70,7 @@ pub fn normalizeWith(cx: *Cx, messages: ?Value, late_system: []const u8, needs_u for (content.?.array) |part| { const kind = if (part == .object and part.get("type") != null and part.get("type").? == .string) part.get("type").?.string else ""; if (images and std.mem.eql(u8, kind, "image_url")) { - // a tool's result carries images as agents send screenshots; the template renders them in its response + // tool results carry screenshots too; the template renders them in its response if (!std.mem.eql(u8, role.?.string, "user") and !std.mem.eql(u8, role.?.string, "tool")) return cx.refuse("image parts are accepted in user and tool messages only"); try parts.append(cx.a, try imagePart(cx, part)); has_image = true; diff --git a/zig/src/server/model_text.zig b/zig/src/server/model_text.zig index 33b5baa78c..b036ca8342 100644 --- a/zig/src/server/model_text.zig +++ b/zig/src/server/model_text.zig @@ -36,7 +36,7 @@ pub const Text = struct { template_source: *const fn (ctx: *anyopaque) []const u8, /// Whether an id is a special token (an added token flagged special); null: none are known. special: ?*const fn (ctx: *anyopaque, id: u32) bool = null, - /// Ids of ``text`` with no added token matched (text that spells a special token is ordinary text); null: ``encode``. + /// Ids of ``text`` with no added token matched (a spelled special token is plain text); null: ``encode``. encode_plain: ?*const fn (ctx: *anyopaque, a: Allocator, text: []const u8) Error![]u32 = null, /// A token's own bytes (a partial UTF-8 sequence kept whole) for logprob rows; null: the tokenizer can't say. token_bytes: ?*const fn (ctx: *anyopaque, a: Allocator, id: u32) Allocator.Error!?[]u8 = null, diff --git a/zig/src/server/prompt.zig b/zig/src/server/prompt.zig index df2a7024c6..220013501f 100644 --- a/zig/src/server/prompt.zig +++ b/zig/src/server/prompt.zig @@ -11,8 +11,7 @@ const Server = @import("server.zig").Server; const Value = json.Value; const Cx = errors.Cx; -/// With image input, `ids` holds each image's tokens in place of its placeholder, `images` are theirs in order and -/// `cache_key` is the prompt as the cache matches it (engine_api.Request). +/// With image input, `ids` holds each image's tokens, `images` the images and `cache_key` the prompt the cache matches. pub const Rendered = struct { ids: []const u32, history_len: usize = 0, rewind_len: usize = 0, images: []const api.Image = &.{}, cache_key: []const u32 = &.{} }; /// Where lessons decide to act on a reply: the row before the generation prompt's ``, else before its last. @@ -56,7 +55,7 @@ pub fn renderIds(srv: *Server, cx: *Cx, messages: Value, tools: []const Value, t return ids; } -/// The template's ids for `messages`; with image input, a marker the messages' text spells is ordinary text (images.zig). +/// The template's ids for `messages`; with image input, a marker the text spells is ordinary text (images.zig). fn render(srv: *Server, a: std.mem.Allocator, messages: Value, options: model_text.RenderOptions, problem: *[]const u8) model_text.Error![]u32 { const v = srv.info.vision orelse return srv.text.renderIds(a, messages, options, problem); const markers = try images.markerText(srv.text, a, v); @@ -113,8 +112,7 @@ pub fn prepare(srv: *Server, cx: *Cx, input: chat.Input, thinking: bool, effort: var history_len: usize = 0; if (history.len > 0 and history.len < prompt.len and std.mem.eql(u32, prompt[0..history.len], history)) history_len = history.len; if (history_len == 0 and prompt.len > 1 and std.mem.eql(u32, history, prompt)) history_len = prompt.len - 1; // a template with no generation suffix - // --vision: each image's placeholder expanded to its tokens before the window, chunks and cache see the prompt; - // such a prompt keeps no rewind, which the expansion does not translate + // --vision: placeholders expanded to image tokens before the window, chunks and cache see it; no rewind kept if (try images.expand(srv.info.vision, if (srv.config.vision_urls) images.Fetch.network(srv.io) else null, cx, input.messages, prompt, history_len)) |x| return .{ .ids = x.ids, .history_len = x.history_len, .images = x.images, .cache_key = x.cache_key }; const count = if (input.messages == .array) input.messages.array.len else 0; const rewind_len = if (srv.info.prompt_cache) rewindLen(srv, cx, input.messages, count, input.tools, prompt, thinking, effort) else 0; // one more render From 5a4987b7702255cd0e8cb21b50b06834fd4c076b Mon Sep 17 00:00:00 2001 From: ZackSample <134018356+ZackSample@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:53:02 -0500 Subject: [PATCH 13/17] Living Weights: the learner, pocket and fits move to zig/src/living, unchanged The learner, its whole-lesson and routed paths, the pocket and its fits and helpers move from families/nemotron to a `living` module that both builds import, as 19 renames with no change to their contents. The family-neutral half of learn_shape.zig (block sizes, Adam settings, direction lengths) moves with them; Nemotron's learn_shape.zig keeps where its blocks sit and names the shared constants from the module. Nemotron's files import the moved ones through the module. The learner's tests now also run on Linux, as `zig build test-living` and under test-cuda-host. No behaviour change. --- build.zig | 8 ++-- zig/build/cuda.zig | 11 +++++- zig/src/families/nemotron/adapters.zig | 4 +- zig/src/families/nemotron/backend.zig | 2 +- zig/src/families/nemotron/cuda.zig | 2 - zig/src/families/nemotron/cuda_engine.zig | 2 +- zig/src/families/nemotron/cuda_forward.zig | 2 +- zig/src/families/nemotron/cuda_lanes.zig | 2 +- zig/src/families/nemotron/cuda_prompt.zig | 2 +- zig/src/families/nemotron/cuda_sites.zig | 4 +- zig/src/families/nemotron/cuda_slide.zig | 2 +- zig/src/families/nemotron/cuda_state.zig | 2 +- zig/src/families/nemotron/cuda_train.zig | 6 +-- zig/src/families/nemotron/cuda_train_fwd.zig | 2 +- zig/src/families/nemotron/cuda_train_ops.zig | 2 +- zig/src/families/nemotron/forward.zig | 2 +- zig/src/families/nemotron/layers.zig | 2 +- zig/src/families/nemotron/learn_shape.zig | 39 +++++++------------ zig/src/families/nemotron/nemotron.zig | 4 +- zig/src/families/nemotron/prefill.zig | 2 +- zig/src/families/nemotron/slide.zig | 2 +- zig/src/families/nemotron/state.zig | 2 +- zig/src/families/nemotron/train.zig | 6 +-- zig/src/families/nemotron/train_back.zig | 2 +- zig/src/families/nemotron/train_forward.zig | 2 +- zig/src/families/nemotron/train_job.zig | 4 +- zig/src/families/nemotron/train_ops.zig | 2 +- .../{families/nemotron => living}/choice.zig | 0 .../{families/nemotron => living}/editor.zig | 0 zig/src/living/learn_shape.zig | 25 ++++++++++++ .../{families/nemotron => living}/learner.zig | 0 .../nemotron => living}/lesson_examples.zig | 0 .../nemotron => living}/lesson_route.zig | 0 zig/src/living/living.zig | 30 ++++++++++++++ .../{families/nemotron => living}/pocket.zig | 0 .../nemotron => living}/pocket_clock.zig | 0 .../nemotron => living}/pocket_dump.zig | 0 .../nemotron => living}/pocket_fit.zig | 0 .../nemotron => living}/pocket_joint.zig | 0 .../nemotron => living}/pocket_pack.zig | 0 .../nemotron => living}/pocket_prefix.zig | 0 .../nemotron => living}/pocket_read.zig | 0 .../nemotron => living}/pocket_values.zig | 0 .../{families/nemotron => living}/probe.zig | 0 .../{families/nemotron => living}/router.zig | 0 .../nemotron => living}/subspace.zig | 0 .../nemotron => living}/train_mode.zig | 0 .../{families/nemotron => living}/whole.zig | 0 zig/src/tensorfold.zig | 6 --- 49 files changed, 114 insertions(+), 69 deletions(-) rename zig/src/{families/nemotron => living}/choice.zig (100%) rename zig/src/{families/nemotron => living}/editor.zig (100%) create mode 100644 zig/src/living/learn_shape.zig rename zig/src/{families/nemotron => living}/learner.zig (100%) rename zig/src/{families/nemotron => living}/lesson_examples.zig (100%) rename zig/src/{families/nemotron => living}/lesson_route.zig (100%) create mode 100644 zig/src/living/living.zig rename zig/src/{families/nemotron => living}/pocket.zig (100%) rename zig/src/{families/nemotron => living}/pocket_clock.zig (100%) rename zig/src/{families/nemotron => living}/pocket_dump.zig (100%) rename zig/src/{families/nemotron => living}/pocket_fit.zig (100%) rename zig/src/{families/nemotron => living}/pocket_joint.zig (100%) rename zig/src/{families/nemotron => living}/pocket_pack.zig (100%) rename zig/src/{families/nemotron => living}/pocket_prefix.zig (100%) rename zig/src/{families/nemotron => living}/pocket_read.zig (100%) rename zig/src/{families/nemotron => living}/pocket_values.zig (100%) rename zig/src/{families/nemotron => living}/probe.zig (100%) rename zig/src/{families/nemotron => living}/router.zig (100%) rename zig/src/{families/nemotron => living}/subspace.zig (100%) rename zig/src/{families/nemotron => living}/train_mode.zig (100%) rename zig/src/{families/nemotron => living}/whole.zig (100%) diff --git a/build.zig b/build.zig index 08765bd1df..5e7677cba7 100644 --- a/build.zig +++ b/build.zig @@ -539,7 +539,7 @@ fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b } /// The server and distribution use the same embedded-source Metal engine. -fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, draft_ids: *std.Build.Module) struct { metal: *std.Build.Module, lanes: *std.Build.Module, fabric: *std.Build.Module, sources: *std.Build.Module, engine: *std.Build.Module, qwen27: qwen27_build.Shared } { +fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, draft_ids: *std.Build.Module) struct { metal: *std.Build.Module, lanes: *std.Build.Module, fabric: *std.Build.Module, sources: *std.Build.Module, engine: *std.Build.Module, qwen27: qwen27_build.Shared, living: *std.Build.Module } { const metal = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = target, @@ -553,14 +553,16 @@ fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = target, .optimize = optimize, .link_libc = true }); const fabric = b.createModule(.{ .root_source_file = b.path("zig/src/fabric/fabric.zig"), .target = target, .optimize = optimize, .link_libc = true }); const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); + // Living Weights' learner, pocket and fits, which Nemotron's lessons import + const living = b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .optimize = optimize, .link_libc = true }); const engine = b.createModule(.{ .root_source_file = b.path("zig/src/tensorfold.zig"), .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "nemotron_draft_ids", .module = draft_ids }, .{ .name = "lanes", .module = lanes }, .{ .name = "fabric", .module = fabric } }, + .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = sources }, .{ .name = "nemotron_draft_ids", .module = draft_ids }, .{ .name = "lanes", .module = lanes }, .{ .name = "fabric", .module = fabric }, .{ .name = "living", .module = living } }, }); - return .{ .metal = metal, .lanes = lanes, .fabric = fabric, .sources = sources, .engine = engine, .qwen27 = qwen27_build.engineModules(b, target, metal, sources, engine) }; + return .{ .metal = metal, .lanes = lanes, .fabric = fabric, .sources = sources, .engine = engine, .living = living, .qwen27 = qwen27_build.engineModules(b, target, metal, sources, engine) }; } pub fn distMetalServer(b: *std.Build, target: std.Build.ResolvedTarget, draft_ids: *std.Build.Module, build_options: *std.Build.Step.Options, sdk: []const u8) *std.Build.Step.Compile { diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index eac681628c..be4526406c 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -78,19 +78,22 @@ fn runtime(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builti return cuda; } -fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, draft_ids: *std.Build.Module) struct { core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, tokenizer: *std.Build.Module, heat: *std.Build.Module } { +fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, draft_ids: *std.Build.Module) struct { core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, tokenizer: *std.Build.Module, heat: *std.Build.Module, living: *std.Build.Module } { const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = optimize, .link_libc = true }); const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = target, .optimize = optimize, .link_libc = true }); core.addImport("tokenizer", tokenizer); const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = target, .optimize = optimize, .link_libc = true }); const heat = b.createModule(.{ .root_source_file = b.path("zig/src/core/heat.zig"), .target = target, .optimize = optimize, .link_libc = true }); + // Living Weights' learner, pocket and fits, which a family's lessons import + const living = b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .optimize = optimize, .link_libc = true }); const nemotron = b.createModule(.{ .root_source_file = b.path("zig/src/families/nemotron/cuda.zig"), .target = target, .optimize = optimize, .link_libc = true }); nemotron.addImport("cuda", cuda); nemotron.addImport("core", core); nemotron.addImport("lanes", lanes); nemotron.addImport("heat", heat); nemotron.addImport("nemotron_draft_ids", draft_ids); - return .{ .core = core, .lanes = lanes, .nemotron = nemotron, .tokenizer = tokenizer, .heat = heat }; + nemotron.addImport("living", living); + return .{ .core = core, .lanes = lanes, .nemotron = nemotron, .tokenizer = tokenizer, .heat = heat, .living = living }; } /// Linux targets: fatbins (-Dnvcc builds them, -Dfatbins embeds prebuilt ones), `tensorfold` and `tf-cuda-test`. @@ -211,6 +214,10 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st } // the tokenizer's own tests (memo, steps, regex, unicode) run here: no other test binary reaches them for ([_]*std.Build.Module{ cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.tokenizer, native, stagger(b, host, .debug) }) |m| step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); + // Living Weights' learner on the host, beside the family that imports it + const living_run = b.addRunArtifact(b.addTest(.{ .root_module = mods.living })); + step.dependOn(&living_run.step); + b.step("test-living", "Living Weights' learner, pocket and fits, on the host").dependOn(&living_run.step); const cli = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cuda_main.zig"), .target = host, .optimize = .debug, .link_libc = true }); cli.addImport("cuda", cuda); cli.addImport("core", mods.core); diff --git a/zig/src/families/nemotron/adapters.zig b/zig/src/families/nemotron/adapters.zig index 3350594214..7d2bac4403 100644 --- a/zig/src/families/nemotron/adapters.zig +++ b/zig/src/families/nemotron/adapters.zig @@ -5,14 +5,14 @@ const cfg = @import("config.zig"); const wts = @import("weights.zig"); const ops = @import("train_ops.zig"); const pl = @import("prefill_launch.zig"); -const subspace = @import("subspace.zig"); +const subspace = @import("living").subspace; const Buffer = mtl.Buffer; const At = pl.At; const opts = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; const shape = @import("learn_shape.zig"); -const route = @import("lesson_route.zig"); +const route = @import("living").lesson_route; pub const block = shape.block; pub const max_rank = shape.max_rank; diff --git a/zig/src/families/nemotron/backend.zig b/zig/src/families/nemotron/backend.zig index f52e5a4a6c..5f2b737a62 100644 --- a/zig/src/families/nemotron/backend.zig +++ b/zig/src/families/nemotron/backend.zig @@ -5,7 +5,7 @@ const lanes = @import("lanes"); const Fence = @import("../../core/fence.zig").Fence; const fwd = @import("forward.zig"); const st = @import("state.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const layers = @import("layers.zig"); const mtp = @import("mtp.zig"); const timing = @import("timing.zig"); diff --git a/zig/src/families/nemotron/cuda.zig b/zig/src/families/nemotron/cuda.zig index cb2fa934a1..c6495fa7fd 100644 --- a/zig/src/families/nemotron/cuda.zig +++ b/zig/src/families/nemotron/cuda.zig @@ -40,7 +40,5 @@ test { _ = @import("cuda_prompt_cuts.zig"); _ = @import("cuda_profile_window.zig"); _ = reuse; - _ = @import("learner.zig"); - _ = @import("subspace.zig"); _ = @import("cuda_train_back.zig"); } diff --git a/zig/src/families/nemotron/cuda_engine.zig b/zig/src/families/nemotron/cuda_engine.zig index f287c4ced4..7d0e6d4518 100644 --- a/zig/src/families/nemotron/cuda_engine.zig +++ b/zig/src/families/nemotron/cuda_engine.zig @@ -15,7 +15,7 @@ const head_fields = @import("cuda_mtp.zig").seq_fields; const sampler = @import("cuda_sampler.zig"); const segs = @import("cuda_segments.zig"); const train_ops = @import("cuda_train_ops.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const heat = @import("heat"); const seq_graphs = @import("cuda_seq_graphs.zig"); const prompt_rows = @import("cuda_prompt_rows.zig"); diff --git a/zig/src/families/nemotron/cuda_forward.zig b/zig/src/families/nemotron/cuda_forward.zig index a0e0452e86..848bec5856 100644 --- a/zig/src/families/nemotron/cuda_forward.zig +++ b/zig/src/families/nemotron/cuda_forward.zig @@ -9,7 +9,7 @@ const weights = @import("cuda_weights.zig"); const state = @import("cuda_state.zig"); const Dump = @import("cuda_dump.zig").Dump; const train_ops = @import("cuda_train_ops.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const kept = @import("cuda_marks.zig"); pub const Delta = enum { none, dense, moe }; diff --git a/zig/src/families/nemotron/cuda_lanes.zig b/zig/src/families/nemotron/cuda_lanes.zig index 203ccd74cb..3f98a86a5c 100644 --- a/zig/src/families/nemotron/cuda_lanes.zig +++ b/zig/src/families/nemotron/cuda_lanes.zig @@ -14,7 +14,7 @@ const prompt_rows = @import("cuda_prompt_rows.zig"); const config = @import("config.zig"); const seq_graphs = @import("cuda_seq_graphs.zig"); const costs = @import("cuda_costs.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const be = lanes.backend; const LogRow = lanes.LogprobRow; diff --git a/zig/src/families/nemotron/cuda_prompt.zig b/zig/src/families/nemotron/cuda_prompt.zig index ba5408db8d..64e07e3f87 100644 --- a/zig/src/families/nemotron/cuda_prompt.zig +++ b/zig/src/families/nemotron/cuda_prompt.zig @@ -14,7 +14,7 @@ const marks = @import("cuda_marks.zig"); const cuts = @import("cuda_prompt_cuts.zig"); const prompt_rows = @import("cuda_prompt_rows.zig"); const reuse = @import("cuda_reuse.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const heat = @import("heat"); const pin_sampled = engine.pin_sampled; const pin_prompt = engine.pin_prompt; diff --git a/zig/src/families/nemotron/cuda_sites.zig b/zig/src/families/nemotron/cuda_sites.zig index c44e37c527..930e5ef0f5 100644 --- a/zig/src/families/nemotron/cuda_sites.zig +++ b/zig/src/families/nemotron/cuda_sites.zig @@ -4,9 +4,9 @@ const cuda = @import("cuda"); const Config = @import("config.zig").Config; const weights = @import("cuda_weights.zig"); const train_ops = @import("cuda_train_ops.zig"); -const subspace = @import("subspace.zig"); +const subspace = @import("living").subspace; const shape = @import("learn_shape.zig"); -const route = @import("lesson_route.zig"); +const route = @import("living").lesson_route; pub const block = shape.block; pub const max_rank = shape.max_rank; diff --git a/zig/src/families/nemotron/cuda_slide.zig b/zig/src/families/nemotron/cuda_slide.zig index e65dd647b2..acc0452082 100644 --- a/zig/src/families/nemotron/cuda_slide.zig +++ b/zig/src/families/nemotron/cuda_slide.zig @@ -1,7 +1,7 @@ //! Nemotron's Sliding Weights learner on CUDA: learner.zig's lessons over the CUDA trainer, the engine and its shards. const std = @import("std"); const cuda = @import("cuda"); -const lessons = @import("learner.zig"); +const lessons = @import("living").learner; const train = @import("cuda_train.zig"); const engine = @import("cuda_engine.zig"); const sites_mod = @import("cuda_sites.zig"); diff --git a/zig/src/families/nemotron/cuda_state.zig b/zig/src/families/nemotron/cuda_state.zig index 92bac057b9..e6a7c7caab 100644 --- a/zig/src/families/nemotron/cuda_state.zig +++ b/zig/src/families/nemotron/cuda_state.zig @@ -1,7 +1,7 @@ //! Device buffers of one Nemotron sequence: its caches and recurrent state, and the scratch a window or chunk uses. const std = @import("std"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const cuda = @import("cuda"); const Config = @import("config.zig").Config; const kern = @import("cuda_kernels.zig"); diff --git a/zig/src/families/nemotron/cuda_train.zig b/zig/src/families/nemotron/cuda_train.zig index 771e472886..ab96e317d4 100644 --- a/zig/src/families/nemotron/cuda_train.zig +++ b/zig/src/families/nemotron/cuda_train.zig @@ -1,6 +1,6 @@ //! Learning in the weights on CUDA (train.zig on Metal): sequences side by side forward, their losses, and back. const std = @import("std"); -const train_mode = @import("train_mode.zig"); +const train_mode = @import("living").train_mode; const cuda = @import("cuda"); const core = @import("core"); const Config = @import("config.zig").Config; @@ -10,12 +10,12 @@ const fwd = @import("cuda_forward.zig"); const engine = @import("cuda_engine.zig"); const ops = @import("cuda_train_ops.zig"); const sites_mod = @import("cuda_sites.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const back = @import("cuda_train_back.zig"); const tfw = @import("cuda_train_fwd.zig"); const lay = @import("cuda_train_layout.zig"); const prefix = @import("cuda_train_prefix.zig"); -const Count = @import("pocket_clock.zig").Count; +const Count = @import("living").pocket_clock.Count; const Source = @import("cuda_source.zig").Source; /// Rows a sequence learns from at most: a question and its answer (attention's backward reads at most 256). diff --git a/zig/src/families/nemotron/cuda_train_fwd.zig b/zig/src/families/nemotron/cuda_train_fwd.zig index 3b39c30976..b099ae94e6 100644 --- a/zig/src/families/nemotron/cuda_train_fwd.zig +++ b/zig/src/families/nemotron/cuda_train_fwd.zig @@ -6,7 +6,7 @@ const state = @import("cuda_state.zig"); const weights = @import("cuda_weights.zig"); const fwd = @import("cuda_forward.zig"); const train_ops = @import("cuda_train_ops.zig"); -const Span = @import("train_mode.zig").Span; +const Span = @import("living").train_mode.Span; const Store = @import("cuda_train_prefix.zig").Store; /// The open fact's pocket neurons scaled row by row: `rows` f32 [rows] on the device, at layer l from `from[l]` on. diff --git a/zig/src/families/nemotron/cuda_train_ops.zig b/zig/src/families/nemotron/cuda_train_ops.zig index 209ad9de3b..b5b10bc39f 100644 --- a/zig/src/families/nemotron/cuda_train_ops.zig +++ b/zig/src/families/nemotron/cuda_train_ops.zig @@ -1,7 +1,7 @@ //! The training kernels (train.cu) as calls on one stream: the loss, the change, products and each layer's backward. const std = @import("std"); const cuda = @import("cuda"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; /// A Mamba layer's shape as the mixer kernels read it (train.cu's Shape). pub const Shape = extern struct { rows: c_int, heads: c_int, dh: c_int, groups: c_int, n: c_int, inner: c_int, conv: c_int, proj: c_int }; diff --git a/zig/src/families/nemotron/forward.zig b/zig/src/families/nemotron/forward.zig index 7dc93e2de2..9fa69def84 100644 --- a/zig/src/families/nemotron/forward.zig +++ b/zig/src/families/nemotron/forward.zig @@ -13,7 +13,7 @@ const fullVocabulary = @import("lanes").gpu_full.fullVocabulary; const gpu_rule = @import("lanes").gpu_rule; const row = @import("../../core/row_projection.zig"); const Masks = @import("../../core/grammar_mask.zig").Masks; -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const Buffer = mtl.Buffer; pub const Enc = encoder.Enc; diff --git a/zig/src/families/nemotron/layers.zig b/zig/src/families/nemotron/layers.zig index e2e18fb105..5dc16880d2 100644 --- a/zig/src/families/nemotron/layers.zig +++ b/zig/src/families/nemotron/layers.zig @@ -6,7 +6,7 @@ const st = @import("state.zig"); const fwd = @import("forward.zig"); const kern = @import("kernels.zig"); const tree = @import("tree.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const max_blocks = @import("learn_shape.zig").max_blocks; const Buffer = mtl.Buffer; diff --git a/zig/src/families/nemotron/learn_shape.zig b/zig/src/families/nemotron/learn_shape.zig index 6e4e3bf779..773c71f875 100644 --- a/zig/src/families/nemotron/learn_shape.zig +++ b/zig/src/families/nemotron/learn_shape.zig @@ -1,30 +1,19 @@ -//! The learned change's shape, shared by the Metal and CUDA learners: blocks of ranks, their scale and gates. +//! The learned change's shape on Nemotron: the shared constants (living/learn_shape.zig) and where its blocks sit. const std = @import("std"); const Config = @import("config.zig").Config; - -pub const block = 16; // ranks a lesson adds at each layer -pub const max_rank = 2048; // a hundred and twenty-eight lessons' blocks, each layer's buffers grown to it as lessons come -pub const max_blocks = max_rank / block; -pub const scale: f32 = 10; -pub const avoid_dims = 192; // directions sketched from the inputs a new block must leave alone -pub const candidates = 64; // directions sketched from the fact's inputs, which a new block's are chosen among - -/// Adam's settings for a block's outputs (its gate keeps them off what must stay): rate, moments' decays, epsilon. -pub const hyper = [4]f32{ 3e-4, 0.9, 0.999, 1e-8 }; - -/// Adam's settings at step `step`: the rate halves every `settle` steps, three times at most, so later rounds refine. -pub fn hyperAt(step: u64) [4]f32 { - var h = hyper; - h[0] /= @as(f32, @floatFromInt(@as(u32, 1) << @intCast(@min(step / settle, 3)))); - return h; -} -pub const settle = 60; - -/// Each new input direction's length, as MLX's LoRA draws its down factor's columns (uniform within 1 / sqrt(in)). -pub const a_norm: f32 = 0.577; - -/// A block's directions' squared length: a row's cosine with one is (x . a) / sqrt(unit |x|^2). -pub const unit = a_norm * a_norm; +const shape = @import("living").learn_shape; + +pub const block = shape.block; +pub const max_rank = shape.max_rank; +pub const max_blocks = shape.max_blocks; +pub const scale = shape.scale; +pub const avoid_dims = shape.avoid_dims; +pub const candidates = shape.candidates; +pub const hyper = shape.hyper; +pub const hyperAt = shape.hyperAt; +pub const settle = shape.settle; +pub const a_norm = shape.a_norm; +pub const unit = shape.unit; /// Layer i's output projection as the checkpoint names its module: the one a lesson's change sits after. pub fn moduleName(buf: []u8, c: Config, i: usize) ![]const u8 { diff --git a/zig/src/families/nemotron/nemotron.zig b/zig/src/families/nemotron/nemotron.zig index 5e26d6d4d1..0d521769f5 100644 --- a/zig/src/families/nemotron/nemotron.zig +++ b/zig/src/families/nemotron/nemotron.zig @@ -25,8 +25,8 @@ pub const learned = @import("learned.zig"); pub const train_ops = @import("train_ops.zig"); pub const train_back = @import("train_back.zig"); pub const train = @import("train.zig"); -pub const pocket_fit = @import("pocket_fit.zig"); -pub const lesson_route = @import("lesson_route.zig"); +pub const pocket_fit = @import("living").pocket_fit; +pub const lesson_route = @import("living").lesson_route; pub const snapshot = @import("snapshot.zig"); pub const learned_prompts = @import("learned_prompts.zig"); diff --git a/zig/src/families/nemotron/prefill.zig b/zig/src/families/nemotron/prefill.zig index 46c1070408..0bd134b925 100644 --- a/zig/src/families/nemotron/prefill.zig +++ b/zig/src/families/nemotron/prefill.zig @@ -9,7 +9,7 @@ const pk = @import("prefill_kernels.zig"); const pl = @import("prefill_launch.zig"); const mixers = @import("prefill_mixers.zig"); const layers = @import("layers.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const Model = @import("model.zig").Model; const Buffer = mtl.Buffer; diff --git a/zig/src/families/nemotron/slide.zig b/zig/src/families/nemotron/slide.zig index ac6bca25f4..d062d2f40a 100644 --- a/zig/src/families/nemotron/slide.zig +++ b/zig/src/families/nemotron/slide.zig @@ -1,6 +1,6 @@ //! Nemotron's Sliding Weights learner on Metal: learner.zig's lessons over the Metal trainer, its weights and shards. const std = @import("std"); -const lessons = @import("learner.zig"); +const lessons = @import("living").learner; const train = @import("train.zig"); const backend = @import("backend.zig"); const adapters = @import("adapters.zig"); diff --git a/zig/src/families/nemotron/state.zig b/zig/src/families/nemotron/state.zig index e45b2ca86c..eec5bab7a1 100644 --- a/zig/src/families/nemotron/state.zig +++ b/zig/src/families/nemotron/state.zig @@ -3,7 +3,7 @@ const std = @import("std"); const mtl = @import("metal"); const cfg = @import("config.zig"); const fwd = @import("forward.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const opts = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; diff --git a/zig/src/families/nemotron/train.zig b/zig/src/families/nemotron/train.zig index 7de08a1eb6..641dc36681 100644 --- a/zig/src/families/nemotron/train.zig +++ b/zig/src/families/nemotron/train.zig @@ -1,6 +1,6 @@ //! Learning in the weights: sequences side by side forward through every layer, their losses, back to each change. const std = @import("std"); -const train_mode = @import("train_mode.zig"); +const train_mode = @import("living").train_mode; const mtl = @import("metal"); const cfg = @import("config.zig"); const st = @import("state.zig"); @@ -11,9 +11,9 @@ const back = @import("train_back.zig"); const job = @import("train_job.zig"); const adapters = @import("adapters.zig"); const backend = @import("backend.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const prefix = @import("train_prefix.zig"); -const Count = @import("pocket_clock.zig").Count; +const Count = @import("living").pocket_clock.Count; const Metal = backend.Metal; const At = pl.At; diff --git a/zig/src/families/nemotron/train_back.zig b/zig/src/families/nemotron/train_back.zig index 8a37c70ddd..1dfa6c390f 100644 --- a/zig/src/families/nemotron/train_back.zig +++ b/zig/src/families/nemotron/train_back.zig @@ -7,7 +7,7 @@ const pre = @import("prefill.zig"); const pl = @import("prefill_launch.zig"); const ops = @import("train_ops.zig"); const adapters = @import("adapters.zig"); -const Span = @import("train_mode.zig").Span; +const Span = @import("living").train_mode.Span; const Store = @import("train_prefix.zig").Store; const Buffer = mtl.Buffer; diff --git a/zig/src/families/nemotron/train_forward.zig b/zig/src/families/nemotron/train_forward.zig index d3d2e1dbdb..a137ee06e1 100644 --- a/zig/src/families/nemotron/train_forward.zig +++ b/zig/src/families/nemotron/train_forward.zig @@ -5,7 +5,7 @@ const wts = @import("weights.zig"); const pre = @import("prefill.zig"); const pl = @import("prefill_launch.zig"); const layers = @import("layers.zig"); -const Span = @import("train_mode.zig").Span; +const Span = @import("living").train_mode.Span; const Store = @import("train_prefix.zig").Store; const At = pl.At; diff --git a/zig/src/families/nemotron/train_job.zig b/zig/src/families/nemotron/train_job.zig index c209c52d1f..6586ddcad8 100644 --- a/zig/src/families/nemotron/train_job.zig +++ b/zig/src/families/nemotron/train_job.zig @@ -1,6 +1,6 @@ //! A training pass as one command buffer: its sequences forward through every layer, their losses, back to each change. const std = @import("std"); -const train_mode = @import("train_mode.zig"); +const train_mode = @import("living").train_mode; const mtl = @import("metal"); const cfg = @import("config.zig"); const fwd = @import("forward.zig"); @@ -11,7 +11,7 @@ const back = @import("train_back.zig"); const tf = @import("train_forward.zig"); const adapters = @import("adapters.zig"); const backend = @import("backend.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const train = @import("train.zig"); const Trainer = train.Trainer; const pack_rows = train.pack_rows; diff --git a/zig/src/families/nemotron/train_ops.zig b/zig/src/families/nemotron/train_ops.zig index f690c07059..2a80871631 100644 --- a/zig/src/families/nemotron/train_ops.zig +++ b/zig/src/families/nemotron/train_ops.zig @@ -7,7 +7,7 @@ const wts = @import("weights.zig"); const pl = @import("prefill_launch.zig"); const pk = @import("prefill_kernels.zig"); const layers = @import("layers.zig"); -const lesson_route = @import("lesson_route.zig"); +const lesson_route = @import("living").lesson_route; const Buffer = mtl.Buffer; const At = pl.At; diff --git a/zig/src/families/nemotron/choice.zig b/zig/src/living/choice.zig similarity index 100% rename from zig/src/families/nemotron/choice.zig rename to zig/src/living/choice.zig diff --git a/zig/src/families/nemotron/editor.zig b/zig/src/living/editor.zig similarity index 100% rename from zig/src/families/nemotron/editor.zig rename to zig/src/living/editor.zig diff --git a/zig/src/living/learn_shape.zig b/zig/src/living/learn_shape.zig new file mode 100644 index 0000000000..1ea2572a76 --- /dev/null +++ b/zig/src/living/learn_shape.zig @@ -0,0 +1,25 @@ +//! The learned change's shape, shared by the Metal and CUDA learners: blocks of ranks, their scale and gates. + +pub const block = 16; // ranks a lesson adds at each layer +pub const max_rank = 2048; // a hundred and twenty-eight lessons' blocks, each layer's buffers grown to it as lessons come +pub const max_blocks = max_rank / block; +pub const scale: f32 = 10; +pub const avoid_dims = 192; // directions sketched from the inputs a new block must leave alone +pub const candidates = 64; // directions sketched from the fact's inputs, which a new block's are chosen among + +/// Adam's settings for a block's outputs (its gate keeps them off what must stay): rate, moments' decays, epsilon. +pub const hyper = [4]f32{ 3e-4, 0.9, 0.999, 1e-8 }; + +/// Adam's settings at step `step`: the rate halves every `settle` steps, three times at most, so later rounds refine. +pub fn hyperAt(step: u64) [4]f32 { + var h = hyper; + h[0] /= @as(f32, @floatFromInt(@as(u32, 1) << @intCast(@min(step / settle, 3)))); + return h; +} +pub const settle = 60; + +/// Each new input direction's length, as MLX's LoRA draws its down factor's columns (uniform within 1 / sqrt(in)). +pub const a_norm: f32 = 0.577; + +/// A block's directions' squared length: a row's cosine with one is (x . a) / sqrt(unit |x|^2). +pub const unit = a_norm * a_norm; diff --git a/zig/src/families/nemotron/learner.zig b/zig/src/living/learner.zig similarity index 100% rename from zig/src/families/nemotron/learner.zig rename to zig/src/living/learner.zig diff --git a/zig/src/families/nemotron/lesson_examples.zig b/zig/src/living/lesson_examples.zig similarity index 100% rename from zig/src/families/nemotron/lesson_examples.zig rename to zig/src/living/lesson_examples.zig diff --git a/zig/src/families/nemotron/lesson_route.zig b/zig/src/living/lesson_route.zig similarity index 100% rename from zig/src/families/nemotron/lesson_route.zig rename to zig/src/living/lesson_route.zig diff --git a/zig/src/living/living.zig b/zig/src/living/living.zig new file mode 100644 index 0000000000..9b9d1d1afe --- /dev/null +++ b/zig/src/living/living.zig @@ -0,0 +1,30 @@ +//! Living Weights: the lesson learner, its pocket of new neurons beside each shared expert, their fits and helpers. +pub const learner = @import("learner.zig"); +pub const whole = @import("whole.zig"); +pub const choice = @import("choice.zig"); +pub const editor = @import("editor.zig"); +pub const probe = @import("probe.zig"); +pub const router = @import("router.zig"); +pub const subspace = @import("subspace.zig"); +pub const train_mode = @import("train_mode.zig"); +pub const learn_shape = @import("learn_shape.zig"); +pub const lesson_examples = @import("lesson_examples.zig"); +pub const lesson_route = @import("lesson_route.zig"); +pub const pocket = @import("pocket.zig"); +pub const pocket_clock = @import("pocket_clock.zig"); +pub const pocket_dump = @import("pocket_dump.zig"); +pub const pocket_fit = @import("pocket_fit.zig"); +pub const pocket_joint = @import("pocket_joint.zig"); +pub const pocket_pack = @import("pocket_pack.zig"); +pub const pocket_prefix = @import("pocket_prefix.zig"); +pub const pocket_read = @import("pocket_read.zig"); +pub const pocket_values = @import("pocket_values.zig"); + +test { + _ = learner; + _ = subspace; + _ = pocket; + _ = pocket_fit; + _ = router; + _ = lesson_route; +} diff --git a/zig/src/families/nemotron/pocket.zig b/zig/src/living/pocket.zig similarity index 100% rename from zig/src/families/nemotron/pocket.zig rename to zig/src/living/pocket.zig diff --git a/zig/src/families/nemotron/pocket_clock.zig b/zig/src/living/pocket_clock.zig similarity index 100% rename from zig/src/families/nemotron/pocket_clock.zig rename to zig/src/living/pocket_clock.zig diff --git a/zig/src/families/nemotron/pocket_dump.zig b/zig/src/living/pocket_dump.zig similarity index 100% rename from zig/src/families/nemotron/pocket_dump.zig rename to zig/src/living/pocket_dump.zig diff --git a/zig/src/families/nemotron/pocket_fit.zig b/zig/src/living/pocket_fit.zig similarity index 100% rename from zig/src/families/nemotron/pocket_fit.zig rename to zig/src/living/pocket_fit.zig diff --git a/zig/src/families/nemotron/pocket_joint.zig b/zig/src/living/pocket_joint.zig similarity index 100% rename from zig/src/families/nemotron/pocket_joint.zig rename to zig/src/living/pocket_joint.zig diff --git a/zig/src/families/nemotron/pocket_pack.zig b/zig/src/living/pocket_pack.zig similarity index 100% rename from zig/src/families/nemotron/pocket_pack.zig rename to zig/src/living/pocket_pack.zig diff --git a/zig/src/families/nemotron/pocket_prefix.zig b/zig/src/living/pocket_prefix.zig similarity index 100% rename from zig/src/families/nemotron/pocket_prefix.zig rename to zig/src/living/pocket_prefix.zig diff --git a/zig/src/families/nemotron/pocket_read.zig b/zig/src/living/pocket_read.zig similarity index 100% rename from zig/src/families/nemotron/pocket_read.zig rename to zig/src/living/pocket_read.zig diff --git a/zig/src/families/nemotron/pocket_values.zig b/zig/src/living/pocket_values.zig similarity index 100% rename from zig/src/families/nemotron/pocket_values.zig rename to zig/src/living/pocket_values.zig diff --git a/zig/src/families/nemotron/probe.zig b/zig/src/living/probe.zig similarity index 100% rename from zig/src/families/nemotron/probe.zig rename to zig/src/living/probe.zig diff --git a/zig/src/families/nemotron/router.zig b/zig/src/living/router.zig similarity index 100% rename from zig/src/families/nemotron/router.zig rename to zig/src/living/router.zig diff --git a/zig/src/families/nemotron/subspace.zig b/zig/src/living/subspace.zig similarity index 100% rename from zig/src/families/nemotron/subspace.zig rename to zig/src/living/subspace.zig diff --git a/zig/src/families/nemotron/train_mode.zig b/zig/src/living/train_mode.zig similarity index 100% rename from zig/src/families/nemotron/train_mode.zig rename to zig/src/living/train_mode.zig diff --git a/zig/src/families/nemotron/whole.zig b/zig/src/living/whole.zig similarity index 100% rename from zig/src/families/nemotron/whole.zig rename to zig/src/living/whole.zig diff --git a/zig/src/tensorfold.zig b/zig/src/tensorfold.zig index 8a85dfccc1..7a6befdab1 100644 --- a/zig/src/tensorfold.zig +++ b/zig/src/tensorfold.zig @@ -40,14 +40,8 @@ test { _ = @import("families/nemotron/simd_attention.zig"); // The pre-M5 attention rewrite finds its lines. _ = @import("families/nemotron/weights.zig"); _ = @import("families/nemotron/kernels.zig"); - _ = @import("families/nemotron/subspace.zig"); // a new block's directions _ = @import("families/nemotron/living_test.zig"); // saved lessons and their routers, beside the shards _ = @import("families/nemotron/pocket_shards_test.zig"); // learned neurons in the shards themselves - _ = @import("families/nemotron/pocket.zig"); // which row a fact's neurons fire at - _ = @import("families/nemotron/pocket_fit.zig"); // where a fact's neurons fire, and stay silent - _ = @import("families/nemotron/router.zig"); // when a lesson acts on a reply - _ = @import("families/nemotron/lesson_route.zig"); - _ = @import("families/nemotron/learner.zig"); _ = @import("families/flashnext/tp_settings.zig"); // speed-up settings read without a typed JSON parse _ = @import("families/flashnext/follow.zig"); // rank 1's reply hash _ = @import("families/flashnext/dense.zig"); // The core projection adapter keeps format, cuts and tiles. From 75978a1c5c05d9c2aff212a0e2a7d2fd3938145a Mon Sep 17 00:00:00 2001 From: ZackSample <134018356+ZackSample@users.noreply.github.com> Date: Thu, 15 Oct 2026 03:03:27 -0500 Subject: [PATCH 14/17] Living Weights learns into any family described as data: the family's layout, neuron kind and shard format A family now describes itself once, as data (living/families.zig): where its shared experts sit and their tensor names, the neuron's activation (relu^2, or SwiGLU with an optional per-row gate), the quantization, the config keys and the object they live in, and its MTP head's expert. Its host gives the learner a layout and the pocket hooks (living/family.zig). Nemotron is the one family listed, and its lessons, routed blocks, edits and probes are unchanged. - The pocket reads its layers and width from the family's layout, not from Nemotron's config, and the learner offers routed blocks, edits and probes only to a trainer with `sites` (Nemotron's). - living/shards.zig widens any family's experts at its group and width; Nemotron's writer is now a wrapper over it. shard_edit sets and reads nested config keys (text_config). - A SwiGLU neuron fitted as u is written as gate row 16u and up row u/16: relu(u x)^2 on its fact's rows, at most 8e-5 of it at a 0.5 margin; a gated family's outputs fit gate * act(x). No listed family uses it yet; the tests use a stand-in family shaped as Qwen3.8 Flash Next's shared expert. - The server's view reads layers, pockets and shards through the family its config's model_type names, and native/nemotron_slide.zig is native/slide_adapter.zig. - pocket.zig's quiet refit and its loading move to pocket_quiet.zig and pocket_load.zig, for the 600-line rule. - Tests: the generic writer equals affine4_host at 4 bits in groups of 64, Nemotron's save test over the wrapper, a SwiGLU neuron fitted and stored at 4 bits in groups of 32, and a whole pocket lesson over a stand-in host for each activation (test-living, also under test-cuda-host). --- build.zig | 14 +- zig/build/cuda.zig | 21 +- zig/src/core/shard_edit.zig | 47 +++- zig/src/families/nemotron/cuda.zig | 1 + zig/src/families/nemotron/cuda_slide.zig | 7 + zig/src/families/nemotron/pocket_layout.zig | 12 + zig/src/families/nemotron/pocket_shards.zig | 174 +------------- zig/src/families/nemotron/slide.zig | 7 + zig/src/living/affine.zig | 86 +++++++ zig/src/living/families.zig | 79 +++++++ zig/src/living/family.zig | 135 +++++++++++ zig/src/living/host_test.zig | 215 ++++++++++++++++++ zig/src/living/learner.zig | 50 ++-- zig/src/living/living.zig | 22 +- zig/src/living/neuron.zig | 55 +++++ zig/src/living/pocket.zig | 159 +++++++------ zig/src/living/pocket_fit.zig | 18 +- zig/src/living/pocket_load.zig | 30 +++ zig/src/living/pocket_prefix.zig | 2 +- zig/src/living/pocket_quiet.zig | 59 +++++ zig/src/living/pocket_read.zig | 1 + zig/src/living/pocket_values.zig | 22 +- zig/src/living/probe.zig | 2 +- zig/src/living/shards.zig | 211 +++++++++++++++++ zig/src/living/swiglu_test.zig | 82 +++++++ zig/src/living/test_families.zig | 18 ++ zig/src/living/whole.zig | 18 ++ zig/src/living_shards_test.zig | 32 +++ zig/src/native/cuda.zig | 8 +- zig/src/native/metal.zig | 6 +- .../{nemotron_slide.zig => slide_adapter.zig} | 6 +- zig/src/server/slide_model.zig | 61 ++--- 32 files changed, 1303 insertions(+), 357 deletions(-) create mode 100644 zig/src/families/nemotron/pocket_layout.zig create mode 100644 zig/src/living/affine.zig create mode 100644 zig/src/living/families.zig create mode 100644 zig/src/living/family.zig create mode 100644 zig/src/living/host_test.zig create mode 100644 zig/src/living/neuron.zig create mode 100644 zig/src/living/pocket_load.zig create mode 100644 zig/src/living/pocket_quiet.zig create mode 100644 zig/src/living/shards.zig create mode 100644 zig/src/living/swiglu_test.zig create mode 100644 zig/src/living/test_families.zig create mode 100644 zig/src/living_shards_test.zig rename zig/src/native/{nemotron_slide.zig => slide_adapter.zig} (90%) diff --git a/build.zig b/build.zig index 5e7677cba7..31ce3658bb 100644 --- a/build.zig +++ b/build.zig @@ -192,7 +192,7 @@ pub fn build(b: *std.Build) void { } /// `zig build native -Dcpu=apple_m1`: tensorfold-native with the Metal engines for the Python package's bundle (a native M5 build traps on M1-M4). -fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, engine: *std.Build.Module, api: *std.Build.Module, engines: *std.Build.Module, build_options: *std.Build.Step.Options, test_step: ?*std.Build.Step) *std.Build.Step.Compile { +fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal: *std.Build.Module, engine: *std.Build.Module, living: *std.Build.Module, api: *std.Build.Module, engines: *std.Build.Module, build_options: *std.Build.Step.Options, test_step: ?*std.Build.Step) *std.Build.Step.Compile { // the HTTP side keeps its safety checks; the engine below it runs at `optimize` const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); @@ -201,7 +201,7 @@ fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b .target = target, .optimize = .ReleaseSafe, .link_libc = true, - .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = engines }, .{ .name = "checkpoint_cli", .module = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, engine) } }) } }, + .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = engines }, .{ .name = "living", .module = living }, .{ .name = "checkpoint_cli", .module = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, engine) } }) } }, }) }); exe.root_module.addOptions("build_options", build_options); if (test_step == null) { @@ -219,7 +219,7 @@ fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b .target = target, .optimize = .Debug, // the server's unit tests run with safety checks, as zig_test.sh builds them .link_libc = true, - .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template } }, + .imports = &.{ .{ .name = "engine_api", .module = api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "living", .module = living } }, }); test_step.?.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = server_tests })).step); @import("zig/build/cortheon_fuzz.zig").add(b, target, api, tokenizer, template); @@ -466,7 +466,7 @@ fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b glm_checks.targets(b, target, optimize, metal, engine, sources); flashnext_checks.targets(b, target, optimize, metal, engine); - _ = nativeServer(b, target, optimize, metal, engine, api, engines, build_options, test_step); + _ = nativeServer(b, target, optimize, metal, engine, mods.living, api, engines, build_options, test_step); const cluster_metal = b.createModule(.{ .root_source_file = b.path("zig/src/cluster/metal_sink.zig"), @@ -539,7 +539,7 @@ fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b } /// The server and distribution use the same embedded-source Metal engine. -fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, draft_ids: *std.Build.Module) struct { metal: *std.Build.Module, lanes: *std.Build.Module, fabric: *std.Build.Module, sources: *std.Build.Module, engine: *std.Build.Module, qwen27: qwen27_build.Shared, living: *std.Build.Module } { +fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, draft_ids: *std.Build.Module) struct { metal: *std.Build.Module, lanes: *std.Build.Module, fabric: *std.Build.Module, sources: *std.Build.Module, engine: *std.Build.Module, living: *std.Build.Module, qwen27: qwen27_build.Shared } { const metal = b.createModule(.{ .root_source_file = b.path("zig/src/metal/metal.zig"), .target = target, @@ -553,7 +553,7 @@ fn metalEngineModules(b: *std.Build, target: std.Build.ResolvedTarget, optimize: const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = target, .optimize = optimize, .link_libc = true }); const fabric = b.createModule(.{ .root_source_file = b.path("zig/src/fabric/fabric.zig"), .target = target, .optimize = optimize, .link_libc = true }); const sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/sources.zig") }); - // Living Weights' learner, pocket and fits, which Nemotron's lessons import + // Living Weights' family-neutral learner, which Nemotron's lessons and the server's view of them share const living = b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .optimize = optimize, .link_libc = true }); const engine = b.createModule(.{ .root_source_file = b.path("zig/src/tensorfold.zig"), @@ -576,7 +576,7 @@ pub fn distMetalServer(b: *std.Build, target: std.Build.ResolvedTarget, draft_id m.metal.addSystemIncludePath(b.graph.cwdRelativePath(b.pathJoin(&.{ sdk, "usr/include" }))); const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = .fast, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = m.lanes }} }); const engines = b.createModule(.{ .root_source_file = b.path("zig/src/native/metal.zig"), .target = target, .optimize = .fast, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = m.metal }, .{ .name = "engine_api", .module = api }, .{ .name = "tensorfold", .module = m.engine } } }); - return nativeServer(b, target, .fast, m.metal, m.engine, api, engines, build_options, null); + return nativeServer(b, target, .fast, m.metal, m.engine, m.living, api, engines, build_options, null); } test { diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index be4526406c..d36ee9c52b 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -84,7 +84,7 @@ fn family(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin core.addImport("tokenizer", tokenizer); const lanes = b.createModule(.{ .root_source_file = b.path("zig/src/core/lanes/lanes.zig"), .target = target, .optimize = optimize, .link_libc = true }); const heat = b.createModule(.{ .root_source_file = b.path("zig/src/core/heat.zig"), .target = target, .optimize = optimize, .link_libc = true }); - // Living Weights' learner, pocket and fits, which a family's lessons import + // Living Weights' family-neutral learner: a family's lessons, and the server's view of them, import it const living = b.createModule(.{ .root_source_file = b.path("zig/src/living/living.zig"), .target = target, .optimize = optimize, .link_libc = true }); const nemotron = b.createModule(.{ .root_source_file = b.path("zig/src/families/nemotron/cuda.zig"), .target = target, .optimize = optimize, .link_libc = true }); nemotron.addImport("cuda", cuda); @@ -142,7 +142,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu runner.addImport("exlr8_frozen_dense", b.createModule(.{ .root_source_file = b.path("zig/tests/fixtures/exlr8/frozen_dense.zig"), .target = target, .optimize = optimize })); for (exlr8_build.denseModules(b, target, optimize, exlr8, exlr8_tests[0])) |m| runner.addImport(m.name, m.module); b.installArtifact(b.addExecutable(.{ .name = "tf-cuda-test", .root_module = runner })); - nativeServer(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.tokenizer, build_options, true).root_module.strip = strip; + nativeServer(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.tokenizer, mods.living, build_options, true).root_module.strip = strip; } /// The CUDA engines a native server opens (native/cuda.zig), over the given runtime and families. @@ -164,7 +164,7 @@ fn checkpointCli(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std. } /// `zig build native`: tensorfold-native with the CUDA engines into zig-out/native/bin, as the Metal build makes it. -fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, tokenizer: *std.Build.Module, build_options: *std.Build.Step.Options, install_native: bool) *std.Build.Step.Compile { +fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, lanes: *std.Build.Module, nemotron: *std.Build.Module, tokenizer: *std.Build.Module, living: *std.Build.Module, build_options: *std.Build.Step.Options, install_native: bool) *std.Build.Step.Compile { const m = engines(b, target, optimize, cuda, lanes, nemotron); // the HTTP side keeps its safety checks; the engine below it runs at `optimize` (the tokenizer is the family's) const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); @@ -173,7 +173,7 @@ fn nativeServer(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.b .target = target, .optimize = .ReleaseSafe, .link_libc = true, - .imports = &.{ .{ .name = "engine_api", .module = m.api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = m.engines }, .{ .name = "checkpoint_cli", .module = checkpointCli(b, target, .ReleaseSafe, null, m.engines, core) } }, + .imports = &.{ .{ .name = "engine_api", .module = m.api }, .{ .name = "tokenizer", .module = tokenizer }, .{ .name = "template", .module = template }, .{ .name = "native_engines", .module = m.engines }, .{ .name = "living", .module = living }, .{ .name = "checkpoint_cli", .module = checkpointCli(b, target, .ReleaseSafe, null, m.engines, core) } }, }) }); exe.root_module.addOptions("build_options", build_options); if (!install_native) { @@ -202,7 +202,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st .target = host, .optimize = .debug, .link_libc = true, - .imports = &.{ .{ .name = "engine_api", .module = native_modules.api }, .{ .name = "tokenizer", .module = mods.tokenizer }, .{ .name = "template", .module = template } }, + .imports = &.{ .{ .name = "engine_api", .module = native_modules.api }, .{ .name = "tokenizer", .module = mods.tokenizer }, .{ .name = "template", .module = template }, .{ .name = "living", .module = mods.living } }, }); const server_test = b.addRunArtifact(b.addTest(.{ .root_module = server_tests })); step.dependOn(&server_test.step); @@ -214,10 +214,15 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st } // the tokenizer's own tests (memo, steps, regex, unicode) run here: no other test binary reaches them for ([_]*std.Build.Module{ cuda, mods.core, mods.lanes, mods.nemotron, mods.heat, mods.tokenizer, native, stagger(b, host, .debug) }) |m| step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = m })).step); - // Living Weights' learner on the host, beside the family that imports it + // Living Weights: the family-neutral learner, then the pocket in each family's shards over the core's shard files const living_run = b.addRunArtifact(b.addTest(.{ .root_module = mods.living })); + const shards = b.createModule(.{ .root_source_file = b.path("zig/src/living_shards_test.zig"), .target = host, .optimize = .debug, .link_libc = true, .imports = &.{.{ .name = "living", .module = mods.living }} }); + const shards_run = b.addRunArtifact(b.addTest(.{ .root_module = shards })); step.dependOn(&living_run.step); - b.step("test-living", "Living Weights' learner, pocket and fits, on the host").dependOn(&living_run.step); + step.dependOn(&shards_run.step); + const living_step = b.step("test-living", "Living Weights' learner and the pocket in each family's shards, on the host"); + living_step.dependOn(&living_run.step); + living_step.dependOn(&shards_run.step); const cli = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cuda_main.zig"), .target = host, .optimize = .debug, .link_libc = true }); cli.addImport("cuda", cuda); cli.addImport("core", mods.core); @@ -253,7 +258,7 @@ pub fn distServer(b: *std.Build, target: std.Build.ResolvedTarget, draft_ids: *s }; const cuda = runtime(b, target, .fast, if (prebuilt != null) &images else &.{}); const mods = family(b, target, .fast, cuda, draft_ids); - return nativeServer(b, target, .fast, cuda, mods.core, mods.lanes, mods.nemotron, mods.tokenizer, build_options, false); + return nativeServer(b, target, .fast, cuda, mods.core, mods.lanes, mods.nemotron, mods.tokenizer, mods.living, build_options, false); } /// SASS targets every release fatbin holds: Ampere (sm_86), RTX 50 and RTX PRO Blackwell (sm_120), GB10 (sm_121). diff --git a/zig/src/core/shard_edit.zig b/zig/src/core/shard_edit.zig index b340a40523..c8b33b11d4 100644 --- a/zig/src/core/shard_edit.zig +++ b/zig/src/core/shard_edit.zig @@ -114,24 +114,44 @@ pub fn grow(gpa: Allocator, io: Io, dir: []const u8, edits: []const Replacement) /// config.json in `dir` with each of `ints` set (added where missing), every other key as it was. pub fn setConfig(gpa: Allocator, io: Io, dir: []const u8, ints: []const struct { []const u8, i64 }) !void { + return setConfigIn(gpa, io, dir, null, ints); +} + +/// config.json in `dir` with each of `ints` set inside the object `scope` names (null: the top level), as setConfig. +pub fn setConfigIn(gpa: Allocator, io: Io, dir: []const u8, scope: ?[]const u8, ints: []const struct { []const u8, i64 }) !void { var arena_state = std.heap.ArenaAllocator.init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); const path = try std.fs.path.join(arena, &.{ dir, "config.json" }); var config = try readJson(arena, io, path); if (config != .object) return error.BadConfig; - for (ints) |kv| try config.object.put(arena, kv[0], .{ .integer = kv[1] }); + const o = if (scope) |name| blk: { + const inner = config.object.getPtr(name) orelse return error.BadConfig; + if (inner.* != .object) return error.BadConfig; + break :blk &inner.object; + } else &config.object; + for (ints) |kv| try o.put(arena, kv[0], .{ .integer = kv[1] }); try writeJson(arena, path, config); } /// An integer of `dir`'s config.json, or null when it has none. pub fn configInt(gpa: Allocator, io: Io, dir: []const u8, key: []const u8) !?i64 { + return configIntIn(gpa, io, dir, null, key); +} + +/// An integer of the object `scope` names in `dir`'s config.json (null: the top level), or null when it has none. +pub fn configIntIn(gpa: Allocator, io: Io, dir: []const u8, scope: ?[]const u8, key: []const u8) !?i64 { var arena_state = std.heap.ArenaAllocator.init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); const config = try readJson(arena, io, try std.fs.path.join(arena, &.{ dir, "config.json" })); if (config != .object) return error.BadConfig; - const v = config.object.get(key) orelse return null; + const o = if (scope) |name| blk: { + const inner = config.object.get(name) orelse return error.BadConfig; + if (inner != .object) return error.BadConfig; + break :blk inner.object; + } else config.object; + const v = o.get(key) orelse return null; return if (v == .integer) v.integer else error.BadConfig; } @@ -508,6 +528,29 @@ test "a tensor grown in its shard: the shard is rewritten, the index's total mov try std.testing.expectEqualStrings("x", (try field(config, "model_type")).string); } +test "integers set and read inside a nested config object, the top level and every other key as they were" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = "{\"model_type\":\"x\",\"width\":7,\"text_config\":{\"width\":2,\"name\":\"t\"}}" }); + const dir = try std.fs.path.join(gpa, &.{ ".zig-cache", "tmp", &tmp.sub_path }); + defer gpa.free(dir); + try std.testing.expectEqual(@as(?i64, 2), try configIntIn(gpa, io, dir, "text_config", "width")); + try std.testing.expectEqual(@as(?i64, null), try configIntIn(gpa, io, dir, "text_config", "learned")); + try setConfigIn(gpa, io, dir, "text_config", &.{ .{ "width", 3 }, .{ "learned", 1 } }); + try std.testing.expectEqual(@as(?i64, 3), try configIntIn(gpa, io, dir, "text_config", "width")); + try std.testing.expectEqual(@as(?i64, 1), try configIntIn(gpa, io, dir, "text_config", "learned")); + try std.testing.expectEqual(@as(?i64, 7), try configInt(gpa, io, dir, "width")); + try std.testing.expectEqual(@as(?i64, null), try configInt(gpa, io, dir, "learned")); + try std.testing.expectError(error.BadConfig, configIntIn(gpa, io, dir, "vision_config", "width")); + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const config = try readJson(arena, io, try std.fs.path.join(arena, &.{ dir, "config.json" })); + try std.testing.expectEqualStrings("t", (try field(try field(config, "text_config"), "name")).string); +} + test "a folder whose shard is a symlink or a hard link is refused for learning; its own files pass" { const gpa = std.testing.allocator; const io = std.testing.io; diff --git a/zig/src/families/nemotron/cuda.zig b/zig/src/families/nemotron/cuda.zig index c6495fa7fd..58e979c6e5 100644 --- a/zig/src/families/nemotron/cuda.zig +++ b/zig/src/families/nemotron/cuda.zig @@ -40,5 +40,6 @@ test { _ = @import("cuda_prompt_cuts.zig"); _ = @import("cuda_profile_window.zig"); _ = reuse; + _ = slide; _ = @import("cuda_train_back.zig"); } diff --git a/zig/src/families/nemotron/cuda_slide.zig b/zig/src/families/nemotron/cuda_slide.zig index acc0452082..9c67cf53a0 100644 --- a/zig/src/families/nemotron/cuda_slide.zig +++ b/zig/src/families/nemotron/cuda_slide.zig @@ -10,6 +10,7 @@ const state = @import("cuda_state.zig"); const Living = living.Io(@import("core")); const PocketShards = @import("pocket_shards.zig").Io(@import("core")); +const pocket_layout = @import("pocket_layout.zig"); pub const Example = lessons.Example; pub const Lesson = lessons.Lesson; @@ -27,11 +28,17 @@ const Host = struct { pub const Trainer = train.Trainer; pub const max_rows = train.max_rows; pub const Ctx = Model; + pub const family = pocket_layout.family; pub fn layers(m: Ctx) usize { return m.e.c.layers; } + /// Where the pocket sits and learns: every MoE layer, all but the last learning. + pub fn layout(m: Ctx) @import("living").Layout { + return pocket_layout.layout(m.e.c); + } + pub fn trainer(gpa: std.mem.Allocator, io: std.Io, m: Ctx) !*Trainer { return train.Trainer.init(gpa, io, m.e, m.dir, m.living); } diff --git a/zig/src/families/nemotron/pocket_layout.zig b/zig/src/families/nemotron/pocket_layout.zig new file mode 100644 index 0000000000..879ddb28d1 --- /dev/null +++ b/zig/src/families/nemotron/pocket_layout.zig @@ -0,0 +1,12 @@ +//! Nemotron as Living Weights reads it: its family (living/families.zig) and the layout its config gives. +const living = @import("living"); +const Config = @import("config.zig").Config; + +pub const family = living.families.nemotron_h; + +/// Every MoE layer's shared expert carries the pocket; all but the last layer's learn. +pub fn layout(c: Config) living.Layout { + var moe: living.Layers = .empty; + for (0..c.layers) |l| if (c.kinds[l] == .moe) moe.set(l); + return .fromExperts(c.hidden, c.shared_width, c.layers, moe); +} diff --git a/zig/src/families/nemotron/pocket_shards.zig b/zig/src/families/nemotron/pocket_shards.zig index 8eaca2c3b5..5cdab00612 100644 --- a/zig/src/families/nemotron/pocket_shards.zig +++ b/zig/src/families/nemotron/pocket_shards.zig @@ -1,178 +1,16 @@ -//! The pocket in the shards: every shared expert widened once (config.json told), later writes in place. +//! The pocket in Nemotron's shards: living/shards.zig over its family and config (up_proj rows, down_proj columns). const std = @import("std"); const cfg = @import("config.zig"); +const living = @import("living"); +const pocket_layout = @import("pocket_layout.zig"); -const group = 64; - -/// The writer over `core`, the backend's own (its shard_edit, safetensors and affine4_host). +/// The writer over `core`, the backend's own (its shard_edit and safetensors). pub fn Io(comptime core: type) type { - const st = core.safetensors; - const se = core.shard_edit; - const host4 = core.affine4_host; + const Shards = living.shards.Io(core); return struct { /// The learned neurons of MoE layers `layers` into `dir`'s shards (widened first if new), as 4-bit; the bytes. pub fn write(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, c: cfg.Config, layers: []const usize, neurons: usize, up: []f32, down: []f32) !usize { - const d = c.hidden; - const own = c.shared_width; - if (neurons % group != 0 or d % group != 0 or own % group != 0) return error.BadPocket; - const has = try se.configInt(gpa, io, dir, cfg.pocket_key); - const widen = has == null; - if (has) |n| if (n != neurons) return error.PocketOfAnotherSize; - var arena_state = std.heap.ArenaAllocator.init(gpa); - defer arena_state.deinit(); - const arena = arena_state.allocator(); - var files: Files = .{ .gpa = gpa, .io = io, .dir = dir, .paths = .init(gpa) }; - defer files.close(); - var edits: std.ArrayList(se.Replacement) = .empty; - var bytes: usize = 0; - for (0..c.layers) |l| { - if (c.kinds[l] != .moe) continue; - const at = std.mem.indexOfScalar(usize, layers, l); - const n = neurons * d; - const u = if (at) |j| up[j * n ..][0..n] else try zeros(arena, n); - const v = if (at) |j| down[j * n ..][0..n] else try zeros(arena, n); - var buf: [96]u8 = undefined; - const base = try std.fmt.bufPrint(&buf, "backbone.layers.{d}.mixer.shared_experts.", .{l}); - bytes += try expert(arena, &files, &edits, base, own, neurons, d, u, v); - } - if (widen) try se.grow(gpa, io, dir, edits.items) else try se.overwrite(gpa, io, dir, edits.items); - if (widen) { - const mtp = try std.fs.path.join(arena, &.{ dir, "mtp-4bit.safetensors" }); - if (hasMtp(gpa, io, mtp)) { - var only: std.ArrayList(se.Replacement) = .empty; - var none: Files = .{ .gpa = gpa, .io = io, .dir = dir, .single = mtp, .paths = .init(gpa) }; - defer none.close(); - const z = try zeros(arena, neurons * d); - bytes += try expert(arena, &none, &only, "layers.1.mixer.shared_experts.", own, neurons, d, z, z); - _ = try se.rewrite(gpa, io, mtp, only.items); - } - try se.setConfig(gpa, io, dir, &.{ .{ "moe_shared_expert_intermediate_size", @intCast(own + neurons) }, .{ cfg.pocket_key, @intCast(neurons) } }); - } - return bytes; - } - - fn hasMtp(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool { - var f = st.File.open(gpa, io, path) catch return false; - defer f.close(io); - return f.get("layers.1.mixer.shared_experts.up_proj.weight") != null; - } - - /// The shard files a model's tensors are read from: the index's, or one file (the MTP head's). - const Files = struct { - gpa: std.mem.Allocator, - io: std.Io, - dir: []const u8, - single: ?[]const u8 = null, - open: std.StringArrayHashMapUnmanaged(st.File) = .empty, - paths: std.heap.ArenaAllocator, - map: ?std.json.Parsed(std.json.Value) = null, - - fn get(fs: *Files, name: []const u8) !st.Tensor { - const shard = if (fs.single) |x| x else try fs.shardOf(name); - const slot = try fs.open.getOrPut(fs.gpa, shard); - if (!slot.found_existing) slot.value_ptr.* = st.File.open(fs.gpa, fs.io, shard) catch |e| { - _ = fs.open.pop(); - return e; - }; - return slot.value_ptr.get(name) orelse error.MissingTensor; - } - - /// The path of the shard holding `name`, kept until the files close. - fn shardOf(fs: *Files, name: []const u8) ![]const u8 { - const a = fs.paths.allocator(); - if (fs.map == null) { - const path = try std.fs.path.join(a, &.{ fs.dir, "model.safetensors.index.json" }); - const text = std.Io.Dir.cwd().readFileAlloc(fs.io, path, a, .limited(1 << 26)) catch |e| if (e == error.FileNotFound) { - fs.single = try std.fs.path.join(a, &.{ fs.dir, "model.safetensors" }); - return fs.single.?; - } else return e; - fs.map = try std.json.parseFromSlice(std.json.Value, fs.gpa, text, .{ .allocate = .alloc_always }); - } - const root = fs.map.?.value; - if (root != .object) return error.BadIndex; - const weights = root.object.get("weight_map") orelse return error.BadIndex; - if (weights != .object) return error.BadIndex; - const file = weights.object.get(name) orelse return error.MissingTensor; - if (file != .string) return error.BadIndex; - return std.fs.path.join(a, &.{ fs.dir, file.string }); - } - - fn close(fs: *Files) void { - for (fs.open.values()) |*f| f.close(fs.io); - fs.open.deinit(fs.gpa); - if (fs.map) |*x| x.deinit(); - fs.paths.deinit(); - } - }; - - /// One shared expert's up_proj and down_proj with `neurons` learned after its `own`, into `edits`; the bytes. - fn expert(arena: std.mem.Allocator, files: *Files, edits: *std.ArrayList(se.Replacement), base: []const u8, own: usize, neurons: usize, d: usize, u: []f32, v: []f32) !usize { - const wide = own + neurons; - var name: [128]u8 = undefined; - var parts: [6]st.Tensor = undefined; - const leaves = [_][]const u8{ "up_proj.weight", "up_proj.scales", "up_proj.biases", "down_proj.weight", "down_proj.scales", "down_proj.biases" }; - for (&parts, leaves) |*t, leaf| t.* = try files.get(try std.fmt.bufPrint(&name, "{s}{s}", .{ base, leaf })); - const rows_had = parts[0].dim(0); // up_proj's rows: `own`, or `wide` once widened - if (rows_had != own and rows_had != wide) return error.UnexpectedTensor; - // up_proj: the own rows as they are, then a row a learned neuron - const uw = try arena.alloc(u32, wide * d / 8); - const us = try arena.alloc(u16, wide * d / group); - const ub = try arena.alloc(u16, wide * d / group); - @memcpy(uw[0 .. own * d / 8], words(parts[0].bytes)[0 .. own * d / 8]); - @memcpy(us[0 .. own * d / group], halves(parts[1].bytes)[0 .. own * d / group]); - @memcpy(ub[0 .. own * d / group], halves(parts[2].bytes)[0 .. own * d / group]); - for (0..neurons) |k| { - const r = own + k; - const x = u[k * d ..][0..d]; - host4.quantize(x, uw[r * d / 8 ..][0 .. d / 8], us[r * d / group ..][0 .. d / group], ub[r * d / group ..][0 .. d / group]); - host4.dequantize(uw[r * d / 8 ..][0 .. d / 8], us[r * d / group ..][0 .. d / group], ub[r * d / group ..][0 .. d / group], x); - } - // down_proj: each output row's own columns as they are, then a column a learned neuron - const had = rows_had; // down_proj's columns, as wide as up_proj had rows - const dw = try arena.alloc(u32, d * wide / 8); - const ds = try arena.alloc(u16, d * wide / group); - const db = try arena.alloc(u16, d * wide / group); - const col = try arena.alloc(f32, neurons); - for (0..d) |o| { - @memcpy(dw[o * wide / 8 ..][0 .. own / 8], words(parts[3].bytes)[o * had / 8 ..][0 .. own / 8]); - @memcpy(ds[o * wide / group ..][0 .. own / group], halves(parts[4].bytes)[o * had / group ..][0 .. own / group]); - @memcpy(db[o * wide / group ..][0 .. own / group], halves(parts[5].bytes)[o * had / group ..][0 .. own / group]); - for (col, 0..) |*x, k| x.* = v[k * d + o]; - const w8 = dw[o * wide / 8 ..][own / 8 ..][0 .. neurons / 8]; - const s8 = ds[o * wide / group ..][own / group ..][0 .. neurons / group]; - const b8 = db[o * wide / group ..][own / group ..][0 .. neurons / group]; - host4.quantize(col, w8, s8, b8); - host4.dequantize(w8, s8, b8, col); - for (col, 0..) |x, k| v[k * d + o] = x; - } - const made = [_]struct { leaf: []const u8, dtype: st.DType, shape: [2]usize, bytes: []const u8 }{ - .{ .leaf = leaves[0], .dtype = .u32, .shape = .{ wide, d / 8 }, .bytes = std.mem.sliceAsBytes(uw) }, - .{ .leaf = leaves[1], .dtype = .bf16, .shape = .{ wide, d / group }, .bytes = std.mem.sliceAsBytes(us) }, - .{ .leaf = leaves[2], .dtype = .bf16, .shape = .{ wide, d / group }, .bytes = std.mem.sliceAsBytes(ub) }, - .{ .leaf = leaves[3], .dtype = .u32, .shape = .{ d, wide / 8 }, .bytes = std.mem.sliceAsBytes(dw) }, - .{ .leaf = leaves[4], .dtype = .bf16, .shape = .{ d, wide / group }, .bytes = std.mem.sliceAsBytes(ds) }, - .{ .leaf = leaves[5], .dtype = .bf16, .shape = .{ d, wide / group }, .bytes = std.mem.sliceAsBytes(db) }, - }; - var bytes: usize = 0; - for (made) |m| { - try edits.append(arena, .{ .name = try std.fmt.allocPrint(arena, "{s}{s}", .{ base, m.leaf }), .dtype = m.dtype, .shape = try arena.dupe(usize, &m.shape), .bytes = m.bytes }); - bytes += m.bytes.len; - } - return bytes; + return Shards.write(gpa, io, dir, pocket_layout.family, pocket_layout.layout(c), layers, neurons, &.{up}, down); } }; } - -fn zeros(arena: std.mem.Allocator, n: usize) ![]f32 { - const z = try arena.alloc(f32, n); - @memset(z, 0); - return z; -} - -fn words(bytes: []const u8) []align(1) const u32 { - return std.mem.bytesAsSlice(u32, bytes); -} - -fn halves(bytes: []const u8) []align(1) const u16 { - return std.mem.bytesAsSlice(u16, bytes); -} diff --git a/zig/src/families/nemotron/slide.zig b/zig/src/families/nemotron/slide.zig index d062d2f40a..ff62940596 100644 --- a/zig/src/families/nemotron/slide.zig +++ b/zig/src/families/nemotron/slide.zig @@ -9,6 +9,7 @@ const learn_shape = @import("learn_shape.zig"); const weights = @import("weights.zig"); const mtl = @import("metal"); const ckpt = @import("../../core/checkpoint_metal.zig"); +const pocket_layout = @import("pocket_layout.zig"); const shard_edit = @import("../../core/shard_edit.zig"); const Living = living.Io(struct { @@ -31,11 +32,17 @@ const Host = struct { pub const Trainer = train.Trainer; pub const max_rows = train.max_rows; pub const Ctx = *backend.Metal; + pub const family = pocket_layout.family; pub fn layers(b: Ctx) usize { return b.m.config.layers; } + /// Where the pocket sits and learns: every MoE layer, all but the last learning. + pub fn layout(b: Ctx) @import("living").Layout { + return pocket_layout.layout(b.m.config); + } + pub fn trainer(gpa: std.mem.Allocator, _: std.Io, b: Ctx) !*Trainer { return train.Trainer.init(gpa, b); } diff --git a/zig/src/living/affine.zig b/zig/src/living/affine.zig new file mode 100644 index 0000000000..177b40a4d4 --- /dev/null +++ b/zig/src/living/affine.zig @@ -0,0 +1,86 @@ +//! MLX's affine layout on the host at any group and code width; at 4 bits in groups of 64 it is affine4_host's. +const std = @import("std"); +const Quant = @import("family.zig").Quant; + +pub fn f32of(b: u16) f32 { + return @bitCast(@as(u32, b) << 16); +} + +/// The nearest bf16, ties to even; NaN stays NaN. +pub fn bf16of(x: f32) u16 { + const u: u32 = @bitCast(x); + if (std.math.isNan(x)) return @intCast((u >> 16) | 0x40); + return @intCast((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} + +/// u32 words `n` values take at `q`'s width. +pub fn wordsOf(comptime q: Quant, n: usize) usize { + return n * q.bits / 32; +} + +/// Row-major values from codes, scales and biases: scale * code + bias in f32 (the rows a whole number of groups). +pub fn dequantize(comptime q: Quant, words: []const u32, scales: []const u16, biases: []const u16, out: []f32) void { + const per = 32 / q.bits; + const mask: u32 = (1 << q.bits) - 1; + for (out, 0..) |*o, i| { + const c: u32 = (words[i / per] >> @intCast(q.bits * (i % per))) & mask; + o.* = f32of(scales[i / q.group]) * @as(f32, @floatFromInt(c)) + f32of(biases[i / q.group]); + } +} + +/// Codes, scales and biases for row-major values: a group's minimum is its bias, its range over the top code its scale. +pub fn quantize(comptime q: Quant, values: []const f32, words: []u32, scales: []u16, biases: []u16) void { + comptime std.debug.assert(32 % q.bits == 0); + const per = 32 / q.bits; + const top: f32 = @floatFromInt((1 << q.bits) - 1); + @memset(words, 0); + for (0..values.len / q.group) |g| { + const v = values[g * q.group ..][0..q.group]; + const lo = std.mem.min(f32, v); + const hi = std.mem.max(f32, v); + scales[g] = bf16of((hi - lo) / top); + biases[g] = bf16of(lo); + const s = f32of(scales[g]); + const b = f32of(biases[g]); + for (v, g * q.group..) |x, i| { + const c: u32 = if (s == 0) 0 else @intFromFloat(std.math.clamp(@round((x - b) / s), 0, top)); + words[i / per] |= c << @intCast(q.bits * (i % per)); + } + } +} + +test "a row at 4 bits in groups of 32 lands within half a step of each value, a flat group exactly on its bias" { + const q: Quant = .{ .bits = 4, .group = 32 }; + var values: [3 * 32]f32 = undefined; + for (&values, 0..) |*v, i| v.* = @sin(@as(f32, @floatFromInt(i)) * 0.41) * 0.07; + @memset(values[64..], -0.03); + var words: [wordsOf(q, 3 * 32)]u32 = undefined; + var scales: [3]u16 = undefined; + var biases: [3]u16 = undefined; + quantize(q, &values, &words, &scales, &biases); + var back: [3 * 32]f32 = undefined; + dequantize(q, &words, &scales, &biases, &back); + for (values, back, 0..) |v, b, i| try std.testing.expect(@abs(v - b) <= f32of(scales[i / 32]) * 0.51 + 1e-3); + for (back[64..]) |b| try std.testing.expectEqual(f32of(bf16of(-0.03)), b); + // written again from what it reads back, a row is the same codes: a save's values are a fixed point + var again: [wordsOf(q, 3 * 32)]u32 = undefined; + var s2: [3]u16 = undefined; + var b2: [3]u16 = undefined; + quantize(q, &back, &again, &s2, &b2); + var back2: [3 * 32]f32 = undefined; + dequantize(q, &again, &s2, &b2, &back2); + for (back, back2) |x, y| try std.testing.expectApproxEqAbs(x, y, 1e-6); +} + +test "8-bit codes pack four a word" { + const q: Quant = .{ .bits = 8, .group = 32 }; + var values: [32]f32 = undefined; + for (&values, 0..) |*v, i| v.* = @as(f32, @floatFromInt(i)) / 31; + var words: [8]u32 = undefined; + var s: [1]u16 = undefined; + var b: [1]u16 = undefined; + quantize(q, &values, &words, &s, &b); + var back: [32]f32 = undefined; + dequantize(q, &words, &s, &b, &back); + for (values, back) |v, x| try std.testing.expectApproxEqAbs(v, x, f32of(s[0]) * 0.51 + 1e-3); +} diff --git a/zig/src/living/families.zig b/zig/src/living/families.zig new file mode 100644 index 0000000000..a1db5ab468 --- /dev/null +++ b/zig/src/living/families.zig @@ -0,0 +1,79 @@ +//! Every family Living Weights knows, as data: the learner, the shard writer and the server's view read these. +const std = @import("std"); +const family = @import("family.zig"); +const Family = family.Family; +const test_families = @import("test_families.zig"); + +/// Nemotron 3.5 Lightning (nemotron_h): relu^2 shared experts at the pattern's MoE layers, 4-bit groups of 64. +pub const nemotron_h: Family = .{ + .model_type = "nemotron_h", + .names = .{ + .layers = "backbone.layers.", + .expert = "mixer.shared_experts.", + .inputs = &.{"up_proj"}, + .mtp = .{ .file = "mtp-4bit.safetensors", .base = "layers.1.mixer.shared_experts." }, + }, + .neuron = .{ .act = .relu2, .margin = 0.25 }, + .quant = .{ .bits = 4, .group = 64 }, + .keys = .{ .width = "moe_shared_expert_intermediate_size" }, + .experts = .pattern, +}; + +pub const all = [_]Family{nemotron_h}; + +/// The family of a checkpoint's top-level model_type, or null. +pub fn byModelType(model_type: []const u8) ?Family { + inline for (all) |f| if (std.mem.eql(u8, f.model_type, model_type)) return f; + return null; +} + +/// A config's layer letters (M mamba, E MoE, * attention, - MLP, ? other); a family with an expert at each: all E. +pub fn kinds(a: std.mem.Allocator, f: Family, o: std.json.ObjectMap) ![]const u8 { + const n = intField(o, f.keys.layers); + if (f.experts == .every) { + const count = n orelse if (o.get("layer_types")) |v| (if (v == .array) v.array.items.len else 0) else 0; + const out = try a.alloc(u8, count); + @memset(out, 'E'); + return out; + } + if (o.get("hybrid_override_pattern")) |v| if (v == .string and v.string.len > 0) return a.dupe(u8, v.string); + if (o.get("layers_block_type")) |v| if (v == .array) { + const out = try a.alloc(u8, v.array.items.len); + for (v.array.items, out) |b, *k| k.* = letter(if (b == .string) b.string else ""); + return out; + }; + const out = try a.alloc(u8, n orelse 0); + @memset(out, '?'); + return out; +} + +/// The object a family's model keys sit in (its scope, else the top level). +pub fn scoped(f: Family, root: std.json.ObjectMap) ?std.json.ObjectMap { + const s = f.keys.scope orelse return root; + const v = root.get(s) orelse return null; + return if (v == .object) v.object else null; +} + +fn letter(name: []const u8) u8 { + const names = [_]struct { []const u8, u8 }{ .{ "mamba", 'M' }, .{ "moe", 'E' }, .{ "attention", '*' }, .{ "mlp", '-' } }; + for (names) |n| if (std.mem.eql(u8, name, n[0])) return n[1]; + return '?'; +} + +pub fn intField(o: std.json.ObjectMap, key: []const u8) ?usize { + const v = o.get(key) orelse return null; + return if (v == .integer and v.integer >= 0) @intCast(v.integer) else null; +} + +test "each family's model type finds it; a pattern family's letters come from its pattern, an every-layer one's are E" { + try std.testing.expectEqualStrings("nemotron_h", byModelType("nemotron_h").?.model_type); + try std.testing.expect(byModelType("qwen4_exp") == null); + try std.testing.expect(byModelType("glm") == null); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const n = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"layers_block_type\": [\"mamba\", \"moe\", \"attention\"]}", .{}); + try std.testing.expectEqualStrings("ME*", try kinds(a, nemotron_h, n.object)); + const q = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"text_config\": {\"num_hidden_layers\": 3}}", .{}); + try std.testing.expectEqualStrings("EEE", try kinds(a, test_families.swiglu, scoped(test_families.swiglu, q.object).?)); +} diff --git a/zig/src/living/family.zig b/zig/src/living/family.zig new file mode 100644 index 0000000000..e4498b1d3c --- /dev/null +++ b/zig/src/living/family.zig @@ -0,0 +1,135 @@ +//! What a family hands Living Weights: where a pocket sits, how its neurons fire, how its shards hold them. +const std = @import("std"); + +/// What a pocket neuron does with its input x: relu(u x)^2 (Nemotron), or silu(g x) (w x) (a SwiGLU shared expert). +pub const Activation = enum { relu2, swiglu }; + +/// A pocket neuron's kind: its activation, whether a per-row gate scales its expert's output, and its input fit. +pub const Neuron = struct { + act: Activation, + /// The shared expert's output is scaled by a gate the trainer reads at each row, so a neuron adds gate act(x) v. + gated: bool = false, + /// The input fit's margin: rows a neuron stays silent on are fitted to u x at or below -margin. + margin: f32 = 0.25, + /// SwiGLU: a neuron fitted as u is written as gate row sharp * u and up row u / sharp (a power of two keeps u). + sharp: f32 = 16, + + /// Input projections a neuron has a row in: one (up) or two (gate, then up). + pub fn inputs(n: Neuron) usize { + return switch (n.act) { + .relu2 => 1, + .swiglu => 2, + }; + } +}; + +/// The shared expert's storage: MLX affine, `bits` a code in u32 words, a bf16 scale and bias every `group`. +pub const Quant = struct { bits: u8 = 4, group: usize = 64 }; + +/// The MTP head's shared expert, widened with zero neurons when the model's are, so its tensors stay one width. +pub const Mtp = struct { + file: ?[]const u8 = null, // its own safetensors file in the folder; null: in the model's index beside the rest + base: []const u8, // its shared expert's tensors' prefix, ending in "." +}; + +/// Tensor names: layer i's shared expert is `.`, then `.weight|scales|biases`. +pub const Names = struct { + layers: []const u8, + expert: []const u8, + inputs: []const []const u8, // the input projections in Neuron.inputs order: a row a neuron each + output: []const u8 = "down_proj", // the output projection: a column a neuron + mtp: ?Mtp = null, +}; + +/// config.json keys: where the model's own keys sit, the shared expert's width, the pocket's width once written. +pub const Keys = struct { + scope: ?[]const u8 = null, // the object holding the model's keys (Flash Next: "text_config"); null: the top level + width: []const u8, // the shared expert's width, widened by the pocket on its first save + pocket: []const u8 = "tensorfold_learned_neurons", + layers: []const u8 = "num_hidden_layers", + hidden: []const u8 = "hidden_size", +}; + +/// Which layers have a shared expert: those a layer pattern marks MoE, or every layer. +pub const Experts = enum { pattern, every }; + +pub const Family = struct { + model_type: []const u8, + names: Names, + neuron: Neuron, + quant: Quant, + keys: Keys, + experts: Experts, + /// Pocket neurons at each layer: a whole number of quantization groups. + neurons: usize = 64, + + /// Layer `layer`'s shared expert's tensor prefix, into `buf`. + pub fn expertBase(f: Family, buf: []u8, layer: usize) ![]const u8 { + return std.fmt.bufPrint(buf, "{s}{d}.{s}", .{ f.names.layers, layer, f.names.expert }); + } + + /// The layer a tensor name's shared expert sits at (null: not one of a layer's shared expert's tensors). + pub fn expertLayer(f: Family, name: []const u8) ?usize { + if (!std.mem.startsWith(u8, name, f.names.layers)) return null; + const rest = name[f.names.layers.len..]; + const dot = std.mem.indexOfScalar(u8, rest, '.') orelse return null; + if (!std.mem.startsWith(u8, rest[dot + 1 ..], f.names.expert)) return null; + return std.fmt.parseInt(usize, rest[0..dot], 10) catch null; + } + + /// Whether the description holds together: a neuron's rows match its inputs, the pocket a whole number of groups. + pub fn check(f: Family) !void { + if (f.names.inputs.len != f.neuron.inputs()) return error.BadFamily; + if (32 % f.quant.bits != 0 or f.quant.group == 0 or f.neurons == 0 or f.neurons % f.quant.group != 0) return error.BadFamily; + if (f.neuron.act == .swiglu and !(f.neuron.sharp > 0 and std.math.isPowerOfTwo(@as(u32, @intFromFloat(f.neuron.sharp))))) return error.BadFamily; + } +}; + +pub const max_layers = 128; +pub const Layers = std.bit_set.Static(max_layers); + +/// The served checkpoint as Living Weights reads it, built by the family (from its config) for its host. +pub const Layout = struct { + hidden: usize, + width: usize, // the shared expert's own neurons, a pocket written earlier left out + layers: usize, + widen: Layers = .empty, // layers whose shared expert carries the pocket in the shards (each with an expert) + learn: Layers = .empty, // of those, the ones lessons put neurons in + + /// The layers set in `which`, in order, into `out`. + pub fn list(lay: Layout, which: Layers, out: []usize) []usize { + var n: usize = 0; + for (0..lay.layers) |l| if (which.isSet(l)) { + out[n] = l; + n += 1; + }; + return out[0..n]; + } + + /// Every layer `has` names carries one widened; all but the last learn (a nudge after it has no gradient to read). + pub fn fromExperts(hidden: usize, width: usize, layers: usize, has: Layers) Layout { + var lay: Layout = .{ .hidden = hidden, .width = width, .layers = layers, .widen = has, .learn = has }; + if (layers > 0) lay.learn.unset(layers - 1); + return lay; + } +}; + +test "a family finds its shared expert's layer in a tensor name and builds its prefix" { + const f = @import("test_families.zig").swiglu; + try f.check(); + var buf: [128]u8 = undefined; + try std.testing.expectEqualStrings("language_model.model.layers.7.mlp.shared_expert.", try f.expertBase(&buf, 7)); + try std.testing.expectEqual(@as(?usize, 7), f.expertLayer("language_model.model.layers.7.mlp.shared_expert.up_proj.scales")); + try std.testing.expectEqual(@as(?usize, null), f.expertLayer("language_model.model.layers.7.mlp.shared_expert_gate.scales")); + try std.testing.expectEqual(@as(?usize, null), f.expertLayer("language_model.mtp.layers.0.mlp.shared_expert.up_proj.scales")); + const n = @import("families.zig").nemotron_h; + try n.check(); + try std.testing.expectEqual(@as(?usize, 13), n.expertLayer("backbone.layers.13.mixer.shared_experts.down_proj.weight")); + var has: Layers = .empty; + has.set(1); + has.set(3); + const lay = Layout.fromExperts(8, 16, 4, has); + var out: [4]usize = undefined; + try std.testing.expectEqualSlices(usize, &.{ 1, 3 }, lay.list(lay.widen, &out)); + try std.testing.expectEqualSlices(usize, &.{1}, lay.list(lay.learn, &out)); +} diff --git a/zig/src/living/host_test.zig b/zig/src/living/host_test.zig new file mode 100644 index 0000000000..e9cb25b719 --- /dev/null +++ b/zig/src/living/host_test.zig @@ -0,0 +1,215 @@ +//! The learner over a stand-in host and trainer on the CPU: a whole pocket lesson read, fitted, stepped, saved. +const std = @import("std"); +const learner = @import("learner.zig"); +const families = @import("families.zig"); +const fam = @import("family.zig"); +const train_mode = @import("train_mode.zig"); +const lesson_route = @import("lesson_route.zig"); +const clock = @import("pocket_clock.zig"); +const neuron = @import("neuron.zig"); + +const Example = @import("lesson_examples.zig").Example; +const Seq = train_mode.Seq; +const Span = train_mode.Span; +const Result = train_mode.Result; +const d = 64; +const layers = 8; + +/// A trainer with the pocket's hooks and nothing of Nemotron's routed blocks (no `sites`). +const Toy = struct { + spans: [4]Span = undefined, + pack: usize = 64, + count: clock.Count = .{}, + prefixes: struct { + pub const most = 4; + } = .{}, + nudge: train_mode.Nudge = .{}, + from: [layers]u32 = @splat(std.math.maxInt(u32)), + rows: std.ArrayList(u64) = .empty, // each pass row's hash of the tokens through it + gpa: std.mem.Allocator, + scratch: [d]u16 = undefined, + push: [d]f32 = undefined, + delta: [d]f32 = undefined, + gates: usize = 0, // gate scales read + + pub fn packs(_: *const Toy) bool { + return false; + } + + pub fn prefixSlots(_: *Toy, _: usize) !void {} + + fn lay(t: *Toy, seqs: []const Seq) !void { + t.rows.clearRetainingCapacity(); + for (seqs, 0..) |q, i| { + t.spans[i] = .{ .at = t.rows.items.len, .rows = q.ids.len - 1 - q.skip, .skip = q.skip, .slot = q.slot }; + var h = std.hash.Wyhash.init(0); + for (q.ids[0 .. q.ids.len - 1], 0..) |id, r| { + h.update(std.mem.asBytes(&id)); + if (r >= q.skip) try t.rows.append(t.gpa, h.final()); + } + } + t.count.passes += 1; + t.count.rows += t.rows.items.len; + } + + pub fn pass(t: *Toy, seqs: []const Seq, mode: train_mode.Mode, _: lesson_route.Turn, out: []Result) !void { + try t.lay(seqs); + for (out[0..seqs.len]) |*r| r.* = .{ .loss = if (mode == .keys) 0 else 0.5, .recalled = true }; + } + + pub fn step(t: *Toy, ids: []const u32, start: usize, mode: train_mode.Mode, turn: lesson_route.Turn) !Result { + var out: [1]Result = undefined; + try t.pass(&.{.{ .ids = ids, .start = start, .decide = turn.decide }}, mode, turn, &out); + return out[0]; + } + + /// Row `row`'s input at layer `l`: unit-sized noise from the row's hash, so different contexts read apart. + pub fn normed(t: *Toy, l: usize, row: usize) []const u16 { + var prng = std.Random.DefaultPrng.init(t.rows.items[row] ^ (@as(u64, l) *% 0x9e3779b97f4a7c15)); + for (&t.scratch) |*x| x.* = @truncate(@as(u32, @bitCast(1 + prng.random().floatNorm(f32))) >> 16); + return &t.scratch; + } + + pub fn residual(t: *Toy, l: usize, row: usize) []const u16 { + return t.normed(l + 100, row); + } + + pub fn pushAt(t: *Toy, _: usize, key: usize, l: usize) []const f32 { + for (&t.push, 0..) |*x, i| x.* = 0.01 * @as(f32, @floatFromInt((i + key + l) % 7)) - 0.03; + return &t.push; + } + + pub fn deltaAt(t: *Toy, _: usize, _: usize, _: usize) []f32 { + return &t.delta; + } + + pub fn gateAt(t: *Toy, _: usize, _: usize) f32 { + t.gates += 1; + return 0.25; + } +}; + +/// A host over the toy trainer for family `F`, counting what the learner hands it. +fn Host(comptime F: fam.Family) type { + return struct { + pub const Trainer = Toy; + pub const max_rows = 64; + pub const family = F; + pub const Ctx = *Seen; + + pub const Seen = struct { uploads: usize = 0, saved: usize = 0, gate_ok: bool = true, up_ok: bool = true, written: []const usize = &.{} }; + + pub fn layout(_: Ctx) fam.Layout { + var every: fam.Layers = .empty; + for (0..layers) |l| every.set(l); + return .fromExperts(d, 128, layers, every); + } + + pub fn trainer(gpa: std.mem.Allocator, _: std.Io, _: Ctx) !*Toy { + const t = try gpa.create(Toy); + t.* = .{ .gpa = gpa }; + return t; + } + + pub fn free(t: *Toy, gpa: std.mem.Allocator) void { + t.rows.deinit(gpa); + gpa.destroy(t); + } + + pub fn seconds(_: std.Io) f64 { + return 0; + } + + pub fn pocket(s: Ctx, _: usize, _: []const f32, _: []const f32, _: usize) !void { + s.uploads += 1; + } + + pub fn pocketRead(_: Ctx, _: usize, _: []f32, _: []f32) usize { + return 0; + } + + pub fn pocketSave(s: Ctx, _: std.mem.Allocator, _: std.Io, written: []const usize, _: usize, _: []f32, _: []f32) !usize { + s.saved += 1; + s.written = written; + return 1; + } + + /// The forward's rows before a save: each gate row sharp^2 times its up row (g = sharp u, w = u / sharp). + pub fn pocketSwiglu(s: Ctx, _: usize, gate: []const f32, up: []const f32, _: []const f32, _: usize) !void { + s.uploads += 1; + if (s.saved > 0) return; // after a save the rows are as written, each rounded its own way + for (gate, up) |g, w| if (@abs(g - F.neuron.sharp * F.neuron.sharp * w) > 1e-5 * @abs(g) + 1e-30) { + s.up_ok = false; + }; + } + + pub fn pocketReadSwiglu(_: Ctx, _: usize, _: []f32, _: []f32, _: []f32) usize { + return 0; + } + + pub fn pocketSaveSwiglu(s: Ctx, _: std.mem.Allocator, _: std.Io, written: []const usize, _: usize, gate: []f32, up: []f32, _: []f32) !usize { + s.saved += 1; + s.written = written; + for (gate, up) |g, w| if (@abs(g - F.neuron.sharp * F.neuron.sharp * w) > 1e-5 * @abs(g) + 1e-30) { + s.gate_ok = false; + }; + // handed back as a writer would: rounded, so the learner takes u from the up rows as written + for (up) |*w| w.* = std.math.round(w.* * 4096) / 4096; + return 1; + } + }; +} + +/// A fact's question and answer: token `who` picks whose fact it is, so its rows read apart from others'. +fn qa(gpa: std.mem.Allocator, who: u32, k: u32) !Example { + const ids = try gpa.dupe(u32, &.{ 1, 2, who, 40 + k, 5, 90 + who, 91, 92 }); + return .{ .ids = ids, .start = 5, .decide = 4 }; +} + +fn run(comptime F: fam.Family) !void { + const gpa = std.testing.allocator; + const H = Host(F); + var seen: H.Seen = .{}; + var l = learner.Learner(H).init(gpa, std.testing.io, &seen); + defer l.deinit(); + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + var train: [6]Example = undefined; + var held: [2]Example = undefined; + var other: [8]Example = undefined; + for (&train, 0..) |*x, k| x.* = try qa(a, 7, @intCast(k)); + for (&held, 0..) |*x, k| x.* = try qa(a, 7, @intCast(10 + k)); + for (&other, 0..) |*x, k| x.* = try qa(a, 20 + @as(u32, @intCast(k)), @intCast(k)); + try l.begin(.{ .train = &train, .held = &held, .keep = &other }); + var report: ?learner.Report = null; + var steps: usize = 0; + while (true) : (steps += 1) { + const s = l.step(); + if (s.report) |r| report = r; + if (s.done) break; + try std.testing.expect(steps < 10_000); + } + try std.testing.expect(report != null and report.? == .learned); + try std.testing.expect(report.?.learned.recalled); + var placed: [64]learner.Learner(H).Placed = undefined; + const got = l.placed(&placed); + try std.testing.expect(got.len > 0); + for (got) |x| try std.testing.expect(x.layer > 0 and x.layer < layers - 1); + try std.testing.expect(seen.uploads > 0); + // the save: through the family's own hook, every learning layer handed over + try l.begin(.{ .save = true }); + while (!l.step().done) {} + try std.testing.expectEqual(@as(usize, 1), seen.saved); + try std.testing.expectEqual(@as(usize, layers - 1), seen.written.len); + try std.testing.expect(seen.gate_ok and seen.up_ok); + if (F.neuron.gated) try std.testing.expect(l.trainer.?.gates > 0); +} + +test "a pocket lesson over a stand-in relu^2 host: read, fitted, stepped, judged, saved" { + try run(families.nemotron_h); +} + +test "a pocket lesson over a stand-in gated SwiGLU host: its rows handed over as gate sharp u and up u / sharp, the gate read" { + try run(@import("test_families.zig").swiglu); +} diff --git a/zig/src/living/learner.zig b/zig/src/living/learner.zig index 0607eb90c1..ddad1c54b8 100644 --- a/zig/src/living/learner.zig +++ b/zig/src/living/learner.zig @@ -1,4 +1,4 @@ -//! Sliding Weights' lessons, one learner for every backend over a host that gives the trainer, weights and files. +//! Living Weights' lessons, one learner for every family and backend over a host that gives the trainer and hooks. const std = @import("std"); const adapters = @import("learn_shape.zig"); const choice = @import("choice.zig"); @@ -42,16 +42,17 @@ const replay_each = 8; // of a lesson's answers, its first (plain questions) joi /// A lesson builds (build) and learns (steps); an edit is written at its subject (edit), more rounds report (again). const Phase = enum { idle, build, steps, undo, reroute, drop, save, edit, again, probe, pocket, retire }; -/// The lessons over host H: its Trainer, max_rows, Ctx, layers, trainer, free, attach, write and seconds. +/// The lessons over host H: its trainer and hooks (family.zig), routed blocks only when its trainer keeps `sites`. pub fn Learner(comptime H: type) type { return struct { const Self = @This(); - const has_edits = @hasDecl(H.Trainer, "key") and @hasDecl(H, "commit"); // keys, a nudged row, codes to write - const has_pocket = @hasDecl(H.Trainer, "normed") and @hasDecl(H, "pocketSave"); // inputs, gradients, a pocket to write + const has_sites = @hasField(H.Trainer, "sites"); // Nemotron's routed blocks of ranks (the LoRA path) + const has_edits = has_sites and @hasDecl(H.Trainer, "key") and @hasDecl(H, "commit"); // keys, a nudged row, codes to write + const has_pocket = @hasDecl(H.Trainer, "normed") and (@hasDecl(H, "pocketSave") or @hasDecl(H, "pocketSaveSwiglu")); // inputs, gradients, a pocket to write const has_whole = has_edits or has_pocket; // lessons that change the model itself const Edits = if (has_edits) editor.Editor(H.Trainer) else void; const Probes = if (has_edits) probe.Probe(H.Trainer) else void; - const Pockets = if (has_pocket) pocket.Pocket(H.Trainer) else void; + const Pockets = if (has_pocket) pocket.Pocket(H.Trainer, H.family) else void; pub const Host = H; gpa: std.mem.Allocator, @@ -96,7 +97,7 @@ pub fn Learner(comptime H: type) type { pocketed: bool = false, // the last lesson put neurons in the pocket pub fn init(gpa: std.mem.Allocator, io: std.Io, b: H.Ctx) Self { - return .{ .gpa = gpa, .io = io, .b = b, .whole = std.c.getenv("TF_SLIDE_ROUTED") == null, .edits = if (has_edits) Edits.init(gpa) else {}, .method = if (has_edits) whole_lessons.method() else .pocket, .probe = if (has_edits) Probes.init(gpa) else {}, .pockets = if (has_pocket) Pockets.init(gpa) else {} }; + return .{ .gpa = gpa, .io = io, .b = b, .whole = !has_sites or std.c.getenv("TF_SLIDE_ROUTED") == null, .edits = if (has_edits) Edits.init(gpa) else {}, .method = if (has_edits) whole_lessons.method() else .pocket, .probe = if (has_edits) Probes.init(gpa) else {}, .pockets = if (has_pocket) Pockets.init(gpa) else {} }; } pub fn deinit(l: *Self) void { @@ -177,9 +178,11 @@ pub fn Learner(comptime H: type) type { return l.start(); } try l.settleLast(lesson.train); - if (l.trainer.?.sites.rank + adapters.block > adapters.max_rank) return error.LearnedChangeFull; - l.trainer.?.sites.clear(); - l.trainer.?.sketched = 0; + if (has_sites) { + if (l.trainer.?.sites.rank + adapters.block > adapters.max_rank) return error.LearnedChangeFull; + l.trainer.?.sites.clear(); + l.trainer.?.sketched = 0; + } l.built = 0; l.bits.clearRetainingCapacity(); l.seen.clearRetainingCapacity(); @@ -189,6 +192,7 @@ pub fn Learner(comptime H: type) type { l.keeps.clearRetainingCapacity(); l.topic = false; if (l.whole) return if (has_whole) whole_lessons.begin(l, lesson) else error.EditsUnsupported; + if (comptime !has_sites) unreachable; // a host without routed blocks learns whole lessons only l.gpa.free(l.answers); l.answers = try std.mem.concat(l.gpa, Example, &.{ lesson.train, lesson.think }); l.phase = .build; @@ -202,18 +206,21 @@ pub fn Learner(comptime H: type) type { fn ready(l: *Self) !void { if (l.trainer != null) return; const t0 = H.seconds(l.io); - l.choice = try choice.Choice.init(l.gpa, H.layers(l.b)); + if (has_sites) l.choice = try choice.Choice.init(l.gpa, H.layers(l.b)); l.trainer = try H.trainer(l.gpa, l.io, l.b); std.log.info("slide: the trainer is ready in {d:.1} s", .{H.seconds(l.io) - t0}); - l.trainer.?.sites.whole = l.whole; - for (&l.asks) |*side| { - side.* = try l.gpa.alloc(std.ArrayList(f32), H.layers(l.b)); - for (side.*) |*rows| rows.* = .empty; + if (has_sites) { + l.trainer.?.sites.whole = l.whole; + for (&l.asks) |*side| { + side.* = try l.gpa.alloc(std.ArrayList(f32), H.layers(l.b)); + for (side.*) |*rows| rows.* = .empty; + } } } /// A round's steps from the open block as it is now, which an undo comes back to. fn start(l: *Self) !void { + if (comptime !has_sites) return error.RoutedUnsupported; try l.schedule(@max(@min(l.lesson.steps, max_steps), 1)); l.trainer.?.sites.keep(); l.can_undo = true; @@ -230,7 +237,7 @@ pub fn Learner(comptime H: type) type { /// One bounded unit: one example sketched or projected, one step of learning (a check every few), or the undo. pub fn step(l: *Self) Step { return l.advance() catch |e| { - if (l.phase == .steps) l.trainer.?.sites.restore(); + if (has_sites and l.phase == .steps) l.trainer.?.sites.restore(); l.phase = .idle; return .{ .done = true, .changed = true, .report = .{ .failed = @errorName(e) } }; }; @@ -242,7 +249,7 @@ pub fn Learner(comptime H: type) type { .undo => { l.phase = .idle; if (has_whole and l.whole and try whole_lessons.undo(l)) return .{ .done = true, .changed = true }; - if (!l.can_undo) return .{ .done = true }; + if (!has_sites or !l.can_undo) return .{ .done = true }; l.trainer.?.sites.restore(); l.can_undo = false; l.kept_rounds -|= 1; @@ -283,6 +290,7 @@ pub fn Learner(comptime H: type) type { if (has_whole and !try whole_lessons.save(l)) try whole_lessons.foldOpen(l); return .{ .done = true, .changed = true }; } + if (comptime !has_sites) return .{ .done = true }; const ranks = t.sites.rank - @as(usize, if (l.opened and l.kept_rounds == 0) adapters.block else 0); if (ranks == 0) return .{ .done = true }; const t0 = H.seconds(l.io); @@ -298,6 +306,7 @@ pub fn Learner(comptime H: type) type { /// A pass of `ex` in `mode` (`acting`: the open lesson acts on its reply); its first reads which kept ones act. fn pass(l: *Self, ex: Example, mode: train_mode.Mode, acting: bool) !f32 { + if (comptime !has_sites) return error.RoutedUnsupported; const t = l.trainer.?; const k = key(ex); const known = l.bits.get(k); @@ -311,6 +320,7 @@ pub fn Learner(comptime H: type) type { /// Every lesson kept before the open one, all acting (an in-place learner's lessons are part of the model). pub fn keptLessons(l: *const Self) Acting { var bits: Acting = .empty; + if (comptime !has_sites) return bits; // no blocks: the pocket is the model's own for (0..l.trainer.?.sites.rank / adapters.block - @intFromBool(l.opened)) |b| bits.set(b); return bits; } @@ -323,12 +333,14 @@ pub fn Learner(comptime H: type) type { /// Layer by layer, a routing prompt's decision row along the candidates, as the last project pass left it. fn ask(l: *Self, r: Asked) !void { + if (comptime !has_sites) return error.RoutedUnsupported; const t = l.trainer.?; for (l.asks[@backingInt(r.kind)], 0..) |*rows, k| try rows.appendSlice(l.gpa, t.projected(k, r.ex.ids.len - 1)[r.ex.decide * adapters.candidates ..][0..adapters.candidates]); } /// One example at a time: sketched, projected, routing rows copied; then the block chosen, its router fitted. fn buildOnce(l: *Self) !Step { + if (comptime !has_sites) return error.RoutedUnsupported; const t = l.trainer.?; const c = &l.choice.?; // an edit of the weights also keeps the questions about others, and reads every wording of the fact's @@ -383,6 +395,7 @@ pub fn Learner(comptime H: type) type { /// The open block's router: if facts don't stand apart it acts on what most clear, learning to leave the rest. fn route(l: *Self) !void { + if (comptime !has_sites) return error.RoutedUnsupported; const t = l.trainer.?; var fit = try l.fitWith(&.{.fact}, &.{ .near, .swap, .other }); defer fit.deinit(l.gpa); @@ -447,6 +460,7 @@ pub fn Learner(comptime H: type) type { /// A taken question: a topic lesson keeps its answer for next round; a strict one refits its router without it. fn rerouteOnce(l: *Self) !Step { if (l.whole) return if (has_whole) whole_lessons.reroute(l) else unreachable; + if (comptime !has_sites) return error.RoutedUnsupported; if (l.topic) { for (l.lesson.kept) |ex| try l.keeps.append(l.gpa, .{ .ids = try l.gpa.dupe(u32, ex.ids), .start = ex.start, .decide = ex.decide }); l.phase = .idle; @@ -513,7 +527,7 @@ pub fn Learner(comptime H: type) type { const t = l.trainer.?; for (held) |ex| { var bits = if (l.whole) l.keptLessons() else l.earlier(ex); - if (open) bits.set(t.sites.first() / adapters.block); + if (has_sites and open) bits.set(t.sites.first() / adapters.block); if (!(try t.step(ex.ids, ex.start, .loss, .{ .decide = ex.decide, .bits = bits, .whole = l.whole })).recalled) return false; } return true; @@ -523,7 +537,7 @@ pub fn Learner(comptime H: type) type { fn settleLast(l: *Self, answers: []const Example) !void { const now = try own(l.gpa, answers); if (has_whole and l.whole) try whole_lessons.settle(l); - if (l.opened and l.kept_rounds == 0) { + if (has_sites and l.opened and l.kept_rounds == 0) { l.trainer.?.sites.needs()[l.trainer.?.sites.first() / adapters.block] = 0; l.trainer.?.sites.close(); try H.attach(l.b, l.trainer.?); diff --git a/zig/src/living/living.zig b/zig/src/living/living.zig index 9b9d1d1afe..e1d75f4163 100644 --- a/zig/src/living/living.zig +++ b/zig/src/living/living.zig @@ -1,4 +1,10 @@ -//! Living Weights: the lesson learner, its pocket of new neurons beside each shared expert, their fits and helpers. +//! Living Weights, family-neutral: the learner, its pocket of new neurons, their fits and the shard writer. +pub const family = @import("family.zig"); +pub const families = @import("families.zig"); +pub const Family = family.Family; +pub const Layout = family.Layout; +pub const Layers = family.Layers; + pub const learner = @import("learner.zig"); pub const whole = @import("whole.zig"); pub const choice = @import("choice.zig"); @@ -10,21 +16,35 @@ pub const train_mode = @import("train_mode.zig"); pub const learn_shape = @import("learn_shape.zig"); pub const lesson_examples = @import("lesson_examples.zig"); pub const lesson_route = @import("lesson_route.zig"); +pub const neuron = @import("neuron.zig"); +pub const affine = @import("affine.zig"); +pub const shards = @import("shards.zig"); pub const pocket = @import("pocket.zig"); pub const pocket_clock = @import("pocket_clock.zig"); pub const pocket_dump = @import("pocket_dump.zig"); pub const pocket_fit = @import("pocket_fit.zig"); pub const pocket_joint = @import("pocket_joint.zig"); +pub const pocket_load = @import("pocket_load.zig"); pub const pocket_pack = @import("pocket_pack.zig"); pub const pocket_prefix = @import("pocket_prefix.zig"); +pub const pocket_quiet = @import("pocket_quiet.zig"); pub const pocket_read = @import("pocket_read.zig"); pub const pocket_values = @import("pocket_values.zig"); test { + _ = family; + _ = families; + _ = neuron; + _ = affine; + _ = shards; _ = learner; + _ = whole; _ = subspace; _ = pocket; _ = pocket_fit; _ = router; + _ = choice; _ = lesson_route; + _ = @import("swiglu_test.zig"); + _ = @import("host_test.zig"); } diff --git a/zig/src/living/neuron.zig b/zig/src/living/neuron.zig new file mode 100644 index 0000000000..52db123839 --- /dev/null +++ b/zig/src/living/neuron.zig @@ -0,0 +1,55 @@ +//! A pocket neuron's activation for each family's kind, and the gate and up rows a SwiGLU neuron is written as. +const std = @import("std"); +const Neuron = @import("family.zig").Neuron; + +pub fn sigmoid(y: f32) f32 { + return 1 / (1 + @exp(-y)); +} + +pub fn silu(y: f32) f32 { + return y * sigmoid(y); +} + +/// The activation of a neuron of kind `n` at input x: `z` is u x (u as fitted), `zg` its gate row's g x (SwiGLU). +pub fn act(n: Neuron, z: f32, zg: f32) f32 { + return switch (n.act) { + .relu2 => if (z > 0) z * z else 0, + .swiglu => silu(zg) * (z / n.sharp), // its up row is u / sharp + }; +} + +/// A SwiGLU neuron's gate row from its fitted input u: sharp u. +pub fn gateRow(n: Neuron, u: []const f32, out: []f32) void { + for (out, u) |*o, x| o.* = n.sharp * x; +} + +/// The up row a SwiGLU neuron is written as, from u: u / sharp (exact for a power of two). +pub fn upRow(n: Neuron, u: []const f32, out: []f32) void { + for (out, u) |*o, x| o.* = x / n.sharp; +} + +/// u back from an up row as written: sharp w. +pub fn fromUp(n: Neuron, w: []const f32, out: []f32) void { + for (out, w) |*o, x| o.* = n.sharp * x; +} + +test "a SwiGLU neuron written as sharp u and u / sharp fires as relu^2 on its rows and stays near zero past the margin" { + const n: Neuron = .{ .act = .swiglu, .margin = 0.5, .sharp = 16 }; + const r: Neuron = .{ .act = .relu2 }; + // z = u x; the gate row reads sharp z, and the up row's z / sharp times silu is what the forward adds + for ([_]f32{ 1, 1.5, 3 }) |z| { + try std.testing.expectApproxEqRel(act(r, z, 0), act(n, z, n.sharp * z), 1e-6); + } + var most: f32 = 0; + var z: f32 = -n.margin; + while (z > -20) : (z -= 0.01) most = @max(most, @abs(act(n, z, n.sharp * z))); + try std.testing.expect(most < n.margin * n.margin * sigmoid(-n.sharp * n.margin) * 1.01); + try std.testing.expect(most < 1e-4); + // the up row as written gives u back exactly + const u = [_]f32{ 0.123, -7.5e-3, 3.25 }; + var w: [3]f32 = undefined; + var back: [3]f32 = undefined; + upRow(n, &u, &w); + fromUp(n, &w, &back); + try std.testing.expectEqualSlices(f32, &u, &back); +} diff --git a/zig/src/living/pocket.zig b/zig/src/living/pocket.zig index ff24ac5ee9..aff4a4ad4a 100644 --- a/zig/src/living/pocket.zig +++ b/zig/src/living/pocket.zig @@ -8,6 +8,10 @@ const joint = @import("pocket_joint.zig"); const pocket_dump = @import("pocket_dump.zig"); const clock = @import("pocket_clock.zig"); const reading = @import("pocket_read.zig"); +const quieting = @import("pocket_quiet.zig"); +const loading = @import("pocket_load.zig"); +const family = @import("family.zig"); +const neuron_math = @import("neuron.zig"); const Example = examples.Example; const Acting = lesson_route.Acting; @@ -16,15 +20,10 @@ const Fit = pocket_fit.Fit; const fit = pocket_fit.fit; const fitLayer = pocket_fit.fitLayer; const dotBf16 = pocket_fit.dotBf16; -const margin = pocket_fit.margin; const fit_steps = pocket_fit.fit_steps; -/// A pocket's neurons at each MoE layer: one 4-bit group of the shared expert's width. -pub const neurons = 64; const per_fact = 10; // neurons a fact takes, at the layers that tell its questions apart best const value_neurons = 4; // of those, the ones before its answer's value, when its answers show one -const kept_least: f32 = 0.5; // an earlier neuron refitted must still reach this on every one of its own fact's rows -const refit_above: f32 = 0.5; // an earlier neuron is refitted only where it fires above this on a new fact's rows /// Where a neuron fires: the reply's first row, the named subject's last token, or the row before the answer's value. pub const Key = enum(u2) { reply, subject, value }; @@ -85,10 +84,16 @@ fn better(f: []const Fit, a: usize, b: usize) bool { return f[a].fact_least > f[b].fact_least; } -/// A pocket over trainer T (Metal's: input, residual, nudges) and a host that hands each layer's to the forward. -pub fn Pocket(comptime T: type) type { +/// A pocket over trainer T (its inputs, residuals, nudges) for family F, and a host handing each layer to the forward. +pub fn Pocket(comptime T: type, comptime F: family.Family) type { + comptime F.check() catch unreachable; return struct { const Self = @This(); + /// A pocket's neurons at each layer it sits at: a whole number of quantization groups of the expert's width. + pub const neurons = F.neurons; + pub const of = F; // the family it learns into + pub const swiglu = F.neuron.act == .swiglu; + pub const gated = F.neuron.gated; gpa: std.mem.Allocator, mode: Mode, // as asked (TF_SLIDE_POCKET_KEY), auto by default @@ -105,9 +110,13 @@ pub fn Pocket(comptime T: type) type { split: [3]usize = .{ per_fact, 0, 0 }, // the open fact's neurons on each key subjects: std.ArrayList(u32) = .empty, // the open fact's subject tokens leads: std.ArrayList(u32) = .empty, // the tokens before them: after another, the subject is someone else's - moe: std.ArrayList(usize) = .empty, // the MoE layers a pocket sits at, its slots in order - up: std.ArrayList(f32) = .empty, // [slots, neurons, D]: each neuron's input weights + moe: std.ArrayList(usize) = .empty, // the layers a pocket learns at (the layout's), its slots in order + hidden: usize = 0, // D, as the layout gives it + layers: usize = 0, // the model's layers, as the layout gives them + up: std.ArrayList(f32) = .empty, // [slots, neurons, D]: each neuron's input weights u, as fitted down: std.ArrayList(f32) = .empty, // [slots, neurons, D]: each neuron's output + gate: std.ArrayList(f32) = .empty, // SwiGLU: [slots, neurons, D], each neuron's gate row (sharp u, or as written) + scratch: std.ArrayList(f32) = .empty, // SwiGLU: [neurons, D], a slot's up rows (u / sharp) as handed over used: std.ArrayList(usize) = .empty, // [slots]: neurons in use, the first ones taken: std.ArrayList(Taken) = .empty, // the open fact's neurons answered: []const Example = &.{}, // the fact's answers, which its neurons' outputs are fitted on @@ -124,6 +133,7 @@ pub fn Pocket(comptime T: type) type { retired_marks: usize = 0, // retired_lessons before the last retire, which a put-back returns to retired: std.ArrayList([2]usize) = .empty, // the last retire's (slot, neuron), put back if the newer fact fails retired_w: std.ArrayList(f32) = .empty, // [retired, 2, D]: their input and output weights from before + refit_gate: std.ArrayList(f32) = .empty, // SwiGLU: [refits, D], their gate rows from before phase: enum { read, fit, values, check, done } = .done, at: usize = 0, // the next example read, answer of a step, or held-out answer judged back: usize = 0, // held-out answers that came back token for token @@ -141,7 +151,7 @@ pub fn Pocket(comptime T: type) type { } pub fn deinit(p: *Self) void { - inline for (.{ "moe", "up", "down", "used", "taken", "rows", "labels", "keeps", "refits", "refit_up", "retired_lessons", "retired", "retired_w", "joint", "joint_down", "joint_answers", "learned", "pos", "subjects", "leads" }) |f| @field(p, f).deinit(p.gpa); + inline for (.{ "moe", "up", "down", "gate", "scratch", "used", "taken", "rows", "labels", "keeps", "refits", "refit_up", "refit_gate", "retired_lessons", "retired", "retired_w", "joint", "joint_down", "joint_answers", "learned", "pos", "subjects", "leads" }) |f| @field(p, f).deinit(p.gpa); p.read.deinit(p.gpa); p.v.deinit(p.gpa); } @@ -188,23 +198,29 @@ pub fn Pocket(comptime T: type) type { return which[(slot * neurons + n) * d ..][0..d]; } - /// The pocket's neurons as the shards hold them, read once: every MoE layer but the last. + /// Neuron n of `slot`'s activation at input `x` (bf16): relu(u x)^2, or silu(g x) (u x) / sharp (neuron.zig). + pub fn act(p: *const Self, slot: usize, n: usize, x: []const u16) f32 { + const d = p.hidden; + const z = dotBf16(p.neuron(@constCast(p.up.items), slot, n, d), x); + const zg = if (swiglu) dotBf16(p.neuron(@constCast(p.gate.items), slot, n, d), x) else 0; + return neuron_math.act(F.neuron, z, zg); + } + + /// A SwiGLU neuron's gate row set from its input weights as they are now. + pub fn gateFrom(p: *Self, slot: usize, n: usize) void { + if (!swiglu) return; + neuron_math.gateRow(F.neuron, p.neuron(p.up.items, slot, n, p.hidden), p.neuron(p.gate.items, slot, n, p.hidden)); + } + fn load(p: *Self, t: *T, host: anytype) !void { - if (p.moe.items.len > 0) return; - const c = t.config(); - // every MoE layer but the last (a nudge after it has no gradient to read), its neurons as loaded - for (0..c.layers - 1) |l| if (c.kinds[l] == .moe) try p.moe.append(p.gpa, l); - const n = neurons * c.hidden; - try p.up.appendNTimes(p.gpa, 0, p.slots() * n); - try p.down.appendNTimes(p.gpa, 0, p.slots() * n); - try p.used.appendNTimes(p.gpa, 0, p.slots()); - for (p.moe.items, 0..) |l, j| p.used.items[j] = host.pocketRead(l, p.up.items[j * n ..][0..n], p.down.items[j * n ..][0..n]); + _ = t; + return loading.load(p, host); } /// A replaced fact's neurons, (layer, neuron) each, zeroed where they sit; their places stay taken. pub fn retire(p: *Self, t: *T, host: anytype, gone: []const [2]u16) !void { try p.load(t, host); - const d = t.config().hidden; + const d = p.hidden; p.retired.clearRetainingCapacity(); p.retired_w.clearRetainingCapacity(); p.retired_marks = p.retired_lessons.items.len; @@ -225,7 +241,7 @@ pub fn Pocket(comptime T: type) type { /// The last retire undone: its neurons as they were (the fact that replaced theirs was not learned). pub fn unretire(p: *Self, t: *T, host: anytype) !void { try p.load(t, host); - const d = t.config().hidden; + const d = p.hidden; for (p.retired.items, 0..) |r, i| { @memcpy(p.neuron(p.up.items, r[0], r[1], d), p.retired_w.items[2 * i * d ..][0..d]); @memcpy(p.neuron(p.down.items, r[0], r[1], d), p.retired_w.items[(2 * i + 1) * d ..][0..d]); @@ -260,6 +276,7 @@ pub fn Pocket(comptime T: type) type { p.refit_up.clearRetainingCapacity(); p.joint.clearRetainingCapacity(); p.joint_down.clearRetainingCapacity(); + p.refit_gate.clearRetainingCapacity(); p.learned_before = p.learned.items.len; p.pos_before = p.pos.items.len; p.clock = .{}; @@ -303,7 +320,7 @@ pub fn Pocket(comptime T: type) type { /// The open fact's neurons back to zero and free, and the earlier neurons it fitted again as they were. pub fn undo(p: *Self, t: *T, host: anytype) !void { - const d = t.config().hidden; + const d = p.hidden; p.learned.shrinkRetainingCapacity(p.learned_before); p.pos.shrinkRetainingCapacity(p.pos_before); var i = p.taken.items.len; @@ -312,22 +329,32 @@ pub fn Pocket(comptime T: type) type { const k = p.taken.items[i]; @memset(p.neuron(p.up.items, k.slot, k.neuron, d), 0); @memset(p.neuron(p.down.items, k.slot, k.neuron, d), 0); + if (swiglu) @memset(p.neuron(p.gate.items, k.slot, k.neuron, d), 0); if (k.neuron + 1 == p.used.items[k.slot]) p.used.items[k.slot] -= 1; try p.upload(t, host, k.slot); } for (p.refits.items, 0..) |r, j| { @memcpy(p.neuron(p.up.items, r.slot, r.neuron, d), p.refit_up.items[j * d ..][0..d]); + if (swiglu) @memcpy(p.neuron(p.gate.items, r.slot, r.neuron, d), p.refit_gate.items[j * d ..][0..d]); try p.upload(t, host, r.slot); } p.refits.clearRetainingCapacity(); p.refit_up.clearRetainingCapacity(); try joint.putBack(p, t, host, d); + p.refit_gate.clearRetainingCapacity(); p.taken.clearRetainingCapacity(); } + /// Slot `slot`'s neurons into the forward: relu^2 as u, SwiGLU as its gate rows and up rows u / sharp. pub fn upload(p: *Self, t: *T, host: anytype, slot: usize) !void { - const n = neurons * t.config().hidden; - try host.pocket(p.moe.items[slot], p.up.items[slot * n ..][0..n], p.down.items[slot * n ..][0..n], p.used.items[slot]); + _ = t; + const n = neurons * p.hidden; + const up = p.up.items[slot * n ..][0..n]; + const down = p.down.items[slot * n ..][0..n]; + if (swiglu) { + neuron_math.upRow(F.neuron, up, p.scratch.items); + try host.pocketSwiglu(p.moe.items[slot], p.gate.items[slot * n ..][0..n], p.scratch.items, down, p.used.items[slot]); + } else try host.pocket(p.moe.items[slot], up, down, p.used.items[slot]); } /// Example i and its kind: the fact's answers, then its other wordings, held-out answers and the other prompts. @@ -356,8 +383,7 @@ pub fn Pocket(comptime T: type) type { /// Every key's candidate layers fitted in threads, the best taken; then keeps found, earlier neurons refitted. fn fitAll(p: *Self, t: *T, host: anytype) !bool { - const c = t.config(); - const d = c.hidden; + const d = p.hidden; const n = p.slots(); const m = p.labels.items.len; if (std.c.getenv("TF_SLIDE_POCKET_DUMP")) |dir| pocket_dump.write(p, std.mem.span(dir), p.learned_before, d) catch |e| std.log.warn("slide pocket: the read rows were not written: {t}", .{e}); @@ -372,14 +398,17 @@ pub fn Pocket(comptime T: type) type { defer p.gpa.free(fits); @memset(fits, .{ .fires = std.math.maxInt(usize) }); const t0 = clock.now(host.io); - var threads: [3 * 64]?std.Thread = @splat(null); + const threads = try p.gpa.alloc(?std.Thread, 3 * n); + defer p.gpa.free(threads); + @memset(threads, null); var fitted: usize = 0; - for (0..3) |k| for (p.moe.items, 0..) |l, j| if (p.split[k] > 0 and candidate(l, c.layers, @fromBackingInt(@intCast(k)))) { - threads[k * n + j] = std.Thread.spawn(.{}, fitLayer, .{ p.gpa, p.rows.items, kinds[k * m ..][0..m], n, j, d, us[(k * n + j) * d ..][0..d], &fits[k * n + j] }) catch null; + const below = F.neuron.margin; + for (0..3) |k| for (p.moe.items, 0..) |l, j| if (p.split[k] > 0 and candidate(l, p.layers, @fromBackingInt(@intCast(k)))) { + threads[k * n + j] = std.Thread.spawn(.{}, fitLayer, .{ p.gpa, p.rows.items, kinds[k * m ..][0..m], n, j, d, us[(k * n + j) * d ..][0..d], &fits[k * n + j], below }) catch null; fitted += 1; }; - for (0..3) |k| for (p.moe.items, 0..) |l, j| if (p.split[k] > 0 and candidate(l, c.layers, @fromBackingInt(@intCast(k)))) { - if (threads[k * n + j]) |th| th.join() else fitLayer(p.gpa, p.rows.items, kinds[k * m ..][0..m], n, j, d, us[(k * n + j) * d ..][0..d], &fits[k * n + j]); + for (0..3) |k| for (p.moe.items, 0..) |l, j| if (p.split[k] > 0 and candidate(l, p.layers, @fromBackingInt(@intCast(k)))) { + if (threads[k * n + j]) |th| th.join() else fitLayer(p.gpa, p.rows.items, kinds[k * m ..][0..m], n, j, d, us[(k * n + j) * d ..][0..d], &fits[k * n + j], below); }; const t1 = clock.now(host.io); for (0..3) |k| if (p.split[k] > 0) { @@ -387,14 +416,14 @@ pub fn Pocket(comptime T: type) type { var order: std.ArrayList(usize) = .empty; defer order.deinit(p.gpa); // a layer whose pocket is full is passed over - for (p.moe.items, 0..) |l, j| if (candidate(l, c.layers, key) and p.used.items[j] < neurons) try order.append(p.gpa, j); + for (p.moe.items, 0..) |l, j| if (candidate(l, p.layers, key) and p.used.items[j] < neurons) try order.append(p.gpa, j); if (order.items.len == 0) return error.PocketFull; std.mem.sort(usize, order.items, @as([]const Fit, fits[k * n ..][0..n]), better); for (order.items[0..@min(p.split[k], order.items.len)]) |j| try p.take(j, key, us[(k * n + j) * d ..][0..d], fits[k * n + j], kinds[k * m ..][0..m], d); }; p.logSources(d, m, kinds); try p.findKeeps(d); - try p.quiet(t, host); + try quieting.quiet(p, t, host); std.log.info("slide pocket: {d} candidate neurons fitted on {d} read rows in {d:.1} s; earlier neurons checked in {d:.1} s", .{ fitted, m, t1 - t0, clock.now(host.io) - t1 }); try joint.find(p, d); try p.v.begin(p.gpa, p.taken.items.len + p.joint.items.len, d, p.answered.len + p.joint_answers.items.len + p.keeps.items.len); @@ -430,6 +459,7 @@ pub fn Pocket(comptime T: type) type { p.used.items[j] += 1; try p.taken.append(p.gpa, .{ .slot = j, .neuron = k, .key = key }); @memcpy(p.neuron(p.up.items, j, k, d), u); + p.gateFrom(j, k); @memset(p.neuron(p.down.items, j, k, d), 0); std.log.info("slide pocket: layer {d}, neuron {d}, at the {s}: on for {d:.0}% of the fact's questions (least {d:.2}), held-out {d:.0}% (mean {d:.2}); other prompts at most {d:.2}, other rows {d:.2}, {d} above zero", .{ p.moe.items[j], k, @tagName(key), 100 * f.fact_on, f.fact_least, 100 * f.held_on, f.held_mean, f.steady_most, f.other_most, f.fires }); const start = p.pos.items.len / d; @@ -453,8 +483,7 @@ pub fn Pocket(comptime T: type) type { if (l.kind != .none or l.ex < p.answered.len + p.prompts.len + p.held.len) continue; var sum: f32 = 0; for (p.taken.items) |x| if (x.key == .subject) { - const z = dotBf16(p.neuron(p.up.items, x.slot, x.neuron, d), p.rows.items[(i * n + x.slot) * d ..][0..d]); - sum += if (z > 0) z * z else 0; + sum += @max(p.act(x.slot, x.neuron, p.rows.items[(i * n + x.slot) * d ..][0..d]), 0); }; if (sum > most) { most = sum; @@ -468,59 +497,23 @@ pub fn Pocket(comptime T: type) type { std.log.info("slide pocket: {d} other answers name the fact's subject where its neurons fire; they are to stay as they were", .{p.keeps.items.len}); } - /// Earlier neurons firing on this fact's rows refitted silent there, undo copies kept; same-subject ones stay. - fn quiet(p: *Self, t: *T, host: anytype) !void { - const d = t.config().hidden; - const n = p.slots(); - for (p.learned.items[0..p.learned_before]) |e| { - if (e.key == .subject and std.mem.indexOfScalar(u32, p.subjects.items, e.subject) != null) continue; - const u = p.neuron(p.up.items, e.slot, e.neuron, d); - var most: f32 = -std.math.inf(f32); - for (p.labels.items, 0..) |l, i| if (l.kind == .fact or l.kind == .held) { - most = @max(most, dotBf16(u, p.rows.items[(i * n + e.slot) * d ..][0..d])); - }; - if (most <= refit_above) continue; // weak there: left exactly as it is, this fact's outputs fitted with it - try p.refits.append(p.gpa, .{ .slot = e.slot, .neuron = e.neuron }); - try p.refit_up.appendSlice(p.gpa, u); - var xs: std.ArrayList([]const u16) = .empty; - defer xs.deinit(p.gpa); - var kinds: std.ArrayList(Kind) = .empty; - defer kinds.deinit(p.gpa); - for (0..e.count) |r| { - try xs.append(p.gpa, p.pos.items[(e.start + r) * d ..][0..d]); - try kinds.append(p.gpa, .fact); - } - for (p.labels.items, 0..) |l, i| { - try xs.append(p.gpa, p.rows.items[(i * n + e.slot) * d ..][0..d]); - try kinds.append(p.gpa, switch (l.kind) { - .fact, .held => .steady, // this fact's questions are another fact's to it - .none => .other, - else => l.kind, - }); - } - const f = try fit(p.gpa, xs.items, kinds.items, d, u, true, fit_steps / 2, e.count); - if (f.fact_least < kept_least or @max(f.steady_most, f.other_most) > 0) { - // a refit that forgets its fact or spreads is undone; this fact's outputs are fitted with it firing - @memcpy(u, p.refit_up.items[p.refit_up.items.len - d ..]); - p.refits.shrinkRetainingCapacity(p.refits.items.len - 1); - p.refit_up.shrinkRetainingCapacity(p.refit_up.items.len - d); - std.log.info("slide pocket: layer {d}, neuron {d}, an earlier fact's, fires on this fact's questions (up to {d:.2}); fitted again its own would read at least {d:.2} and other rows at most {d:.2}, so it stays as it was", .{ p.moe.items[e.slot], e.neuron, most, f.fact_least, @max(f.steady_most, f.other_most) }); - continue; - } - try p.upload(t, host, e.slot); - std.log.info("slide pocket: layer {d}, neuron {d}, an earlier fact's, fired on this fact's questions (up to {d:.2}); fitted again: there and elsewhere at most {d:.2}, its own questions' least {d:.2}", .{ p.moe.items[e.slot], e.neuron, most, @max(f.steady_most, f.other_most), f.fact_least }); - } - } - /// Whether no neuron is in use at any layer. pub fn empty(p: *const Self) bool { for (p.used.items) |u| if (u > 0) return false; return true; } - /// Learned neurons into the shards, then into the forward as the shards hold them (4-bit); the bytes written. + /// Learned neurons into the shards, then into the forward as the shards hold them (quantized); the bytes. pub fn save(p: *Self, t: *T, host: anytype) !usize { - const bytes = try host.pocketSave(p.moe.items, neurons, p.up.items, p.down.items); + const bytes = if (swiglu) blk: { + // written as gate rows and up rows u / sharp, handed back as written: u from the up rows again + const rows = try p.gpa.alloc(f32, p.up.items.len); + defer p.gpa.free(rows); + neuron_math.upRow(F.neuron, p.up.items, rows); + const got = try host.pocketSaveSwiglu(p.moe.items, neurons, p.gate.items, rows, p.down.items); + neuron_math.fromUp(F.neuron, rows, p.up.items); + break :blk got; + } else try host.pocketSave(p.moe.items, neurons, p.up.items, p.down.items); for (0..p.slots()) |j| if (p.used.items[j] > 0) try p.upload(t, host, j); return bytes; } @@ -559,7 +552,7 @@ pub fn Pocket(comptime T: type) type { } test "a fact keys as many neurons on its subject as the share of its questions that name it, at least half, else none" { - const P = Pocket(struct {}); + const P = Pocket(struct {}, @import("families.zig").nemotron_h); var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; defer p.deinit(); // ids: a question's tokens, the subject's last token at row 2, the answer from row 4 diff --git a/zig/src/living/pocket_fit.zig b/zig/src/living/pocket_fit.zig index 02c9d99493..ab37028d73 100644 --- a/zig/src/living/pocket_fit.zig +++ b/zig/src/living/pocket_fit.zig @@ -2,7 +2,7 @@ const std = @import("std"); const subspace = @import("subspace.zig"); -pub const margin: f32 = 0.25; // how far below zero a fact's neuron sits on rows it stays silent on +pub const margin: f32 = 0.25; // relu^2's margin (families.zig): how far below zero a neuron sits on rows it stays silent on pub const fit_steps = 500; // Adam steps fitting a neuron's input weights pub const fit_rate: f32 = 0.01; // their step, the inputs scaled to unit length @@ -21,7 +21,7 @@ pub const Fit = struct { }; /// Slot j's neuron fitted on its read rows, copied side by side first (a failure: zero, its slot last in line). -pub fn fitLayer(gpa: std.mem.Allocator, rows: []const u16, kinds: []const Kind, slots: usize, j: usize, d: usize, u: []f32, out: *Fit) void { +pub fn fitLayer(gpa: std.mem.Allocator, rows: []const u16, kinds: []const Kind, slots: usize, j: usize, d: usize, u: []f32, out: *Fit, below: f32) void { const own = gpa.alloc(u16, kinds.len * d) catch { out.* = .{ .fires = std.math.maxInt(usize) }; return; @@ -36,14 +36,14 @@ pub fn fitLayer(gpa: std.mem.Allocator, rows: []const u16, kinds: []const Kind, @memcpy(own[i * d ..][0..d], rows[(i * slots + j) * d ..][0..d]); x.* = own[i * d ..][0..d]; } - out.* = fit(gpa, xs, kinds, d, u, false, fit_steps, 0) catch blk: { + out.* = fit(gpa, xs, kinds, d, u, false, fit_steps, 0, below) catch blk: { @memset(u, 0); break :blk .{ .fires = std.math.maxInt(usize) }; }; } -/// Fits `u` on `xs` (from `u` if `warm`): at least 1 on fact rows, at most -margin elsewhere; first `fixed` rows kept. -pub fn fit(gpa: std.mem.Allocator, xs: []const []const u16, kinds: []const Kind, d: usize, u: []f32, warm: bool, steps: usize, fixed: usize) !Fit { +/// Fits `u` on `xs` (from `u` if `warm`): at least 1 on fact rows, at most -`below` elsewhere; first `fixed` rows kept. +pub fn fit(gpa: std.mem.Allocator, xs: []const []const u16, kinds: []const Kind, d: usize, u: []f32, warm: bool, steps: usize, fixed: usize, below: f32) !Fit { const n = kinds.len; var scale: f32 = 0; for (xs) |x| scale += @sqrt(squares(x)); @@ -93,10 +93,10 @@ pub fn fit(gpa: std.mem.Allocator, xs: []const []const u16, kinds: []const Kind, wrong[0] += 1; axpyRow(parts[0..d], -2 * (1 - z), x); }, - .steady, .other => if (z > -margin) { + .steady, .other => if (z > -below) { const at: usize = if (k == .steady) 1 else 2; wrong[at] += 1; - axpyRow(parts[at * d ..][0..d], 2 * (z + margin), x); + axpyRow(parts[at * d ..][0..d], 2 * (z + below), x); }, .held, .none => {}, } @@ -263,7 +263,7 @@ test "a neuron fires on its fact's rows and stays at zero on the rest; fitted ag k.* = if (i < n_fact) .fact else .other; } var u: [d]f32 = undefined; - const first = try fit(gpa, xs, kinds, d, &u, false, fit_steps, 0); + const first = try fit(gpa, xs, kinds, d, &u, false, fit_steps, 0, margin); try std.testing.expectEqual(@as(f32, 1), first.fact_on); try std.testing.expectEqual(@as(usize, 0), first.fires); // the new fact's rows, which nothing told it about, are where it is fitted again to stay quiet @@ -277,7 +277,7 @@ test "a neuron fires on its fact's rows and stays at zero on the rest; fitted ag } const before = try gpa.dupe(f32, &u); defer gpa.free(before); - const again = try fit(gpa, all, kinds2, d, &u, true, fit_steps / 2, n_fact); + const again = try fit(gpa, all, kinds2, d, &u, true, fit_steps / 2, n_fact, margin); try std.testing.expectEqual(@as(f32, 1), again.fact_on); try std.testing.expectEqual(@as(usize, 0), again.fires); try std.testing.expect(again.steady_most <= 0); diff --git a/zig/src/living/pocket_load.zig b/zig/src/living/pocket_load.zig new file mode 100644 index 0000000000..b76ec8d019 --- /dev/null +++ b/zig/src/living/pocket_load.zig @@ -0,0 +1,30 @@ +//! The pocket's neurons as the shards hold them, read once, at the layers the family's layout learns at. +const std = @import("std"); +const neuron_math = @import("neuron.zig"); + +/// The pocket's neurons as the shards hold them, read once, at the layers the family's layout learns at. +pub fn load(p: anytype, host: anytype) !void { + const P = @TypeOf(p.*); + if (p.moe.items.len > 0) return; + const lay = host.layout(); + if (lay.layers > 64) return error.TooManyLayers; // a step's nudges mark their layers in a u64 + p.hidden = lay.hidden; + p.layers = lay.layers; + for (0..lay.layers) |l| if (lay.learn.isSet(l)) try p.moe.append(p.gpa, l); + const n = P.neurons * lay.hidden; + try p.up.appendNTimes(p.gpa, 0, p.moe.items.len * n); + try p.down.appendNTimes(p.gpa, 0, p.moe.items.len * n); + try p.used.appendNTimes(p.gpa, 0, p.moe.items.len); + if (P.swiglu) { + try p.gate.appendNTimes(p.gpa, 0, p.moe.items.len * n); + try p.scratch.appendNTimes(p.gpa, 0, n); + } + for (p.moe.items, 0..) |l, j| { + const up = p.up.items[j * n ..][0..n]; + const down = p.down.items[j * n ..][0..n]; + if (P.swiglu) { + p.used.items[j] = host.pocketReadSwiglu(l, p.gate.items[j * n ..][0..n], p.scratch.items, down); + neuron_math.fromUp(P.of.neuron, p.scratch.items, up); + } else p.used.items[j] = host.pocketRead(l, up, down); + } +} diff --git a/zig/src/living/pocket_prefix.zig b/zig/src/living/pocket_prefix.zig index ca854f38ee..a5239724a4 100644 --- a/zig/src/living/pocket_prefix.zig +++ b/zig/src/living/pocket_prefix.zig @@ -88,7 +88,7 @@ pub fn learn(p: anytype, t: anytype, s: *Prefixes, sq: Seq, sp: Span, which: usi const k = &s.list.items[which]; if (k.seen or sq.skip > 0) return; k.seen = true; - const d = t.config().hidden; + const d = p.hidden; var limit = @min(sq.decide, sq.start - 1); for (sq.nudge.layers, sq.nudge.rows) |mask, row| if (mask != 0) { limit = @min(limit, row); diff --git a/zig/src/living/pocket_quiet.zig b/zig/src/living/pocket_quiet.zig new file mode 100644 index 0000000000..a1e2d70364 --- /dev/null +++ b/zig/src/living/pocket_quiet.zig @@ -0,0 +1,59 @@ +//! Earlier facts' neurons that fire on the open fact's questions, fitted again to stay silent there. +const std = @import("std"); +const pocket_fit = @import("pocket_fit.zig"); + +const Kind = pocket_fit.Kind; +const fit = pocket_fit.fit; +const dotBf16 = pocket_fit.dotBf16; +const fit_steps = pocket_fit.fit_steps; + +pub const kept_least: f32 = 0.5; // an earlier neuron refitted must still reach this on every one of its own fact's rows +pub const refit_above: f32 = 0.5; // an earlier neuron is refitted only where it fires above this on a new fact's rows + +/// Earlier neurons firing on this fact's rows refitted silent there, undo copies kept; same-subject ones stay. +pub fn quiet(p: anytype, t: anytype, host: anytype) !void { + const P = @TypeOf(p.*); + const d = p.hidden; + const n = p.moe.items.len; + for (p.learned.items[0..p.learned_before]) |e| { + if (e.key == .subject and std.mem.indexOfScalar(u32, p.subjects.items, e.subject) != null) continue; + const u = p.neuron(p.up.items, e.slot, e.neuron, d); + var most: f32 = -std.math.inf(f32); + for (p.labels.items, 0..) |l, i| if (l.kind == .fact or l.kind == .held) { + most = @max(most, dotBf16(u, p.rows.items[(i * n + e.slot) * d ..][0..d])); + }; + if (most <= refit_above) continue; // weak there: left exactly as it is, this fact's outputs fitted with it + try p.refits.append(p.gpa, .{ .slot = e.slot, .neuron = e.neuron }); + try p.refit_up.appendSlice(p.gpa, u); + if (P.swiglu) try p.refit_gate.appendSlice(p.gpa, p.neuron(p.gate.items, e.slot, e.neuron, d)); + var xs: std.ArrayList([]const u16) = .empty; + defer xs.deinit(p.gpa); + var kinds: std.ArrayList(Kind) = .empty; + defer kinds.deinit(p.gpa); + for (0..e.count) |r| { + try xs.append(p.gpa, p.pos.items[(e.start + r) * d ..][0..d]); + try kinds.append(p.gpa, .fact); + } + for (p.labels.items, 0..) |l, i| { + try xs.append(p.gpa, p.rows.items[(i * n + e.slot) * d ..][0..d]); + try kinds.append(p.gpa, switch (l.kind) { + .fact, .held => .steady, // this fact's questions are another fact's to it + .none => .other, + else => l.kind, + }); + } + const f = try fit(p.gpa, xs.items, kinds.items, d, u, true, fit_steps / 2, e.count, P.of.neuron.margin); + if (f.fact_least < kept_least or @max(f.steady_most, f.other_most) > 0) { + // a refit that forgets its fact or spreads is undone; this fact's outputs are fitted with it firing + @memcpy(u, p.refit_up.items[p.refit_up.items.len - d ..]); + p.refits.shrinkRetainingCapacity(p.refits.items.len - 1); + p.refit_up.shrinkRetainingCapacity(p.refit_up.items.len - d); + if (P.swiglu) p.refit_gate.shrinkRetainingCapacity(p.refit_gate.items.len - d); + std.log.info("slide pocket: layer {d}, neuron {d}, an earlier fact's, fires on this fact's questions (up to {d:.2}); fitted again its own would read at least {d:.2} and other rows at most {d:.2}, so it stays as it was", .{ p.moe.items[e.slot], e.neuron, most, f.fact_least, @max(f.steady_most, f.other_most) }); + continue; + } + p.gateFrom(e.slot, e.neuron); + try p.upload(t, host, e.slot); + std.log.info("slide pocket: layer {d}, neuron {d}, an earlier fact's, fired on this fact's questions (up to {d:.2}); fitted again: there and elsewhere at most {d:.2}, its own questions' least {d:.2}", .{ p.moe.items[e.slot], e.neuron, most, @max(f.steady_most, f.other_most), f.fact_least }); + } +} diff --git a/zig/src/living/pocket_read.zig b/zig/src/living/pocket_read.zig index 77d9bcd9dc..246652d6e3 100644 --- a/zig/src/living/pocket_read.zig +++ b/zig/src/living/pocket_read.zig @@ -37,6 +37,7 @@ fn state(p: anytype) u64 { h.update(std.mem.sliceAsBytes(p.up.items)); h.update(std.mem.sliceAsBytes(p.down.items)); h.update(std.mem.sliceAsBytes(p.used.items)); + if (@TypeOf(p.*).swiglu) h.update(std.mem.sliceAsBytes(p.gate.items)); return h.final(); } diff --git a/zig/src/living/pocket_values.zig b/zig/src/living/pocket_values.zig index 628ce8f265..46b1a96acb 100644 --- a/zig/src/living/pocket_values.zig +++ b/zig/src/living/pocket_values.zig @@ -131,8 +131,7 @@ const Drawn = struct { own: bool, joint: bool = false, which: usize, seq: Seq }; /// One output step: its fact answers, then those that are to stay, side by side; then Adam, and every few the judge. pub fn valueOnce(p: anytype, t: anytype, host: anytype) !bool { const s = &p.v; - const c = t.config(); - const d = c.hidden; + const d = p.hidden; const k = p.taken.items.len + p.joint.items.len; // the open fact's neurons, then the earlier ones fitted with them const vals = s.adam.items[0 .. k * d]; const grad = s.adam.items[3 * k * d ..][0 .. k * d]; @@ -253,8 +252,7 @@ pub fn valueOnce(p: anytype, t: anytype, host: anytype) !bool { /// Answer `dr`, the pass's i-th, into the step: its loss, and each neuron's push times its activation at its row. fn absorb(p: anytype, t: anytype, dr: Drawn, i: usize, got: Result, grad: []f32) void { const s = &p.v; - const c = t.config(); - const d = c.hidden; + const d = p.hidden; const masks = dr.seq.nudge.layers; const rows = dr.seq.nudge.rows; const sp = t.spans[i]; @@ -276,8 +274,10 @@ fn absorb(p: anytype, t: anytype, dr: Drawn, i: usize, got: Result, grad: []f32) const key = @backingInt(x.key); if (masks[key] == 0) continue; const l = p.moe.items[x.slot]; - const z = dotBf16(p.neuron(p.up.items, x.slot, x.neuron, d), t.normed(l, sp.row(rows[key]))); - const a = if (z > 0) z * z else 0; + const row = sp.row(rows[key]); + // relu(u x)^2, or a SwiGLU's silu(g x) (u x) / sharp; times its expert's gate there when one scales it + var a = p.act(x.slot, x.neuron, t.normed(l, row)); + if (@TypeOf(p.*).gated) a *= t.gateAt(l, row); subspace.axpy(grad[j * d ..][0..d], dr.seq.scale * a, t.pushAt(i, key, l)); if (dr.own and s.size.items[j] == 0) s.size.items[j] = normBf16(t.residual(l + 1, sp.row(rows[key]))); } @@ -358,7 +358,7 @@ fn judgeOnce(p: anytype, t: anytype, host: anytype, vals: []f32) !bool { /// The outputs into the pocket's neurons and the forward; the held-out answers judged next. fn finish(p: anytype, t: anytype, host: anytype, vals: []const f32) !bool { const s = &p.v; - const d = t.config().hidden; + const d = p.hidden; try put(p, t, host, vals, d); t.from = @splat(std.math.maxInt(u32)); std.log.info("slide pocket: {d} answers' first rows run once, {d} rows the steps did not run again", .{ s.prefixes.slots, s.prefixes.skipped }); @@ -395,9 +395,9 @@ pub fn checkOnce(p: anytype, t: anytype, host: anytype) !bool { return true; } -/// Logs the forward's change after the fact's lowest neuron on `ex` against its relu(u x)^2 v, to spot a bad forward. +/// Logs the forward's change after the fact's lowest neuron on `ex` against its act(x) v, to spot a bad forward. fn verifyForward(p: anytype, t: anytype, host: anytype, ex: Example) !void { - const d = t.config().hidden; + const d = p.hidden; var low: ?std.meta.Elem(@TypeOf(p.taken.items)) = null; var row: usize = 0; for (p.taken.items) |x| { @@ -420,8 +420,8 @@ fn verifyForward(p: anytype, t: anytype, host: anytype, ex: Example) !void { t.nudge = .{}; _ = try t.step(ex.ids, ex.start, .target, turn); for (with, t.residual(l + 1, row)) |*o, b| o.* = @bitCast(@as(u32, b) << 16); - const z = dotBf16(p.neuron(p.up.items, k.slot, k.neuron, d), t.normed(l, row)); - const a = if (z > 0) z * z else 0; + var a = p.act(k.slot, k.neuron, t.normed(l, row)); + if (@TypeOf(p.*).gated) a *= t.gateAt(l, row); const v = p.neuron(p.down.items, k.slot, k.neuron, d); for (want, v) |*o, x| o.* = a * x; @memcpy(saved, v); diff --git a/zig/src/living/probe.zig b/zig/src/living/probe.zig index 1175275c7a..1d2089f2ec 100644 --- a/zig/src/living/probe.zig +++ b/zig/src/living/probe.zig @@ -1,4 +1,4 @@ -//! A measure, not a lesson: how far vectors fitted at one row of a few layers bring a fact's held-out answers back. +//! A measure, not a lesson: how far vectors fitted at a few layers bring a fact back (Nemotron's Metal trainer only). const std = @import("std"); const examples = @import("lesson_examples.zig"); const lesson_route = @import("lesson_route.zig"); diff --git a/zig/src/living/shards.zig b/zig/src/living/shards.zig new file mode 100644 index 0000000000..f0899b8de6 --- /dev/null +++ b/zig/src/living/shards.zig @@ -0,0 +1,211 @@ +//! The pocket in the shards, for any family: every shared expert widened once (config.json told), then in place. +const std = @import("std"); +const family = @import("family.zig"); +const affine = @import("affine.zig"); +const Family = family.Family; +const Layout = family.Layout; + +/// The writer over `core`, the backend's own (its shard_edit and safetensors). +pub fn Io(comptime core: type) type { + const st = core.safetensors; + const se = core.shard_edit; + return struct { + /// The learned neurons of `layers` into `dir`'s shards, quantized as `F` stores them, handed back; the bytes. + pub fn write(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, comptime F: Family, lay: Layout, layers: []const usize, neurons: usize, inputs: []const []f32, down: []f32) !usize { + const q = F.quant; + const d = lay.hidden; + const own = lay.width; + if (inputs.len != F.names.inputs.len) return error.BadPocket; + if (neurons % q.group != 0 or d % q.group != 0 or own % q.group != 0) return error.BadPocket; + const has = try se.configIntIn(gpa, io, dir, F.keys.scope, F.keys.pocket); + const widen = has == null; + if (has) |n| if (n != neurons) return error.PocketOfAnotherSize; + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + var files: Files = .{ .gpa = gpa, .io = io, .dir = dir, .paths = .init(gpa) }; + defer files.close(); + var edits: std.ArrayList(se.Replacement) = .empty; + var bytes: usize = 0; + const n = neurons * d; + var rows: [F.names.inputs.len][]f32 = undefined; + for (0..lay.layers) |l| { + if (!lay.widen.isSet(l)) continue; + const at = std.mem.indexOfScalar(usize, layers, l); + for (&rows, inputs) |*r, x| r.* = if (at) |j| x[j * n ..][0..n] else try zeros(arena, n); + const v = if (at) |j| down[j * n ..][0..n] else try zeros(arena, n); + var buf: [160]u8 = undefined; + bytes += try expert(F, arena, &files, &edits, try F.expertBase(&buf, l), own, neurons, d, &rows, v); + } + const mtp = if (widen) F.names.mtp else null; + const z = try zeros(arena, n); + var zs: [F.names.inputs.len][]f32 = @splat(z); + if (mtp) |m| if (m.file == null and try files.indexed(try std.fmt.allocPrint(arena, "{s}{s}.weight", .{ m.base, F.names.inputs[0] }))) { + // the MTP head's expert in the index: grown with the model's own, zero neurons + bytes += try expert(F, arena, &files, &edits, m.base, own, neurons, d, &zs, z); + }; + if (widen) try se.grow(gpa, io, dir, edits.items) else try se.overwrite(gpa, io, dir, edits.items); + if (mtp) |m| if (m.file) |name| { + // in its own file, zero neurons: that file rewritten whole, apart from the index + const path = try std.fs.path.join(arena, &.{ dir, name }); + if (hasMtp(F, gpa, io, path, m.base)) { + var only: std.ArrayList(se.Replacement) = .empty; + var single: Files = .{ .gpa = gpa, .io = io, .dir = dir, .single = path, .paths = .init(gpa) }; + defer single.close(); + bytes += try expert(F, arena, &single, &only, m.base, own, neurons, d, &zs, z); + _ = try se.rewrite(gpa, io, path, only.items); + } + }; + if (widen) try se.setConfigIn(gpa, io, dir, F.keys.scope, &.{ .{ F.keys.width, @intCast(own + neurons) }, .{ F.keys.pocket, @intCast(neurons) } }); + return bytes; + } + + fn hasMtp(comptime F: Family, gpa: std.mem.Allocator, io: std.Io, path: []const u8, base: []const u8) bool { + var f = st.File.open(gpa, io, path) catch return false; + defer f.close(io); + var buf: [192]u8 = undefined; + const name = std.fmt.bufPrint(&buf, "{s}{s}.weight", .{ base, F.names.inputs[0] }) catch return false; + return f.get(name) != null; + } + + /// The shard files a model's tensors are read from: the index's, or one file (an MTP head's own). + const Files = struct { + gpa: std.mem.Allocator, + io: std.Io, + dir: []const u8, + single: ?[]const u8 = null, + open: std.StringArrayHashMapUnmanaged(st.File) = .empty, + paths: std.heap.ArenaAllocator, + map: ?std.json.Parsed(std.json.Value) = null, + + fn get(fs: *Files, name: []const u8) !st.Tensor { + const shard = if (fs.single) |x| x else try fs.shardOf(name); + const slot = try fs.open.getOrPut(fs.gpa, shard); + if (!slot.found_existing) slot.value_ptr.* = st.File.open(fs.gpa, fs.io, shard) catch |e| { + _ = fs.open.pop(); + return e; + }; + return slot.value_ptr.get(name) orelse error.MissingTensor; + } + + /// Whether the folder's index (or its one shard) holds `name`. + fn indexed(fs: *Files, name: []const u8) !bool { + _ = fs.get(name) catch |e| return if (e == error.MissingTensor) false else e; + return true; + } + + /// The path of the shard holding `name`, kept until the files close. + fn shardOf(fs: *Files, name: []const u8) ![]const u8 { + const a = fs.paths.allocator(); + if (fs.map == null) { + const path = try std.fs.path.join(a, &.{ fs.dir, "model.safetensors.index.json" }); + const text = std.Io.Dir.cwd().readFileAlloc(fs.io, path, a, .limited(1 << 26)) catch |e| if (e == error.FileNotFound) { + fs.single = try std.fs.path.join(a, &.{ fs.dir, "model.safetensors" }); + return fs.single.?; + } else return e; + fs.map = try std.json.parseFromSlice(std.json.Value, fs.gpa, text, .{ .allocate = .alloc_always }); + } + const root = fs.map.?.value; + if (root != .object) return error.BadIndex; + const weights = root.object.get("weight_map") orelse return error.BadIndex; + if (weights != .object) return error.BadIndex; + const file = weights.object.get(name) orelse return error.MissingTensor; + if (file != .string) return error.BadIndex; + return std.fs.path.join(a, &.{ fs.dir, file.string }); + } + + fn close(fs: *Files) void { + for (fs.open.values()) |*f| f.close(fs.io); + fs.open.deinit(fs.gpa); + if (fs.map) |*x| x.deinit(); + fs.paths.deinit(); + } + }; + + /// One shared expert with `neurons` learned after its `own`: a row a neuron per input, a column out; the bytes. + fn expert(comptime F: Family, arena: std.mem.Allocator, files: *Files, edits: *std.ArrayList(se.Replacement), base: []const u8, own: usize, neurons: usize, d: usize, inputs: []const []f32, v: []f32) !usize { + const q = F.quant; + const g = q.group; + const wide = own + neurons; + const per_word = 32 / q.bits; + var name: [192]u8 = undefined; + var bytes: usize = 0; + var had: ?usize = null; // the input projections' rows: `own`, or `wide` once widened + for (F.names.inputs, inputs) |proj, x| { + var parts: [3]st.Tensor = undefined; + for (&parts, [_][]const u8{ "weight", "scales", "biases" }) |*t, leaf| t.* = try files.get(try std.fmt.bufPrint(&name, "{s}{s}.{s}", .{ base, proj, leaf })); + const rows_had = parts[0].dim(0); + if (rows_had != own and rows_had != wide) return error.UnexpectedTensor; + if (had) |h| if (h != rows_had) return error.UnexpectedTensor; + had = rows_had; + const w = try arena.alloc(u32, wide * d / per_word); + const s = try arena.alloc(u16, wide * d / g); + const b = try arena.alloc(u16, wide * d / g); + @memcpy(w[0 .. own * d / per_word], words(parts[0].bytes)[0 .. own * d / per_word]); + @memcpy(s[0 .. own * d / g], halves(parts[1].bytes)[0 .. own * d / g]); + @memcpy(b[0 .. own * d / g], halves(parts[2].bytes)[0 .. own * d / g]); + for (0..neurons) |k| { + const r = own + k; + const row = x[k * d ..][0..d]; + const rw = w[r * d / per_word ..][0 .. d / per_word]; + const rs = s[r * d / g ..][0 .. d / g]; + const rb = b[r * d / g ..][0 .. d / g]; + affine.quantize(q, row, rw, rs, rb); + affine.dequantize(q, rw, rs, rb, row); + } + bytes += try add(arena, edits, base, proj, .{ wide, d }, w, s, b, q); + } + // the output projection: each output row's own columns as they are, then a column a learned neuron + var parts: [3]st.Tensor = undefined; + for (&parts, [_][]const u8{ "weight", "scales", "biases" }) |*t, leaf| t.* = try files.get(try std.fmt.bufPrint(&name, "{s}{s}.{s}", .{ base, F.names.output, leaf })); + const cols = had.?; // as wide as the input projections had rows + const dw = try arena.alloc(u32, d * wide / per_word); + const ds = try arena.alloc(u16, d * wide / g); + const db = try arena.alloc(u16, d * wide / g); + const col = try arena.alloc(f32, neurons); + for (0..d) |o| { + @memcpy(dw[o * wide / per_word ..][0 .. own / per_word], words(parts[0].bytes)[o * cols / per_word ..][0 .. own / per_word]); + @memcpy(ds[o * wide / g ..][0 .. own / g], halves(parts[1].bytes)[o * cols / g ..][0 .. own / g]); + @memcpy(db[o * wide / g ..][0 .. own / g], halves(parts[2].bytes)[o * cols / g ..][0 .. own / g]); + for (col, 0..) |*x, k| x.* = v[k * d + o]; + const cw = dw[o * wide / per_word ..][own / per_word ..][0 .. neurons / per_word]; + const cs = ds[o * wide / g ..][own / g ..][0 .. neurons / g]; + const cb = db[o * wide / g ..][own / g ..][0 .. neurons / g]; + affine.quantize(q, col, cw, cs, cb); + affine.dequantize(q, cw, cs, cb, col); + for (col, 0..) |x, k| v[k * d + o] = x; + } + bytes += try add(arena, edits, base, F.names.output, .{ d, wide }, dw, ds, db, q); + return bytes; + } + + /// A projection's codes, scales and biases ([rows, cols] values) as three replacements; their bytes. + fn add(arena: std.mem.Allocator, edits: *std.ArrayList(se.Replacement), base: []const u8, proj: []const u8, shape: [2]usize, w: []const u32, s: []const u16, b: []const u16, comptime q: family.Quant) !usize { + const made = [_]struct { leaf: []const u8, dtype: st.DType, shape: [2]usize, bytes: []const u8 }{ + .{ .leaf = "weight", .dtype = .u32, .shape = .{ shape[0], shape[1] * q.bits / 32 }, .bytes = std.mem.sliceAsBytes(w) }, + .{ .leaf = "scales", .dtype = .bf16, .shape = .{ shape[0], shape[1] / q.group }, .bytes = std.mem.sliceAsBytes(s) }, + .{ .leaf = "biases", .dtype = .bf16, .shape = .{ shape[0], shape[1] / q.group }, .bytes = std.mem.sliceAsBytes(b) }, + }; + var bytes: usize = 0; + for (made) |m| { + try edits.append(arena, .{ .name = try std.fmt.allocPrint(arena, "{s}{s}.{s}", .{ base, proj, m.leaf }), .dtype = m.dtype, .shape = try arena.dupe(usize, &m.shape), .bytes = m.bytes }); + bytes += m.bytes.len; + } + return bytes; + } + }; +} + +fn zeros(arena: std.mem.Allocator, n: usize) ![]f32 { + const z = try arena.alloc(f32, n); + @memset(z, 0); + return z; +} + +fn words(bytes: []const u8) []align(1) const u32 { + return std.mem.bytesAsSlice(u32, bytes); +} + +fn halves(bytes: []const u8) []align(1) const u16 { + return std.mem.bytesAsSlice(u16, bytes); +} diff --git a/zig/src/living/swiglu_test.zig b/zig/src/living/swiglu_test.zig new file mode 100644 index 0000000000..994a52f8c3 --- /dev/null +++ b/zig/src/living/swiglu_test.zig @@ -0,0 +1,82 @@ +//! A SwiGLU pocket neuron on the host: fitted, written in 4-bit groups of 32 and read back, it fires as relu^2 would. +const std = @import("std"); +const pocket_fit = @import("pocket_fit.zig"); +const neuron = @import("neuron.zig"); +const affine = @import("affine.zig"); +const families = @import("families.zig"); + +const f = @import("test_families.zig").swiglu; +const d = 128; + +fn bf(x: f32) u16 { + return @truncate(@as(u32, @bitCast(x)) >> 16); +} + +fn dot(a: []const f32, b: []const u16) f32 { + return pocket_fit.dotBf16(a, b); +} + +/// `x` written and read back as the family stores its experts. +fn stored(x: []f32) void { + var w: [affine.wordsOf(f.quant, d)]u32 = undefined; + var s: [d / f.quant.group]u16 = undefined; + var b: [d / f.quant.group]u16 = undefined; + affine.quantize(f.quant, x, &w, &s, &b); + affine.dequantize(f.quant, &w, &s, &b, x); +} + +test "a SwiGLU neuron fitted at margin 0.5 and stored at 4 bits in groups of 32 fires on its rows and stays near zero elsewhere" { + const gpa = std.testing.allocator; + var prng = std.Random.DefaultPrng.init(21); + const r = prng.random(); + var common: [d]f32 = undefined; + var lean: [d]f32 = undefined; + for (&common, &lean) |*c, *l| { + c.* = 1 + r.floatNorm(f32) * 0.1; + l.* = r.floatNorm(f32); + } + const n_fact = 16; + const n_rest = 300; + const rows = try gpa.alloc(u16, (n_fact + n_rest) * d); + defer gpa.free(rows); + const xs = try gpa.alloc([]const u16, n_fact + n_rest); + defer gpa.free(xs); + const kinds = try gpa.alloc(pocket_fit.Kind, n_fact + n_rest); + defer gpa.free(kinds); + for (0..n_fact + n_rest) |i| { + for (0..d) |k| { + var v = common[k] + r.floatNorm(f32) * 0.5; + if (i < n_fact) v += 1.5 * lean[k]; + rows[i * d + k] = bf(v); + } + xs[i] = rows[i * d ..][0..d]; + kinds[i] = if (i < n_fact) .fact else .other; + } + var u: [d]f32 = undefined; + const got = try pocket_fit.fit(gpa, xs, kinds, d, &u, false, pocket_fit.fit_steps, 0, f.neuron.margin); + try std.testing.expectEqual(@as(f32, 1), got.fact_on); + try std.testing.expectEqual(@as(usize, 0), got.fires); + try std.testing.expect(@max(got.steady_most, got.other_most) <= -f.neuron.margin + 0.05); + // as the forward and the shards hold it: gate row sharp u, up row u / sharp, each quantized + var g: [d]f32 = undefined; + var w: [d]f32 = undefined; + neuron.gateRow(f.neuron, &u, &g); + neuron.upRow(f.neuron, &u, &w); + stored(&g); + stored(&w); + var least: f32 = std.math.inf(f32); + var most: f32 = 0; + for (xs, kinds) |x, k| { + const a = neuron.silu(dot(&g, x)) * dot(&w, x); + if (k == .fact) { + least = @min(least, a); + // within a hair of relu(u x)^2 on its own rows, but for the rows' quantization + try std.testing.expectApproxEqRel(neuron.act(.{ .act = .relu2 }, dot(&u, x), 0), a, 0.15); + } else most = @max(most, @abs(a)); + } + try std.testing.expect(least >= 0.7); + try std.testing.expect(most <= 1e-3 * least); + // the same rows through act(): u x and g x as the pocket reads them + const x = xs[0]; + try std.testing.expectApproxEqRel(neuron.silu(dot(&g, x)) * dot(&w, x), neuron.act(f.neuron, f.neuron.sharp * dot(&w, x), dot(&g, x)), 1e-5); +} diff --git a/zig/src/living/test_families.zig b/zig/src/living/test_families.zig new file mode 100644 index 0000000000..89a9255cf1 --- /dev/null +++ b/zig/src/living/test_families.zig @@ -0,0 +1,18 @@ +//! A family for tests: a SwiGLU shared expert shaped as Qwen3.8 Flash Next's, which no checkpoint learns into yet. +const Family = @import("family.zig").Family; + +/// A SwiGLU shared expert at every layer, gated by its own router logit, in 4-bit groups of 32, keys under text_config. +pub const swiglu: Family = .{ + .model_type = "swiglu_test", + .names = .{ + .layers = "language_model.model.layers.", + .expert = "mlp.shared_expert.", + .inputs = &.{ "gate_proj", "up_proj" }, + .mtp = .{ .base = "language_model.mtp.layers.0.mlp.shared_expert." }, + }, + // silu(gate) is not zero below it as relu is: a wider margin keeps sigmoid(-16 * 0.5) = 3e-4 of it there + .neuron = .{ .act = .swiglu, .gated = true, .margin = 0.5, .sharp = 16 }, + .quant = .{ .bits = 4, .group = 32 }, + .keys = .{ .scope = "text_config", .width = "shared_expert_intermediate_size" }, + .experts = .every, +}; diff --git a/zig/src/living/whole.zig b/zig/src/living/whole.zig index 4fa4a9fc01..f6a5b34ad0 100644 --- a/zig/src/living/whole.zig +++ b/zig/src/living/whole.zig @@ -46,6 +46,24 @@ pub fn Hooks(comptime H: type) type { pub fn pocketSave(f: Self, layers: []const usize, neurons: usize, up: []f32, down: []f32) !usize { return H.pocketSave(f.b, f.gpa, f.io, layers, neurons, up, down); } + + /// The served checkpoint's layout: where pockets sit and learn, its width (family.zig). + pub fn layout(f: Self) @import("family.zig").Layout { + return H.layout(f.b); + } + + /// A SwiGLU family's layer `layer` for the forward: gate rows, up rows (u / sharp) and outputs, [neurons, D]. + pub fn pocketSwiglu(f: Self, layer: usize, gate: []const f32, up: []const f32, down: []const f32, used: usize) !void { + return H.pocketSwiglu(f.b, layer, gate, up, down, used); + } + + pub fn pocketReadSwiglu(f: Self, layer: usize, gate: []f32, up: []f32, down: []f32) usize { + return H.pocketReadSwiglu(f.b, layer, gate, up, down); + } + + pub fn pocketSaveSwiglu(f: Self, layers: []const usize, neurons: usize, gate: []f32, up: []f32, down: []f32) !usize { + return H.pocketSaveSwiglu(f.b, f.gpa, f.io, layers, neurons, gate, up, down); + } }; } diff --git a/zig/src/living_shards_test.zig b/zig/src/living_shards_test.zig new file mode 100644 index 0000000000..555e672295 --- /dev/null +++ b/zig/src/living_shards_test.zig @@ -0,0 +1,32 @@ +//! Living Weights' pocket in each family's own shards, rooted here so the tests reach the core's shard files by path. +const std = @import("std"); +const living = @import("living"); +const host4 = @import("core/affine4_host.zig"); + +test { + _ = @import("families/nemotron/pocket_shards_test.zig"); +} + +test "living's affine writer at 4 bits in groups of 64 writes the very codes, scales and biases affine4_host does" { + const q: living.family.Quant = .{ .bits = 4, .group = 64 }; + var prng = std.Random.DefaultPrng.init(3); + const r = prng.random(); + var values: [8 * 64]f32 = undefined; + for (&values, 0..) |*v, i| v.* = if (i / 64 == 5) 0.125 else r.floatNorm(f32) * 0.07; + var w1: [values.len / 8]u32 = undefined; + var w2: [values.len / 8]u32 = undefined; + var s1: [8]u16 = undefined; + var s2: [8]u16 = undefined; + var b1: [8]u16 = undefined; + var b2: [8]u16 = undefined; + host4.quantize(&values, &w1, &s1, &b1); + living.affine.quantize(q, &values, &w2, &s2, &b2); + try std.testing.expectEqualSlices(u32, &w1, &w2); + try std.testing.expectEqualSlices(u16, &s1, &s2); + try std.testing.expectEqualSlices(u16, &b1, &b2); + var o1: [values.len]f32 = undefined; + var o2: [values.len]f32 = undefined; + host4.dequantize(&w1, &s1, &b1, &o1); + living.affine.dequantize(q, &w2, &s2, &b2, &o2); + try std.testing.expectEqualSlices(f32, &o1, &o2); +} diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 851f919480..4ea912da72 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -7,7 +7,7 @@ const nemotron = @import("nemotron"); const Allocator = std.mem.Allocator; const budget = @import("cuda_memory.zig"); const lane_backend = @import("cuda_bound.zig"); -const nemotron_slide = @import("nemotron_slide.zig"); +const slide_adapter = @import("slide_adapter.zig"); /// CUDA families provide metadata, open their lane backend and explain their refusals. const registry = .{nemotron.native}; @@ -269,11 +269,13 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O return null; }; if (o.slide) { + // a family learns once its module declares `slide` (its learner), `learnModel` and `linked` if (!@hasDecl(F, "slide")) { problem.* = try std.fmt.allocPrint(a, "--slide: {s} checkpoints do not learn on CUDA yet", .{o.model_type}); return null; } - if (try nemotron_slide.refusal(F, a, io, o.dir, "`cp -RL` (a copy that follows links)")) |why| { + comptime if (!@hasDecl(F, "learnModel") or !@hasDecl(F, "linked")) @compileError(F.model_type ++ " declares slide without learnModel and linked"); + if (try slide_adapter.refusal(F, a, io, o.dir, "`cp -RL` (a copy that follows links)")) |why| { problem.* = why; return null; } @@ -365,7 +367,7 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O gpa.destroy(store); }; if (loaded.learns != null) { - const Slide = nemotron_slide.Adapter(F.slide); + const Slide = slide_adapter.Adapter(F.slide); h.dir = try gpa.dupe(u8, o.dir); const s = try gpa.create(Slide); s.* = Slide.init(gpa, io, F.learnModel(loaded.ctx, h.dir)); diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index 39fe531408..f52361af10 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -10,8 +10,8 @@ const qwen27 = @import("qwen27_served.zig"); const flashnext = @import("flashnext_host.zig"); const glm = @import("glm_host.zig"); const glm_dsa = @import("glm_dsa_host.zig"); -const nemotron_slide = @import("nemotron_slide.zig"); -const Slide = nemotron_slide.Adapter(nemotron.slide); +const slide_adapter = @import("slide_adapter.zig"); +const Slide = slide_adapter.Adapter(nemotron.slide); const cache_fit = @import("cache_fit.zig"); pub const backends: []const []const u8 = &.{"metal"}; @@ -119,7 +119,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c problem.* = try std.fmt.allocPrint(a, "the native engine has no backend for {s} checkpoints yet; the Python engine 0.6.6 may serve them: python -m pip install git+https://github.com/ashhart/TensorFold.git@v0.6.6", .{o.model_type}); return null; } - if (o.slide) if (try nemotron_slide.refusal(tf.shard_edit, a, io, o.dir, "`cp -cRL` (an APFS clone that follows links)")) |why| { + if (o.slide) if (try slide_adapter.refusal(tf.shard_edit, a, io, o.dir, "`cp -cRL` (an APFS clone that follows links)")) |why| { problem.* = why; return null; }; diff --git a/zig/src/native/nemotron_slide.zig b/zig/src/native/slide_adapter.zig similarity index 90% rename from zig/src/native/nemotron_slide.zig rename to zig/src/native/slide_adapter.zig index 157c89e425..39ab12037d 100644 --- a/zig/src/native/nemotron_slide.zig +++ b/zig/src/native/slide_adapter.zig @@ -1,4 +1,4 @@ -//! Nemotron's Sliding Weights learner behind the lane host's learn hook: lessons in, learn events out. +//! A family's Living Weights learner behind the lane host's learn hook: lessons in, learn events out. const std = @import("std"); const api = @import("engine_api"); const Allocator = std.mem.Allocator; @@ -6,9 +6,9 @@ const Allocator = std.mem.Allocator; /// Neurons a learn event carries at most; a fact takes about ten. const max_neurons = 64; -/// Why --slide cannot learn into `dir` (`Checks`: its plainShared and linked; `copy`: the copy to make), or null. +/// Why --slide cannot learn into `dir` (`Checks`: linked and plainShared files; `copy`: the copy to make), or null. pub fn refusal(comptime Checks: type, a: Allocator, io: std.Io, dir: []const u8, copy: []const u8) !?[]const u8 { - if (try Checks.plainShared(a, io, dir)) |name| return try std.fmt.allocPrint(a, "--slide adds learned neurons beside every shared expert, and {s} in {s} is unquantized, as TensorFold 1.0.3 to 1.0.6 saved their lessons: serve this folder without --slide (what it learned stays), or teach a fresh copy", .{ name, dir }); + if (@hasDecl(Checks, "plainShared")) if (try Checks.plainShared(a, io, dir)) |name| return try std.fmt.allocPrint(a, "--slide adds learned neurons beside every shared expert, and {s} in {s} is unquantized, as TensorFold 1.0.3 to 1.0.6 saved their lessons: serve this folder without --slide (what it learned stays), or teach a fresh copy", .{ name, dir }); if (try Checks.linked(a, io, dir)) |name| return try std.fmt.allocPrint(a, "--slide rewrites the model's own files, and {s} in {s} is a link to data another file shares (a Hugging Face cache's blob, or a hard link), so learning would change that file too: serve a copy made with {s}", .{ name, dir, copy }); return null; } diff --git a/zig/src/server/slide_model.zig b/zig/src/server/slide_model.zig index 274f9bb59b..db94df3e69 100644 --- a/zig/src/server/slide_model.zig +++ b/zig/src/server/slide_model.zig @@ -1,6 +1,8 @@ -//! The served model as the Sliding Weights view draws it: its layers, its pockets, and the shards that hold them. +//! The served model as the Living Weights view draws it: layers, pockets and shards, named as its family names them. const std = @import("std"); const json = @import("json.zig"); +const families = @import("living").families; +const Family = @import("living").Family; const Allocator = std.mem.Allocator; const Io = std.Io; @@ -16,15 +18,20 @@ pub const Model = struct { shards: []const Shard = &.{}, }; -const prefix = "backbone.layers."; -const expert = "mixer.shared_experts."; +/// The family a config names by its model_type; Nemotron's for one that names none (as configs before families did). +fn familyOf(o: std.json.ObjectMap) ?Family { + const v = o.get("model_type") orelse return families.nemotron_h; + return if (v == .string) families.byModelType(v.string) else null; +} /// The folder's config, shard headers and stats; the pocket's rows read where the shards hold one. pub fn scan(a: Allocator, io: Io, dir: []const u8) !Model { const config = try readJson(a, io, try std.fs.path.join(a, &.{ dir, "config.json" })); if (config != .object) return error.BadConfig; - const kinds = try kindsOf(a, config.object); - const pocket = intField(config.object, "tensorfold_learned_neurons") orelse 0; + const f = familyOf(config.object) orelse return error.UnknownFamily; + const keys = families.scoped(f, config.object) orelse return error.BadConfig; // text_config, or the top level + const kinds = try families.kinds(a, f, keys); + const pocket = intField(keys, f.keys.pocket) orelse 0; var moe: std.ArrayList(u16) = .empty; for (kinds, 0..) |k, l| if (k == 'E') try moe.append(a, @intCast(l)); const used = try a.alloc(u16, moe.items.len); @@ -39,7 +46,7 @@ pub fn scan(a: Allocator, io: Io, dir: []const u8) !Model { const path = try std.fs.path.join(a, &.{ dir, name }); const stat = try Io.Dir.cwd().statFile(io, path, .{}); var shard: Shard = .{ .name = name, .bytes = stat.size, .mtime = stat.mtime.toNanoseconds(), .inode = @intCast(stat.inode), .layers = &.{}, .expert_bytes = 0 }; - readShard(a, io, path, &shard, pocket, moe.items, used) catch {}; + readShard(a, io, path, f, &shard, pocket, moe.items, used) catch {}; try shards.append(a, shard); } std.mem.sort(Shard, shards.items, {}, byName); @@ -50,33 +57,13 @@ fn byName(_: void, x: Shard, y: Shard) bool { return std.mem.lessThan(u8, x.name, y.name); } -/// The layer kinds as letters, from hybrid_override_pattern, else layers_block_type, else num_hidden_layers unknowns. -fn kindsOf(a: Allocator, o: std.json.ObjectMap) ![]const u8 { - if (o.get("hybrid_override_pattern")) |v| if (v == .string and v.string.len > 0) return a.dupe(u8, v.string); - if (o.get("layers_block_type")) |v| if (v == .array) { - const out = try a.alloc(u8, v.array.items.len); - for (v.array.items, out) |b, *k| k.* = letter(if (b == .string) b.string else ""); - return out; - }; - const n = intField(o, "num_hidden_layers") orelse 0; - const out = try a.alloc(u8, n); - @memset(out, '?'); - return out; -} - -fn letter(name: []const u8) u8 { - const names = [_]struct { []const u8, u8 }{ .{ "mamba", 'M' }, .{ "moe", 'E' }, .{ "attention", '*' }, .{ "mlp", '-' } }; - for (names) |n| if (std.mem.eql(u8, name, n[0])) return n[1]; - return '?'; -} - fn intField(o: std.json.ObjectMap, key: []const u8) ?usize { const v = o.get(key) orelse return null; return if (v == .integer and v.integer >= 0) @intCast(v.integer) else null; } /// The shard's header: the layers whose shared expert it holds and their bytes, and the pocket's neurons in use there. -fn readShard(a: Allocator, io: Io, path: []const u8, shard: *Shard, pocket: usize, moe: []const u16, used: []u16) !void { +fn readShard(a: Allocator, io: Io, path: []const u8, f: Family, shard: *Shard, pocket: usize, moe: []const u16, used: []u16) !void { var file = try Io.Dir.cwd().openFile(io, path, .{}); defer file.close(io); var len: [8]u8 = undefined; @@ -91,14 +78,19 @@ fn readShard(a: Allocator, io: Io, path: []const u8, shard: *Shard, pocket: usiz var it = header.object.iterator(); while (it.next()) |kv| { const name = kv.key_ptr.*; - const at = std.mem.indexOf(u8, name, expert) orelse continue; + const expert = f.names.expert; + const at = std.mem.indexOf(u8, name, expert) orelse continue; // an MTP head's expert's bytes count too const range = offsets(kv.value_ptr.*) orelse continue; shard.expert_bytes += range[1] - range[0]; - const layer = layerOf(name[0..at]) orelse continue; + const layer: u16 = @intCast(f.expertLayer(name) orelse continue); if (std.mem.indexOfScalar(u16, layers.items, layer) == null) try layers.append(a, layer); if (pocket == 0) continue; + // a row a neuron: the first input projection's scales or biases (up_proj, or a SwiGLU's gate_proj) const leaf = name[at + expert.len ..]; - if (!std.mem.eql(u8, leaf, "up_proj.scales") and !std.mem.eql(u8, leaf, "up_proj.biases")) continue; + const proj = f.names.inputs[0]; + if (!std.mem.startsWith(u8, leaf, proj) or leaf.len <= proj.len or leaf[proj.len] != '.') continue; + const part = leaf[proj.len + 1 ..]; + if (!std.mem.eql(u8, part, "scales") and !std.mem.eql(u8, part, "biases")) continue; const slot = std.mem.indexOfScalar(u16, moe, layer) orelse continue; used[slot] = @max(used[slot], try inUse(a, io, file, 8 + n + range[0], kv.value_ptr.*, pocket)); } @@ -106,15 +98,6 @@ fn readShard(a: Allocator, io: Io, path: []const u8, shard: *Shard, pocket: usiz shard.layers = layers.items; } -/// A backbone layer's index from a name's start ("backbone.layers.13."), else null. -fn layerOf(head: []const u8) ?u16 { - if (!std.mem.startsWith(u8, head, prefix)) return null; - const rest = std.mem.trimEnd(u8, head[prefix.len..], "."); - const dot = std.mem.indexOfScalar(u8, rest, '.') orelse rest.len; - if (dot != rest.len) return null; - return std.fmt.parseInt(u16, rest, 10) catch null; -} - fn offsets(entry: std.json.Value) ?[2]u64 { if (entry != .object) return null; const o = entry.object.get("data_offsets") orelse return null; From e90a10354f14016e720c5fc629bdb8f967cb15e7 Mon Sep 17 00:00:00 2001 From: ZackSample <134018356+ZackSample@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:05:30 -0500 Subject: [PATCH 15/17] Living Weights: the learner as the 27B's lessons run it On #878's learner: the refit and recheck fixes (#870's two PRs), facts learned and checked in conversation (the context PR), checks scored through serving's own rounds instead of decoded again (slide_known.zig, the learner's score request), the writer's asks side by side, and the drift fix: pocket neurons kept from driving one another (pocket_decouple.zig; the values backward holds the pocket's activations through Trainer.pocket_back), 92 broad keep prompts, and 12 drift checks a round may not change where the open lesson's neurons fire (the learner's quiet request). families.zig lists qwen3_5 (and qwen4_exp, #896's). pocket.zig, learner.zig and the server's big files are split to stay under 600 lines. --- zig/src/core/engine_api.zig | 5 +- zig/src/living/affine.zig | 4 +- zig/src/living/families.zig | 40 ++- zig/src/living/family.zig | 10 +- zig/src/living/host_test.zig | 6 +- zig/src/living/learner.zig | 172 ++++++------ zig/src/living/learner_steps.zig | 149 ++++++++++ zig/src/living/lesson_examples.zig | 6 +- zig/src/living/living.zig | 38 +-- zig/src/living/neuron.zig | 2 +- zig/src/living/pocket.zig | 408 ++++++++++++++-------------- zig/src/living/pocket_clock.zig | 32 +++ zig/src/living/pocket_decouple.zig | 171 ++++++++++++ zig/src/living/pocket_fit.zig | 72 ++++- zig/src/living/pocket_fits.zig | 240 ++++++++++++++++ zig/src/living/pocket_load.zig | 30 -- zig/src/living/pocket_quiet.zig | 175 +++++++++--- zig/src/living/pocket_read.zig | 171 ++++++++++-- zig/src/living/pocket_retire.zig | 55 ++++ zig/src/living/pocket_test.zig | 232 ++++++++++++++++ zig/src/living/pocket_values.zig | 33 ++- zig/src/living/probe.zig | 2 +- zig/src/living/shards.zig | 71 ++++- zig/src/living/swiglu_test.zig | 4 +- zig/src/living/test_families.zig | 18 -- zig/src/living/whole.zig | 6 +- zig/src/native/slide_adapter.zig | 9 +- zig/src/server/chat.zig | 8 +- zig/src/server/root.zig | 6 + zig/src/server/slide.zig | 200 ++++++++++++-- zig/src/server/slide_ask.zig | 23 +- zig/src/server/slide_context.zig | 167 ++++++++++++ zig/src/server/slide_found.zig | 9 +- zig/src/server/slide_graph.zig | 248 +++++++++-------- zig/src/server/slide_graph_test.zig | 148 ++++++++++ zig/src/server/slide_known.zig | 82 ++++++ zig/src/server/slide_lesson.zig | 338 +++++++++++------------ zig/src/server/slide_model.zig | 31 ++- zig/src/server/slide_pick.zig | 3 + zig/src/server/slide_prompts.zig | 121 +++++++++ zig/src/server/slide_recheck.zig | 179 ++++++++++++ zig/src/server/slide_replace.zig | 21 +- zig/src/server/slide_route.zig | 23 +- zig/src/server/slide_router.zig | 226 +++++++++++++++ zig/src/server/slide_side.zig | 104 ++++++- zig/src/server/slide_subject.zig | 40 +++ zig/src/server/slide_take.zig | 64 ++++- zig/src/server/slide_teacher.zig | 50 +++- zig/src/server/slide_think.zig | 5 +- zig/src/server/slide_verify.zig | 33 ++- zig/src/server/slide_whom.zig | 152 +++++++++++ zig/src/server/slide_words.zig | 204 +++----------- zig/src/server/slide_words_test.zig | 203 ++++++++++++++ 53 files changed, 3882 insertions(+), 967 deletions(-) create mode 100644 zig/src/living/learner_steps.zig create mode 100644 zig/src/living/pocket_decouple.zig create mode 100644 zig/src/living/pocket_fits.zig delete mode 100644 zig/src/living/pocket_load.zig create mode 100644 zig/src/living/pocket_retire.zig create mode 100644 zig/src/living/pocket_test.zig delete mode 100644 zig/src/living/test_families.zig create mode 100644 zig/src/server/slide_context.zig create mode 100644 zig/src/server/slide_graph_test.zig create mode 100644 zig/src/server/slide_known.zig create mode 100644 zig/src/server/slide_recheck.zig create mode 100644 zig/src/server/slide_router.zig create mode 100644 zig/src/server/slide_words_test.zig diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index 2b0915bca4..fb7a497371 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -305,7 +305,7 @@ pub const Status = struct { pub const SubmitError = error{ Closed, Busy, InvalidSpans }; /// A worked example for the learner: token ids, the answer from `start`; `decide`: its assistant header's last row. -pub const Example = struct { ids: []const u32, start: u32, decide: u32, subject: u32 = 0, value: u32 = 0 }; // subject: the row of its last token; value: the row before its answer's value (0: none) +pub const Example = struct { ids: []const u32, start: u32, decide: u32, subject: u32 = 0, value: u32 = 0, context: u32 = 0 }; // subject: the row of its last token; value: the row before its answer's value (0: none); context: the rows of a conversation before its own turn, which other examples share (0: none) /// One fact's lesson (Sliding Weights): answers, held-out answers, near misses, and prompts that must not move. pub const LearnRequest = struct { @@ -325,6 +325,8 @@ pub const LearnRequest = struct { save: bool = false, // every kept lesson written beside the model's shards, each with its router retire: []const Neuron = &.{}, // instead zero these neurons of facts a newer fact replaces unretire: bool = false, // instead put back the neurons the last retire zeroed (the newer fact was not learned) + score: []const Example = &.{}, // instead score these replies teacher-forced: is each its prompt's greedy reply now? + quiet: []const Example = &.{}, // instead read these through the model: do the open lesson's pocket neurons stay at or below zero on all their rows? (verdicts as `scored`) }; /// A neuron a pocket lesson placed (Sliding Weights): its layer, its index in that layer's pocket, the row it keys on. @@ -341,6 +343,7 @@ pub const LearnProgress = struct { phase: LearnPhase, at: u32 = 0, of: u32 = 0, pub const LearnEvent = union(enum) { learned: struct { recalled: bool, steps: u32, loss: f32, neurons: []const Neuron = &.{} }, // neurons: a pocket's progress: LearnProgress, + scored: struct { same: []const bool }, // a score request's verdicts, one a reply: every answer row's greedy pick is its next token done: struct { message: []const u8 = "" }, }; diff --git a/zig/src/living/affine.zig b/zig/src/living/affine.zig index 177b40a4d4..c2c965965e 100644 --- a/zig/src/living/affine.zig +++ b/zig/src/living/affine.zig @@ -1,4 +1,4 @@ -//! MLX's affine layout on the host at any group and code width; at 4 bits in groups of 64 it is affine4_host's. +//! MLX's affine layout on the host at any group and code width. const std = @import("std"); const Quant = @import("family.zig").Quant; @@ -28,7 +28,7 @@ pub fn dequantize(comptime q: Quant, words: []const u32, scales: []const u16, bi } } -/// Codes, scales and biases for row-major values: a group's minimum is its bias, its range over the top code its scale. +/// Codes, scales and biases for row-major values: each group's minimum is its bias. pub fn quantize(comptime q: Quant, values: []const f32, words: []u32, scales: []u16, biases: []u16) void { comptime std.debug.assert(32 % q.bits == 0); const per = 32 / q.bits; diff --git a/zig/src/living/families.zig b/zig/src/living/families.zig index a1db5ab468..3464c50943 100644 --- a/zig/src/living/families.zig +++ b/zig/src/living/families.zig @@ -2,7 +2,6 @@ const std = @import("std"); const family = @import("family.zig"); const Family = family.Family; -const test_families = @import("test_families.zig"); /// Nemotron 3.5 Lightning (nemotron_h): relu^2 shared experts at the pattern's MoE layers, 4-bit groups of 64. pub const nemotron_h: Family = .{ @@ -19,7 +18,33 @@ pub const nemotron_h: Family = .{ .experts = .pattern, }; -pub const all = [_]Family{nemotron_h}; +/// Qwen3.8 Flash Next (qwen4_exp): a SwiGLU shared expert at every layer, gated by sigmoid of its own router logit. +pub const qwen4_exp: Family = .{ + .model_type = "qwen4_exp", + .names = .{ + .layers = "language_model.model.layers.", + .expert = "mlp.shared_expert.", + .inputs = &.{ "gate_proj", "up_proj" }, + .mtp = .{ .base = "language_model.mtp.layers.0.mlp.shared_expert." }, + }, + // silu(gate) is not zero below it as relu is: a wider margin keeps sigmoid(-16 * 0.5) = 3e-4 of it there + .neuron = .{ .act = .swiglu, .gated = true, .margin = 0.5, .sharp = 16 }, + .quant = .{ .bits = 4, .group = 32 }, + .keys = .{ .scope = "text_config", .width = "shared_expert_intermediate_size" }, + .experts = .every, +}; + +/// Qwen3.8-27B (qwen3_5): a dense SwiGLU MLP at every layer, ungated, 4-bit groups of 64, keys under text_config. +pub const qwen3_5: Family = .{ + .model_type = "qwen3_5", + .names = .{ .layers = "language_model.model.layers.", .expert = "mlp.", .inputs = &.{ "gate_proj", "up_proj" } }, + .neuron = .{ .act = .swiglu, .margin = 0.5, .sharp = 16 }, + .quant = .{ .bits = 4, .group = 64 }, + .keys = .{ .scope = "text_config", .width = "intermediate_size" }, + .experts = .every, +}; + +pub const all = [_]Family{ nemotron_h, qwen4_exp, qwen3_5 }; /// The family of a checkpoint's top-level model_type, or null. pub fn byModelType(model_type: []const u8) ?Family { @@ -27,7 +52,7 @@ pub fn byModelType(model_type: []const u8) ?Family { return null; } -/// A config's layer letters (M mamba, E MoE, * attention, - MLP, ? other); a family with an expert at each: all E. +/// The layer letters a config's model keys give (M mamba, E an MoE, * attention, - MLP, ? other). pub fn kinds(a: std.mem.Allocator, f: Family, o: std.json.ObjectMap) ![]const u8 { const n = intField(o, f.keys.layers); if (f.experts == .every) { @@ -66,8 +91,7 @@ pub fn intField(o: std.json.ObjectMap, key: []const u8) ?usize { } test "each family's model type finds it; a pattern family's letters come from its pattern, an every-layer one's are E" { - try std.testing.expectEqualStrings("nemotron_h", byModelType("nemotron_h").?.model_type); - try std.testing.expect(byModelType("qwen4_exp") == null); + try std.testing.expectEqualStrings("qwen4_exp", byModelType("qwen4_exp").?.model_type); try std.testing.expect(byModelType("glm") == null); var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); @@ -75,5 +99,9 @@ test "each family's model type finds it; a pattern family's letters come from it const n = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"layers_block_type\": [\"mamba\", \"moe\", \"attention\"]}", .{}); try std.testing.expectEqualStrings("ME*", try kinds(a, nemotron_h, n.object)); const q = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"text_config\": {\"num_hidden_layers\": 3}}", .{}); - try std.testing.expectEqualStrings("EEE", try kinds(a, test_families.swiglu, scoped(test_families.swiglu, q.object).?)); + try std.testing.expectEqualStrings("EEE", try kinds(a, qwen4_exp, scoped(qwen4_exp, q.object).?)); + try qwen3_5.check(); + try std.testing.expectEqual(@as(?usize, 7), qwen3_5.expertLayer("language_model.model.layers.7.mlp.down_proj.scales")); + try std.testing.expectEqual(@as(?usize, null), qwen3_5.expertLayer("language_model.model.layers.7.linear_attn.out_proj.scales")); + try std.testing.expectEqual(@as(?usize, null), qwen3_5.expertLayer("vision_tower.blocks.7.mlp.linear_fc1.weight")); } diff --git a/zig/src/living/family.zig b/zig/src/living/family.zig index e4498b1d3c..3c64c56b8c 100644 --- a/zig/src/living/family.zig +++ b/zig/src/living/family.zig @@ -1,4 +1,4 @@ -//! What a family hands Living Weights: where a pocket sits, how its neurons fire, how its shards hold them. +//! What a model family hands Living Weights: where a pocket can sit, how its neurons fire, how its shards hold them. const std = @import("std"); /// What a pocket neuron does with its input x: relu(u x)^2 (Nemotron), or silu(g x) (w x) (a SwiGLU shared expert). @@ -7,11 +7,11 @@ pub const Activation = enum { relu2, swiglu }; /// A pocket neuron's kind: its activation, whether a per-row gate scales its expert's output, and its input fit. pub const Neuron = struct { act: Activation, - /// The shared expert's output is scaled by a gate the trainer reads at each row, so a neuron adds gate act(x) v. + /// The shared expert's output is scaled by a gate the trainer reads at each row. gated: bool = false, /// The input fit's margin: rows a neuron stays silent on are fitted to u x at or below -margin. margin: f32 = 0.25, - /// SwiGLU: a neuron fitted as u is written as gate row sharp * u and up row u / sharp (a power of two keeps u). + /// SwiGLU only: a neuron fitted as u is written as gate row sharp * u and up row u / sharp. sharp: f32 = 16, /// Input projections a neuron has a row in: one (up) or two (gate, then up). @@ -106,7 +106,7 @@ pub const Layout = struct { return out[0..n]; } - /// Every layer `has` names carries one widened; all but the last learn (a nudge after it has no gradient to read). + /// Every layer whose expert `has` says carries one widened; all but the last learn. pub fn fromExperts(hidden: usize, width: usize, layers: usize, has: Layers) Layout { var lay: Layout = .{ .hidden = hidden, .width = width, .layers = layers, .widen = has, .learn = has }; if (layers > 0) lay.learn.unset(layers - 1); @@ -115,7 +115,7 @@ pub const Layout = struct { }; test "a family finds its shared expert's layer in a tensor name and builds its prefix" { - const f = @import("test_families.zig").swiglu; + const f = @import("families.zig").qwen4_exp; try f.check(); var buf: [128]u8 = undefined; try std.testing.expectEqualStrings("language_model.model.layers.7.mlp.shared_expert.", try f.expertBase(&buf, 7)); diff --git a/zig/src/living/host_test.zig b/zig/src/living/host_test.zig index e9cb25b719..462a30f261 100644 --- a/zig/src/living/host_test.zig +++ b/zig/src/living/host_test.zig @@ -1,4 +1,4 @@ -//! The learner over a stand-in host and trainer on the CPU: a whole pocket lesson read, fitted, stepped, saved. +//! The learner over a stand-in host and trainer on the CPU: a whole pocket lesson read, fitted, its outputs stepped. const std = @import("std"); const learner = @import("learner.zig"); const families = @import("families.zig"); @@ -134,7 +134,7 @@ fn Host(comptime F: fam.Family) type { return 1; } - /// The forward's rows before a save: each gate row sharp^2 times its up row (g = sharp u, w = u / sharp). + /// The forward's rows before a save: each neuron's gate row sharp^2 times its up row. pub fn pocketSwiglu(s: Ctx, _: usize, gate: []const f32, up: []const f32, _: []const f32, _: usize) !void { s.uploads += 1; if (s.saved > 0) return; // after a save the rows are as written, each rounded its own way @@ -211,5 +211,5 @@ test "a pocket lesson over a stand-in relu^2 host: read, fitted, stepped, judged } test "a pocket lesson over a stand-in gated SwiGLU host: its rows handed over as gate sharp u and up u / sharp, the gate read" { - try run(@import("test_families.zig").swiglu); + try run(families.qwen4_exp); } diff --git a/zig/src/living/learner.zig b/zig/src/living/learner.zig index ddad1c54b8..190431a039 100644 --- a/zig/src/living/learner.zig +++ b/zig/src/living/learner.zig @@ -1,4 +1,4 @@ -//! Living Weights' lessons, one learner for every family and backend over a host that gives the trainer and hooks. +//! Sliding Weights' lessons, one learner for every family and backend over a host that gives the trainer. const std = @import("std"); const adapters = @import("learn_shape.zig"); const choice = @import("choice.zig"); @@ -12,6 +12,8 @@ const probe = @import("probe.zig"); const pocket = @import("pocket.zig"); const whole_lessons = @import("whole.zig"); const examples = @import("lesson_examples.zig"); +const pack = @import("pocket_pack.zig"); +const learner_steps = @import("learner_steps.zig"); pub const Example = examples.Example; pub const Lesson = examples.Lesson; @@ -30,6 +32,7 @@ pub const Codes = struct { words: []u32, scales: []const u16, biases: []const u1 pub const Report = union(enum) { learned: struct { recalled: bool, steps: u32, loss: f32 }, failed: []const u8, + scored: []const bool, // a score request's verdicts (the learner's until its next request) }; pub const Step = struct { done: bool, changed: bool = false, report: ?Report = null }; @@ -40,16 +43,17 @@ const replay_cap = 256; // earlier lessons' answers a new lesson leaves as they const replay_each = 8; // of a lesson's answers, its first (plain questions) join the replay, so every fact keeps some /// A lesson builds (build) and learns (steps); an edit is written at its subject (edit), more rounds report (again). -const Phase = enum { idle, build, steps, undo, reroute, drop, save, edit, again, probe, pocket, retire }; +const Phase = enum { idle, build, steps, undo, reroute, drop, save, edit, again, probe, pocket, retire, score, quiet }; -/// The lessons over host H: its trainer and hooks (family.zig), routed blocks only when its trainer keeps `sites`. +/// The lessons over host H: its Trainer, max_rows, Ctx, trainer, free and seconds. pub fn Learner(comptime H: type) type { return struct { const Self = @This(); - const has_sites = @hasField(H.Trainer, "sites"); // Nemotron's routed blocks of ranks (the LoRA path) - const has_edits = has_sites and @hasDecl(H.Trainer, "key") and @hasDecl(H, "commit"); // keys, a nudged row, codes to write - const has_pocket = @hasDecl(H.Trainer, "normed") and (@hasDecl(H, "pocketSave") or @hasDecl(H, "pocketSaveSwiglu")); // inputs, gradients, a pocket to write - const has_whole = has_edits or has_pocket; // lessons that change the model itself + pub const has_sites = @hasField(H.Trainer, "sites"); // Nemotron's routed blocks of ranks (the LoRA path) + pub const has_edits = has_sites and @hasDecl(H.Trainer, "key") and @hasDecl(H, "commit"); // keys, a nudged row, codes to write + pub const has_pocket = @hasDecl(H.Trainer, "normed") and (@hasDecl(H, "pocketSave") or @hasDecl(H, "pocketSaveSwiglu")); // inputs, gradients, a pocket to write + pub const has_whole = has_edits or has_pocket; // lessons that change the model itself + pub const has_greedy = @hasDecl(H.Trainer, "greedy"); // replies scored teacher-forced in batched passes const Edits = if (has_edits) editor.Editor(H.Trainer) else void; const Probes = if (has_edits) probe.Probe(H.Trainer) else void; const Pockets = if (has_pocket) pocket.Pocket(H.Trainer, H.family) else void; @@ -95,6 +99,9 @@ pub fn Learner(comptime H: type) type { probe: Probes, pockets: Pockets, // every MoE layer's pocket of learned neurons pocketed: bool = false, // the last lesson put neurons in the pocket + plain: [2]std.ArrayList(Example) = .{ .empty, .empty }, // a lesson's asked and unasked, conversations left out + scoring: []const Example = &.{}, // a score request's replies (borrowed until its report) + same: std.ArrayList(bool) = .empty, // their verdicts so far pub fn init(gpa: std.mem.Allocator, io: std.Io, b: H.Ctx) Self { return .{ .gpa = gpa, .io = io, .b = b, .whole = !has_sites or std.c.getenv("TF_SLIDE_ROUTED") == null, .edits = if (has_edits) Edits.init(gpa) else {}, .method = if (has_edits) whole_lessons.method() else .pocket, .probe = if (has_edits) Probes.init(gpa) else {}, .pockets = if (has_pocket) Pockets.init(gpa) else {} }; @@ -126,6 +133,8 @@ pub fn Learner(comptime H: type) type { l.replay_of.deinit(l.gpa); l.live.deinit(l.gpa); l.live_of.deinit(l.gpa); + for (&l.plain) |*x| x.deinit(l.gpa); + l.same.deinit(l.gpa); } /// The earlier lessons' questions a new lesson stays silent on, but those of facts a newer one replaced. @@ -143,6 +152,24 @@ pub fn Learner(comptime H: type) type { /// Start a lesson's round; its examples must stay valid until its last step. pub fn begin(l: *Self, lesson: Lesson) !void { std.debug.assert(l.phase == .idle); + if (lesson.score.len > 0) { + // replies scored, the open lesson left as it is + if (comptime !has_greedy) return error.ScoreUnsupported; + try l.ready(); + l.scoring = lesson.score; + l.same.clearRetainingCapacity(); + l.phase = .score; + return; + } + if (lesson.quiet.len > 0) { + // whether the pocket stays silent on each, the open lesson left as it is + if (comptime !has_pocket) return error.ScoreUnsupported; + try l.ready(); + l.scoring = lesson.quiet; + l.same.clearRetainingCapacity(); + l.phase = .quiet; + return; + } l.lesson = lesson; if (lesson.undo) { l.phase = .undo; @@ -169,15 +196,19 @@ pub fn Learner(comptime H: type) type { } if (lesson.train.len == 0) return; for ([_][]const Example{ lesson.train, lesson.think, lesson.held, lesson.near, lesson.keep, lesson.asked, lesson.unasked, lesson.kept }) |xs| for (xs) |ex| { - if (ex.start < 1 or ex.start >= ex.ids.len or ex.ids.len - 1 > H.max_rows or ex.decide + 1 >= ex.ids.len) return error.ExampleTooLong; + if (ex.start < 1 or ex.start >= ex.ids.len or ex.decide + 1 >= ex.ids.len) return error.ExampleTooLong; + // a prompt in a conversation is read through the host's taps, at any length + if (ex.ids.len - 1 > H.max_rows and ex.context == 0) return error.ExampleTooLong; }; + if (!l.taps()) l.lesson = try l.withoutConversations(lesson); try l.ready(); - if (lesson.more) { + const kept = l.lesson; // as this learner reads it: without the conversations its host cannot read + if (kept.more) { if (l.whole) return if (has_whole) whole_lessons.more(l) else error.EditsUnsupported; if (!l.opened) return error.NothingToContinue; return l.start(); } - try l.settleLast(lesson.train); + try l.settleLast(kept.train); if (has_sites) { if (l.trainer.?.sites.rank + adapters.block > adapters.max_rank) return error.LearnedChangeFull; l.trainer.?.sites.clear(); @@ -191,15 +222,36 @@ pub fn Learner(comptime H: type) type { for (l.keeps.items) |ex| l.gpa.free(ex.ids); l.keeps.clearRetainingCapacity(); l.topic = false; - if (l.whole) return if (has_whole) whole_lessons.begin(l, lesson) else error.EditsUnsupported; + if (l.whole) return if (has_whole) whole_lessons.begin(l, kept) else error.EditsUnsupported; if (comptime !has_sites) unreachable; // a host without routed blocks learns whole lessons only l.gpa.free(l.answers); - l.answers = try std.mem.concat(l.gpa, Example, &.{ lesson.train, lesson.think }); + l.answers = try std.mem.concat(l.gpa, Example, &.{ kept.train, kept.think }); l.phase = .build; - for ([_][]const Example{ lesson.train, lesson.think, lesson.held, lesson.asked }) |xs| for (xs) |ex| try l.routes(ex, .fact); - for (lesson.near) |ex| try l.routes(ex, .near); - for (lesson.unasked) |ex| try l.routes(ex, .swap); - for ([_][]const Example{ lesson.keep, l.replay.items }) |xs| for (xs) |ex| try l.routes(ex, .other); + for ([_][]const Example{ kept.train, kept.think, kept.held, kept.asked }) |xs| for (xs) |ex| try l.routes(ex, .fact); + for (kept.near) |ex| try l.routes(ex, .near); + for (kept.unasked) |ex| try l.routes(ex, .swap); + for ([_][]const Example{ kept.keep, l.replay.items }) |xs| for (xs) |ex| try l.routes(ex, .other); + } + + /// Whether this learner reads prompts in a conversation (Example.context). + fn taps(l: *const Self) bool { + if (comptime !(has_pocket and @hasDecl(H.Trainer, "tapRows"))) return false; + return l.whole and l.method == .pocket; + } + + /// `lesson` with its prompts in a conversation left out (its other examples as they are). + fn withoutConversations(l: *Self, lesson: Lesson) !Lesson { + var out = lesson; + var dropped: usize = 0; + for ([_]*[]const Example{ &out.asked, &out.unasked }, &l.plain) |list, *buf| { + buf.clearRetainingCapacity(); + for (list.*) |ex| if (ex.context == 0) try buf.append(l.gpa, ex) else { + dropped += 1; + }; + list.* = buf.items; + } + if (dropped > 0) std.log.info("slide: {d} questions asked in a conversation are left out: this learner reads none", .{dropped}); + return out; } /// The trainer, made the first time a lesson needs it. @@ -219,7 +271,7 @@ pub fn Learner(comptime H: type) type { } /// A round's steps from the open block as it is now, which an undo comes back to. - fn start(l: *Self) !void { + pub fn start(l: *Self) !void { if (comptime !has_sites) return error.RoutedUnsupported; try l.schedule(@max(@min(l.lesson.steps, max_steps), 1)); l.trainer.?.sites.keep(); @@ -275,6 +327,8 @@ pub fn Learner(comptime H: type) type { .edit => return if (has_edits) whole_lessons.editOnce(l) else unreachable, .probe => return if (has_edits) whole_lessons.probeOnce(l) else unreachable, .pocket => return if (has_pocket) whole_lessons.pocketOnce(l) else unreachable, + .score => return l.scoreOnce(), + .quiet => return l.quietOnce(), .again => { l.phase = .idle; return .{ .done = true, .report = .{ .learned = .{ .recalled = l.edited, .steps = 0, .loss = if (has_edits) l.edits.last_loss else 0 } } }; @@ -282,21 +336,19 @@ pub fn Learner(comptime H: type) type { } } + /// One pass of a score request's replies: whether each is its prompt's greedy reply under the model as it is. + fn scoreOnce(l: *Self) !Step { + return learner_steps.scoreOnce(l); + } + + /// One pass of a quiet request's examples: whether the open lesson's pocket neurons' input products stay at or. + fn quietOnce(l: *Self) !Step { + return learner_steps.quietOnce(l); + } + /// Every kept lesson not yet written goes beside the model's shards, a file each. fn saveOnce(l: *Self) !Step { - l.phase = .idle; - const t = l.trainer orelse return .{ .done = true }; - if (l.whole) { // a lesson of the model itself goes into its own shards: the pocket, or an edit's codes - if (has_whole and !try whole_lessons.save(l)) try whole_lessons.foldOpen(l); - return .{ .done = true, .changed = true }; - } - if (comptime !has_sites) return .{ .done = true }; - const ranks = t.sites.rank - @as(usize, if (l.opened and l.kept_rounds == 0) adapters.block else 0); - if (ranks == 0) return .{ .done = true }; - const t0 = H.seconds(l.io); - const bytes = try H.write(l.b, l.gpa, l.io, t, ranks); - std.log.info("slide: {d} lessons beside the model's shards, a file each with its router: {d} MB written in {d:.1} s", .{ ranks / adapters.block, bytes >> 20, H.seconds(l.io) - t0 }); - return .{ .done = true }; + return learner_steps.saveOnce(l); } /// The lessons already kept that act on a reply to `ex` (their routers' scores at its decision row, read once). @@ -305,7 +357,7 @@ pub fn Learner(comptime H: type) type { } /// A pass of `ex` in `mode` (`acting`: the open lesson acts on its reply); its first reads which kept ones act. - fn pass(l: *Self, ex: Example, mode: train_mode.Mode, acting: bool) !f32 { + pub fn pass(l: *Self, ex: Example, mode: train_mode.Mode, acting: bool) !f32 { if (comptime !has_sites) return error.RoutedUnsupported; const t = l.trainer.?; const k = key(ex); @@ -332,7 +384,7 @@ pub fn Learner(comptime H: type) type { } /// Layer by layer, a routing prompt's decision row along the candidates, as the last project pass left it. - fn ask(l: *Self, r: Asked) !void { + pub fn ask(l: *Self, r: Asked) !void { if (comptime !has_sites) return error.RoutedUnsupported; const t = l.trainer.?; for (l.asks[@backingInt(r.kind)], 0..) |*rows, k| try rows.appendSlice(l.gpa, t.projected(k, r.ex.ids.len - 1)[r.ex.decide * adapters.candidates ..][0..adapters.candidates]); @@ -340,61 +392,11 @@ pub fn Learner(comptime H: type) type { /// One example at a time: sketched, projected, routing rows copied; then the block chosen, its router fitted. fn buildOnce(l: *Self) !Step { - if (comptime !has_sites) return error.RoutedUnsupported; - const t = l.trainer.?; - const c = &l.choice.?; - // an edit of the weights also keeps the questions about others, and reads every wording of the fact's - const stay_all = [_][]const Example{ l.lesson.keep, l.lesson.near, l.replay.items, l.lesson.unasked }; - const fact_all = [_][]const Example{ l.answers, l.lesson.asked }; - const stay: []const []const Example = if (l.whole) &stay_all else stay_all[0..3]; - const facts: []const []const Example = if (l.whole) &fact_all else fact_all[0..1]; - const steady = total(stay); - const nfacts = total(facts); - const asked = l.routing.items; - var i = l.built; - l.built += 1; - if (i < steady) return l.sketch(pick(stay, i), .avoid); - i -= steady; - if (i < nfacts) return l.sketch(pick(facts, i), .seek); - i -= nfacts; - if (i == 0) { - t.sites.frame(); - c.reset(); - } - if (i < steady) { - const ex = pick(stay, i); - _ = try l.pass(ex, .project, false); - for (0..t.sites.list.len) |k| c.add(k, t.projected(k, ex.ids.len - 1), false, ex.start - 1); - return .{ .done = false }; - } - i -= steady; - if (i < nfacts) { - const ex = pick(facts, i); - _ = try l.pass(ex, .project, false); - for (0..t.sites.list.len) |k| { - const rows = t.projected(k, ex.ids.len - 1); - // a weight edit: the question's rows, evenly; a routed block: the answer, its first row heavily - if (l.whole) c.add(k, rows[0 .. (ex.decide + 1) * adapters.candidates], true, std.math.maxInt(usize)) else c.add(k, rows[(ex.start - 1) * adapters.candidates ..], true, 0); - } - return .{ .done = false }; - } - i -= nfacts; - if (i < asked.len) { - _ = try l.pass(asked[i].ex, .project, false); - try l.ask(asked[i]); - return .{ .done = false }; - } - try c.choose(); - try t.sites.open(c.coef); - l.opened = true; - if (!l.whole) try l.route(); - try H.attach(l.b, t); - try l.start(); - return .{ .done = false }; + return learner_steps.buildOnce(l); } /// The open block's router: if facts don't stand apart it acts on what most clear, learning to leave the rest. - fn route(l: *Self) !void { + pub fn route(l: *Self) !void { if (comptime !has_sites) return error.RoutedUnsupported; const t = l.trainer.?; var fit = try l.fitWith(&.{.fact}, &.{ .near, .swap, .other }); @@ -480,7 +482,7 @@ pub fn Learner(comptime H: type) type { return .{ .done = true, .changed = true }; } - fn sketch(l: *Self, ex: Example, comptime mode: @EnumLiteral()) !Step { + pub fn sketch(l: *Self, ex: Example, comptime mode: @EnumLiteral()) !Step { _ = try l.pass(ex, mode, false); return .{ .done = false }; } diff --git a/zig/src/living/learner_steps.zig b/zig/src/living/learner_steps.zig new file mode 100644 index 0000000000..571e584954 --- /dev/null +++ b/zig/src/living/learner_steps.zig @@ -0,0 +1,149 @@ +//! The learner's one-pass requests (replies scored, the pocket read on replies, lessons saved) and a lesson's build. +const std = @import("std"); +const adapters = @import("learn_shape.zig"); +const choice = @import("choice.zig"); +const router = @import("router.zig"); +const lesson_route = @import("lesson_route.zig"); +const Acting = lesson_route.Acting; +const latched = lesson_route.latched; +const train_mode = @import("train_mode.zig"); +const editor = @import("editor.zig"); +const probe = @import("probe.zig"); +const pocket = @import("pocket.zig"); +const whole_lessons = @import("whole.zig"); +const examples = @import("lesson_examples.zig"); +const pack = @import("pocket_pack.zig"); +const max_steps = examples.max_steps; +const Deck = examples.Deck; +const key = examples.key; +const total = examples.total; +const pick = examples.pick; +const own = examples.own; +const disown = examples.disown; +const disownLesson = examples.disownLesson; +const check_every = 20; +const learner = @import("learner.zig"); +const Example = learner.Example; +const Step = learner.Step; + +/// One pass of a score request's replies: whether each is its prompt's greedy reply under the model as it is. +pub fn scoreOnce(l: anytype) !Step { + if (comptime !@TypeOf(l.*).has_greedy) unreachable; + const t = l.trainer.?; + const xs = l.scoring[l.same.items.len..]; + if (xs.len == 0) { + l.phase = .idle; + return .{ .done = true, .report = .{ .scored = l.same.items } }; + } + if (xs[0].ids.len - 1 > @TypeOf(l.*).Host.max_rows or xs[0].start < 1 or xs[0].start >= xs[0].ids.len) { + try l.same.append(l.gpa, false); + return .{ .done = false }; + } + var seqs: [@typeInfo(@TypeOf(t.spans)).array.len]train_mode.Seq = undefined; + var n: usize = 0; + while (n < seqs.len and n < xs.len and xs[n].ids.len - 1 <= @TypeOf(l.*).Host.max_rows and xs[n].start >= 1 and xs[n].start < xs[n].ids.len) : (n += 1) seqs[n] = pack.seq(xs[n]); + n = pack.fits(t, seqs[0..n]); + var got: [seqs.len]bool = undefined; + try t.greedy(seqs[0..n], got[0..n]); + try l.same.appendSlice(l.gpa, got[0..n]); + return .{ .done = false }; +} + +/// One pass of a quiet request's examples: whether the open lesson's pocket neurons' input products stay at or. +pub fn quietOnce(l: anytype) !Step { + if (comptime !@TypeOf(l.*).has_pocket) unreachable; + const t = l.trainer.?; + const xs = l.scoring[l.same.items.len..]; + if (xs.len == 0) { + l.phase = .idle; + return .{ .done = true, .report = .{ .scored = l.same.items } }; + } + if (xs[0].ids.len - 1 > @TypeOf(l.*).Host.max_rows or xs[0].start < 1 or xs[0].start >= xs[0].ids.len) { + try l.same.append(l.gpa, false); + return .{ .done = false }; + } + var seqs: [@typeInfo(@TypeOf(t.spans)).array.len]train_mode.Seq = undefined; + var n: usize = 0; + while (n < seqs.len and n < xs.len and xs[n].ids.len - 1 <= @TypeOf(l.*).Host.max_rows and xs[n].start >= 1 and xs[n].start < xs[n].ids.len) : (n += 1) seqs[n] = pack.seq(xs[n]); + n = pack.fits(t, seqs[0..n]); + var out: [seqs.len]pack.Result = undefined; + try t.pass(seqs[0..n], .keys, pack.turn, out[0..n]); + for (0..n) |i| { + const most = l.pockets.highest(t, t.spans[i].at, xs[i].ids.len - 1); + std.log.info("slide pocket: the open lesson's neurons' highest input product on a {d}-token reply: {d:.3}", .{ xs[i].ids.len, most }); + try l.same.append(l.gpa, most <= 0); + } + return .{ .done = false }; +} + +/// Every kept lesson not yet written goes beside the model's shards, a file each. +pub fn saveOnce(l: anytype) !Step { + l.phase = .idle; + const t = l.trainer orelse return .{ .done = true }; + if (l.whole) { // a lesson of the model itself goes into its own shards: the pocket, or an edit's codes + if (@TypeOf(l.*).has_whole and !try whole_lessons.save(l)) try whole_lessons.foldOpen(l); + return .{ .done = true, .changed = true }; + } + if (comptime !@TypeOf(l.*).has_sites) return .{ .done = true }; + const ranks = t.sites.rank - @as(usize, if (l.opened and l.kept_rounds == 0) adapters.block else 0); + if (ranks == 0) return .{ .done = true }; + const t0 = @TypeOf(l.*).Host.seconds(l.io); + const bytes = try @TypeOf(l.*).Host.write(l.b, l.gpa, l.io, t, ranks); + std.log.info("slide: {d} lessons beside the model's shards, a file each with its router: {d} MB written in {d:.1} s", .{ ranks / adapters.block, bytes >> 20, @TypeOf(l.*).Host.seconds(l.io) - t0 }); + return .{ .done = true }; +} + +/// One example at a time: sketched, projected, routing rows copied; then the block chosen, its router fitted. +pub fn buildOnce(l: anytype) !Step { + if (comptime !@TypeOf(l.*).has_sites) return error.RoutedUnsupported; + const t = l.trainer.?; + const c = &l.choice.?; + // an edit of the weights also keeps the questions about others, and reads every wording of the fact's + const stay_all = [_][]const Example{ l.lesson.keep, l.lesson.near, l.replay.items, l.lesson.unasked }; + const fact_all = [_][]const Example{ l.answers, l.lesson.asked }; + const stay: []const []const Example = if (l.whole) &stay_all else stay_all[0..3]; + const facts: []const []const Example = if (l.whole) &fact_all else fact_all[0..1]; + const steady = total(stay); + const nfacts = total(facts); + const asked = l.routing.items; + var i = l.built; + l.built += 1; + if (i < steady) return l.sketch(pick(stay, i), .avoid); + i -= steady; + if (i < nfacts) return l.sketch(pick(facts, i), .seek); + i -= nfacts; + if (i == 0) { + t.sites.frame(); + c.reset(); + } + if (i < steady) { + const ex = pick(stay, i); + _ = try l.pass(ex, .project, false); + for (0..t.sites.list.len) |k| c.add(k, t.projected(k, ex.ids.len - 1), false, ex.start - 1); + return .{ .done = false }; + } + i -= steady; + if (i < nfacts) { + const ex = pick(facts, i); + _ = try l.pass(ex, .project, false); + for (0..t.sites.list.len) |k| { + const rows = t.projected(k, ex.ids.len - 1); + // a weight edit: the question's rows, evenly; a routed block: the answer, its first row heavily + if (l.whole) c.add(k, rows[0 .. (ex.decide + 1) * adapters.candidates], true, std.math.maxInt(usize)) else c.add(k, rows[(ex.start - 1) * adapters.candidates ..], true, 0); + } + return .{ .done = false }; + } + i -= nfacts; + if (i < asked.len) { + _ = try l.pass(asked[i].ex, .project, false); + try l.ask(asked[i]); + return .{ .done = false }; + } + try c.choose(); + try t.sites.open(c.coef); + l.opened = true; + if (!l.whole) try l.route(); + try @TypeOf(l.*).Host.attach(l.b, t); + try l.start(); + return .{ .done = false }; +} diff --git a/zig/src/living/lesson_examples.zig b/zig/src/living/lesson_examples.zig index b039b2df54..7fe5b3ede9 100644 --- a/zig/src/living/lesson_examples.zig +++ b/zig/src/living/lesson_examples.zig @@ -4,10 +4,12 @@ const std = @import("std"); pub const max_steps = 400; /// Token ids, the answer from `start`; `decide`: the reply's first row; `subject`, `value`: key rows (0: none). -pub const Example = struct { ids: []const u32, start: u32, decide: u32, subject: u32 = 0, value: u32 = 0 }; +pub const Example = struct { ids: []const u32, start: u32, decide: u32, subject: u32 = 0, value: u32 = 0, context: u32 = 0 }; /// One fact's examples; `more` another round, `undo` one back, `save` writes every kept lesson. pub const Lesson = struct { + score: []const Example = &.{}, + quiet: []const Example = &.{}, // instead: whether every pocket neuron stays at or below zero on all of each one's rows train: []const Example = &.{}, think: []const Example = &.{}, // the facts' answers with thinking on, one learned beside each plain one held: []const Example = &.{}, @@ -88,7 +90,7 @@ pub fn own(gpa: std.mem.Allocator, xs: []const Example) ![]Example { gpa.free(out); } for (xs, out) |x, *o| { - o.* = .{ .ids = try gpa.dupe(u32, x.ids), .start = x.start, .decide = x.decide, .subject = x.subject, .value = x.value }; + o.* = .{ .ids = try gpa.dupe(u32, x.ids), .start = x.start, .decide = x.decide, .subject = x.subject, .value = x.value, .context = x.context }; made += 1; } return out; diff --git a/zig/src/living/living.zig b/zig/src/living/living.zig index e1d75f4163..433c8b4978 100644 --- a/zig/src/living/living.zig +++ b/zig/src/living/living.zig @@ -1,4 +1,4 @@ -//! Living Weights, family-neutral: the learner, its pocket of new neurons, their fits and the shard writer. +//! Living Weights (Sliding Weights), family-neutral: the lesson learner. pub const family = @import("family.zig"); pub const families = @import("families.zig"); pub const Family = family.Family; @@ -7,29 +7,17 @@ pub const Layers = family.Layers; pub const learner = @import("learner.zig"); pub const whole = @import("whole.zig"); -pub const choice = @import("choice.zig"); -pub const editor = @import("editor.zig"); -pub const probe = @import("probe.zig"); -pub const router = @import("router.zig"); -pub const subspace = @import("subspace.zig"); -pub const train_mode = @import("train_mode.zig"); -pub const learn_shape = @import("learn_shape.zig"); -pub const lesson_examples = @import("lesson_examples.zig"); -pub const lesson_route = @import("lesson_route.zig"); +pub const pocket = @import("pocket.zig"); +pub const pocket_fit = @import("pocket_fit.zig"); +pub const pocket_clock = @import("pocket_clock.zig"); pub const neuron = @import("neuron.zig"); pub const affine = @import("affine.zig"); pub const shards = @import("shards.zig"); -pub const pocket = @import("pocket.zig"); -pub const pocket_clock = @import("pocket_clock.zig"); -pub const pocket_dump = @import("pocket_dump.zig"); -pub const pocket_fit = @import("pocket_fit.zig"); -pub const pocket_joint = @import("pocket_joint.zig"); -pub const pocket_load = @import("pocket_load.zig"); -pub const pocket_pack = @import("pocket_pack.zig"); -pub const pocket_prefix = @import("pocket_prefix.zig"); -pub const pocket_quiet = @import("pocket_quiet.zig"); -pub const pocket_read = @import("pocket_read.zig"); -pub const pocket_values = @import("pocket_values.zig"); +pub const lesson_examples = @import("lesson_examples.zig"); +pub const lesson_route = @import("lesson_route.zig"); +pub const train_mode = @import("train_mode.zig"); +pub const learn_shape = @import("learn_shape.zig"); +pub const subspace = @import("subspace.zig"); test { _ = family; @@ -39,12 +27,14 @@ test { _ = shards; _ = learner; _ = whole; - _ = subspace; _ = pocket; _ = pocket_fit; - _ = router; - _ = choice; _ = lesson_route; + _ = subspace; + _ = @import("router.zig"); + _ = @import("pocket_decouple.zig"); + _ = @import("pocket_test.zig"); + _ = @import("choice.zig"); _ = @import("swiglu_test.zig"); _ = @import("host_test.zig"); } diff --git a/zig/src/living/neuron.zig b/zig/src/living/neuron.zig index 52db123839..8995d550de 100644 --- a/zig/src/living/neuron.zig +++ b/zig/src/living/neuron.zig @@ -1,4 +1,4 @@ -//! A pocket neuron's activation for each family's kind, and the gate and up rows a SwiGLU neuron is written as. +//! A pocket neuron's activation for each family's kind, and the rows a SwiGLU neuron is written as. const std = @import("std"); const Neuron = @import("family.zig").Neuron; diff --git a/zig/src/living/pocket.zig b/zig/src/living/pocket.zig index aff4a4ad4a..f84950f5f0 100644 --- a/zig/src/living/pocket.zig +++ b/zig/src/living/pocket.zig @@ -8,10 +8,14 @@ const joint = @import("pocket_joint.zig"); const pocket_dump = @import("pocket_dump.zig"); const clock = @import("pocket_clock.zig"); const reading = @import("pocket_read.zig"); -const quieting = @import("pocket_quiet.zig"); -const loading = @import("pocket_load.zig"); const family = @import("family.zig"); const neuron_math = @import("neuron.zig"); +const shards = @import("shards.zig"); +const decouple = @import("pocket_decouple.zig"); +const fits = @import("pocket_fits.zig"); +const quieting = @import("pocket_quiet.zig"); +const retiring = @import("pocket_retire.zig"); +const subspace = @import("subspace.zig"); const Example = examples.Example; const Acting = lesson_route.Acting; @@ -24,6 +28,8 @@ const fit_steps = pocket_fit.fit_steps; const per_fact = 10; // neurons a fact takes, at the layers that tell its questions apart best const value_neurons = 4; // of those, the ones before its answer's value, when its answers show one +pub const kept_least: f32 = 0.5; // an earlier neuron refitted must still reach this on every one of its own fact's rows +pub const refit_above: f32 = 0.5; // an earlier neuron is refitted only where it fires above this on a new fact's rows /// Where a neuron fires: the reply's first row, the named subject's last token, or the row before the answer's value. pub const Key = enum(u2) { reply, subject, value }; @@ -32,25 +38,25 @@ pub const Key = enum(u2) { reply, subject, value }; pub const Mode = enum { auto, reply, subject, both }; // both: half at the subject, half at the reply (relation-aware) /// A neuron the open fact took. -const Taken = struct { slot: usize, neuron: usize, key: Key }; +pub const Taken = struct { slot: usize, neuron: usize, key: Key }; /// A neuron the open fact took, where it sits: its MoE layer, its index in that layer's pocket, its key. pub const Placed = struct { layer: usize, neuron: usize, key: Key }; /// A neuron a fact took, the rows it was fitted to fire on (in `pos`), and its fact's subject token (keyed on it). -const Learned = struct { slot: usize, neuron: usize, key: Key, start: usize, count: usize, subject: u32, lesson: u32 }; +pub const Learned = struct { slot: usize, neuron: usize, key: Key, start: usize, count: usize, subject: u32, lesson: u32 }; /// A read row: what it is to the open fact, whose key row it is (null: neither), its example and its place there. pub const Label = struct { kind: Kind, key: ?Key, ex: u32, row: u32 }; /// Another prompt's answer a subject neuron of the open fact fires on (most at `row`): it is to stay as it was. -const Keep = struct { ex: Example, row: usize }; +pub const Keep = struct { ex: Example, row: usize }; /// An earlier neuron the open fact fitted again; its input weights from before are kept for an undo. -const Refit = struct { slot: usize, neuron: usize }; +pub const Refit = struct { slot: usize, neuron: usize }; /// Whether environment variable `name` is set to `value`. -fn set(name: [*:0]const u8, value: []const u8) bool { +pub fn set(name: [*:0]const u8, value: []const u8) bool { const v = std.c.getenv(name) orelse return false; return std.mem.eql(u8, std.mem.span(v), value); } @@ -66,34 +72,34 @@ pub fn valueRow(ex: Example) ?usize { } /// What read row `l` is to neurons keyed `key`: their own key rows as read, every other row one they stay silent on. -fn kindFor(l: Label, key: Key) Kind { +pub fn kindFor(l: Label, key: Key) Kind { if (l.key == key) return l.kind; return if (l.kind == .steady) .steady else .other; } /// Whether layer l may hold a `key` neuron: a fifth to seven eighths in; a subject's to five eighths, where facts sit. -fn candidate(l: usize, layers: usize, key: Key) bool { +pub fn candidate(l: usize, layers: usize, key: Key) bool { const last = if (key == .subject) layers * 5 / 8 else layers * 7 / 8; return l >= layers / 5 and l <= last; } /// Strict layers first (silent on every row read), then most of the fact's questions on, then the widest least margin. -fn better(f: []const Fit, a: usize, b: usize) bool { +pub fn better(f: []const Fit, a: usize, b: usize) bool { if (f[a].fires != f[b].fires) return f[a].fires < f[b].fires; if (f[a].fact_on != f[b].fact_on) return f[a].fact_on > f[b].fact_on; return f[a].fact_least > f[b].fact_least; } -/// A pocket over trainer T (its inputs, residuals, nudges) for family F, and a host handing each layer to the forward. +/// A pocket over trainer T (its inputs, residuals, nudges) for family F. pub fn Pocket(comptime T: type, comptime F: family.Family) type { comptime F.check() catch unreachable; return struct { const Self = @This(); /// A pocket's neurons at each layer it sits at: a whole number of quantization groups of the expert's width. pub const neurons = F.neurons; - pub const of = F; // the family it learns into pub const swiglu = F.neuron.act == .swiglu; pub const gated = F.neuron.gated; + pub const fam = F; gpa: std.mem.Allocator, mode: Mode, // as asked (TF_SLIDE_POCKET_KEY), auto by default @@ -128,12 +134,12 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { keeps: std.ArrayList(Keep) = .empty, // other answers the open fact's subject neurons fire on refits: std.ArrayList(Refit) = .empty, // earlier neurons the open fact fitted again refit_up: std.ArrayList(f32) = .empty, // [refits, D]: their input weights from before + refit_gate: std.ArrayList(f32) = .empty, // SwiGLU: [refits, D], their gate rows from before lesson: u32 = 0, // the open fact's lesson, which its neurons record retired_lessons: std.ArrayList(u32) = .empty, // lessons a newer fact replaced: their answers no longer stay retired_marks: usize = 0, // retired_lessons before the last retire, which a put-back returns to retired: std.ArrayList([2]usize) = .empty, // the last retire's (slot, neuron), put back if the newer fact fails - retired_w: std.ArrayList(f32) = .empty, // [retired, 2, D]: their input and output weights from before - refit_gate: std.ArrayList(f32) = .empty, // SwiGLU: [refits, D], their gate rows from before + retired_w: std.ArrayList(f32) = .empty, // [retired, 2 or 3, D]: their input and output weights (and SwiGLU gate rows) from before phase: enum { read, fit, values, check, done } = .done, at: usize = 0, // the next example read, answer of a step, or held-out answer judged back: usize = 0, // held-out answers that came back token for token @@ -144,20 +150,123 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { v: values.State = .{}, // the open fact's outputs as they are fitted clock: clock.Clock = .{}, // where the open round's time goes read: reading.Seen = .{}, // what the last read pass read, which a lesson begun again over the same keeps + snap: Snap = .{}, // the pocket as the open fact's lesson found it, which taking the lesson out puts back + decoupled: bool = true, // no neuron's output moves another's input product (pocket_decouple.zig) + scales: decouple.Scales = .{}, // each slot's read scale, read once + above: decouple.Above = .{}, // what the neurons above each slot read, built as a values fit begins pub fn init(gpa: std.mem.Allocator) Self { const asked: Mode = if (std.c.getenv("TF_SLIDE_POCKET_KEY")) |v| std.meta.stringToEnum(Mode, std.mem.span(v)) orelse .auto else .auto; - return .{ .gpa = gpa, .mode = asked, .strict = !set("TF_SLIDE_POCKET_LEADS", "off"), .keeping = !set("TF_SLIDE_POCKET_KEEPS", "off"), .valuing = set("TF_SLIDE_POCKET_VALUES", "on"), .silencing = set("TF_SLIDE_POCKET_SAME", "silent"), .worst = set("TF_SLIDE_POCKET_REPLAY", "worst"), .joining = set("TF_SLIDE_POCKET_GROUP", "joint") }; + return .{ .gpa = gpa, .mode = asked, .strict = !set("TF_SLIDE_POCKET_LEADS", "off"), .keeping = !set("TF_SLIDE_POCKET_KEEPS", "off"), .valuing = set("TF_SLIDE_POCKET_VALUES", "on"), .silencing = set("TF_SLIDE_POCKET_SAME", "silent"), .worst = set("TF_SLIDE_POCKET_REPLAY", "worst"), .joining = set("TF_SLIDE_POCKET_GROUP", "joint"), .decoupled = decouple.on() }; } pub fn deinit(p: *Self) void { inline for (.{ "moe", "up", "down", "gate", "scratch", "used", "taken", "rows", "labels", "keeps", "refits", "refit_up", "refit_gate", "retired_lessons", "retired", "retired_w", "joint", "joint_down", "joint_answers", "learned", "pos", "subjects", "leads" }) |f| @field(p, f).deinit(p.gpa); p.read.deinit(p.gpa); p.v.deinit(p.gpa); + p.scales.deinit(p.gpa); + p.above.deinit(p.gpa); + p.snap.deinit(p.gpa); + } + + /// The pocket as a lesson found it: every neuron's weights, the neurons in use, what was learned so far. + const Snap = struct { + valid: bool = false, + up: std.ArrayList(f32) = .empty, + down: std.ArrayList(f32) = .empty, + gate: std.ArrayList(f32) = .empty, + used: std.ArrayList(usize) = .empty, + learned: usize = 0, + pos: usize = 0, + hash: u64 = 0, + + fn deinit(s: *Snap, gpa: std.mem.Allocator) void { + s.up.deinit(gpa); + s.down.deinit(gpa); + s.gate.deinit(gpa); + s.used.deinit(gpa); + } + }; + + /// The pocket's weights and neurons in use as one number: the same number, the same bits. + pub fn hash(p: *const Self) u64 { + var h = std.hash.Wyhash.init(0); + h.update(std.mem.sliceAsBytes(p.up.items)); + h.update(std.mem.sliceAsBytes(p.down.items)); + h.update(std.mem.sliceAsBytes(p.used.items)); + if (swiglu) h.update(std.mem.sliceAsBytes(p.gate.items)); + return h.final(); + } + + /// A new fact's lesson has begun (the pocket loaded, nothing of the lesson in it yet). + pub fn mark(p: *Self) !void { + const s = &p.snap; + inline for (.{ "up", "down", "gate", "used" }) |f| { + @field(s, f).clearRetainingCapacity(); + try @field(s, f).appendSlice(p.gpa, @field(p, f).items); + } + s.learned = p.learned.items.len; + s.pos = p.pos.items.len; + s.hash = p.hash(); + s.valid = true; + } + + /// The pocket put back as the open lesson found it (mark), each layer whose neurons changed handed to the. + fn restore(p: *Self, t: *T, host: anytype) !bool { + const s = &p.snap; + if (!s.valid or s.up.items.len != p.up.items.len or s.used.items.len != p.used.items.len) return false; + const n = neurons * p.hidden; + const was = p.hash(); + for (0..p.slots()) |j| { + const same = p.used.items[j] == s.used.items[j] and + std.mem.eql(f32, p.up.items[j * n ..][0..n], s.up.items[j * n ..][0..n]) and + std.mem.eql(f32, p.down.items[j * n ..][0..n], s.down.items[j * n ..][0..n]) and + (!swiglu or std.mem.eql(f32, p.gate.items[j * n ..][0..n], s.gate.items[j * n ..][0..n])); + if (same) continue; + @memcpy(p.up.items[j * n ..][0..n], s.up.items[j * n ..][0..n]); + @memcpy(p.down.items[j * n ..][0..n], s.down.items[j * n ..][0..n]); + if (swiglu) @memcpy(p.gate.items[j * n ..][0..n], s.gate.items[j * n ..][0..n]); + p.used.items[j] = s.used.items[j]; + try p.upload(t, host, j); + } + p.learned.shrinkRetainingCapacity(s.learned); + p.pos.shrinkRetainingCapacity(s.pos); + const now = p.hash(); + std.log.info("slide pocket: the lesson taken out: the pocket put back as the lesson found it ({x:0>16} -> {x:0>16}, {s})", .{ was, now, if (now == s.hash) "the same bits" else "NOT the same bits" }); + return true; + } + + /// The open fact's layers rounded as the shards will hold them. + pub fn asWritten(p: *Self, t: *T, host: anytype) !void { + const d = p.hidden; + const n = neurons * d; + var done: std.ArrayList(usize) = .empty; + defer done.deinit(p.gpa); + for (p.taken.items) |x| try mark1(p.gpa, &done, x.slot); + for (p.refits.items) |x| try mark1(p.gpa, &done, x.slot); + for (p.joint.items) |x| try mark1(p.gpa, &done, x.slot); + const rows = try p.gpa.alloc(f32, n); + defer p.gpa.free(rows); + const was = p.hash(); + for (done.items) |j| { + const up = p.up.items[j * n ..][0..n]; + const down = p.down.items[j * n ..][0..n]; + if (swiglu) { + neuron_math.upRow(F.neuron, up, rows); + try shards.roundAsWritten(F, p.gpa, neurons, d, &.{ p.gate.items[j * n ..][0..n], rows }, down); + neuron_math.fromUp(F.neuron, rows, up); + } else try shards.roundAsWritten(F, p.gpa, neurons, d, &.{up}, down); + try p.upload(t, host, j); + } + if (done.items.len > 0) std.log.info("slide pocket: {d} layers' neurons rounded as the shards hold them ({s})", .{ done.items.len, if (p.hash() == was) "already were" else "changed" }); + } + + fn mark1(gpa: std.mem.Allocator, list: *std.ArrayList(usize), j: usize) !void { + if (std.mem.indexOfScalar(usize, list.items, j) == null) try list.append(gpa, j); } /// The fact's neurons per key: as asked, or by how many answers show a value and questions name the subject. - fn pickSplit(p: *const Self, lists: []const []const Example, answered: []const Example) [3]usize { + pub fn pickSplit(p: *const Self, lists: []const []const Example, answered: []const Example) [3]usize { var valued: usize = 0; for (answered) |ex| valued += @intFromBool(valueRow(ex) != null); const on_value: usize = if (p.mode == .auto and p.valuing and valued > 0 and 2 * valued >= answered.len) value_neurons else 0; @@ -190,7 +299,7 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { return p.split[0] > 0 or (p.split[1] > 0 and subjectRow(ex) != null) or (p.split[2] > 0 and valueRow(ex) != null); } - fn slots(p: *const Self) usize { + pub fn slots(p: *const Self) usize { return p.moe.items.len; } @@ -212,47 +321,36 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { neuron_math.gateRow(F.neuron, p.neuron(p.up.items, slot, n, p.hidden), p.neuron(p.gate.items, slot, n, p.hidden)); } - fn load(p: *Self, t: *T, host: anytype) !void { + /// The pocket's neurons as the shards hold them, read once. + pub fn load(p: *Self, t: *T, host: anytype) !void { _ = t; - return loading.load(p, host); - } - - /// A replaced fact's neurons, (layer, neuron) each, zeroed where they sit; their places stay taken. - pub fn retire(p: *Self, t: *T, host: anytype, gone: []const [2]u16) !void { - try p.load(t, host); - const d = p.hidden; - p.retired.clearRetainingCapacity(); - p.retired_w.clearRetainingCapacity(); - p.retired_marks = p.retired_lessons.items.len; - for (gone) |g| { - const slot = std.mem.indexOfScalar(usize, p.moe.items, g[0]) orelse continue; - if (g[1] >= p.used.items[slot]) continue; - for (p.learned.items) |e| if (e.slot == slot and e.neuron == g[1] and std.mem.indexOfScalar(u32, p.retired_lessons.items, e.lesson) == null) try p.retired_lessons.append(p.gpa, e.lesson); - try p.retired.append(p.gpa, .{ slot, g[1] }); - try p.retired_w.appendSlice(p.gpa, p.neuron(p.up.items, slot, g[1], d)); - try p.retired_w.appendSlice(p.gpa, p.neuron(p.down.items, slot, g[1], d)); - @memset(p.neuron(p.up.items, slot, g[1], d), 0); - @memset(p.neuron(p.down.items, slot, g[1], d), 0); - try p.upload(t, host, slot); + if (p.moe.items.len > 0) return; + const lay = host.layout(); + if (lay.layers > 64) return error.TooManyLayers; // a step's nudges mark their layers in a u64 + p.hidden = lay.hidden; + p.layers = lay.layers; + for (0..lay.layers) |l| if (lay.learn.isSet(l)) try p.moe.append(p.gpa, l); + const n = neurons * lay.hidden; + try p.up.appendNTimes(p.gpa, 0, p.slots() * n); + try p.down.appendNTimes(p.gpa, 0, p.slots() * n); + try p.used.appendNTimes(p.gpa, 0, p.slots()); + if (swiglu) { + try p.gate.appendNTimes(p.gpa, 0, p.slots() * n); + try p.scratch.appendNTimes(p.gpa, 0, n); } - std.log.info("slide pocket: {d} neurons of replaced facts zeroed", .{gone.len}); - } - - /// The last retire undone: its neurons as they were (the fact that replaced theirs was not learned). - pub fn unretire(p: *Self, t: *T, host: anytype) !void { - try p.load(t, host); - const d = p.hidden; - for (p.retired.items, 0..) |r, i| { - @memcpy(p.neuron(p.up.items, r[0], r[1], d), p.retired_w.items[2 * i * d ..][0..d]); - @memcpy(p.neuron(p.down.items, r[0], r[1], d), p.retired_w.items[(2 * i + 1) * d ..][0..d]); - try p.upload(t, host, r[0]); + for (p.moe.items, 0..) |l, j| { + const up = p.up.items[j * n ..][0..n]; + const down = p.down.items[j * n ..][0..n]; + if (swiglu) { + p.used.items[j] = host.pocketReadSwiglu(l, p.gate.items[j * n ..][0..n], p.scratch.items, down); + neuron_math.fromUp(F.neuron, p.scratch.items, up); + } else p.used.items[j] = host.pocketRead(l, up, down); } - std.log.info("slide pocket: {d} neurons of replaced facts put back", .{p.retired.items.len}); - p.retired_lessons.shrinkRetainingCapacity(p.retired_marks); - p.retired.clearRetainingCapacity(); - p.retired_w.clearRetainingCapacity(); } + /// The rows a retired neuron keeps for a put-back: its input and output weights. + pub const retired_rows: usize = if (swiglu) 3 else 2; + /// A fact's lesson begun: its answers, more wordings, held-out answers and prompts its neurons stay silent on. pub fn begin(p: *Self, t: *T, host: anytype, answered: []const Example, prompts: []const Example, held: []const Example, steady: []const []const Example) !void { try p.load(t, host); @@ -274,9 +372,9 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { // the last fact's refits stay with it: kept with it, or already put back by its undo p.refits.clearRetainingCapacity(); p.refit_up.clearRetainingCapacity(); + p.refit_gate.clearRetainingCapacity(); p.joint.clearRetainingCapacity(); p.joint_down.clearRetainingCapacity(); - p.refit_gate.clearRetainingCapacity(); p.learned_before = p.learned.items.len; p.pos_before = p.pos.items.len; p.clock = .{}; @@ -303,8 +401,14 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { const before = t.count; const done = switch (p.phase) { .read => try reading.once(p, t), - .fit => try p.fitAll(t, host), - .values => try values.valueOnce(p, t, host), + .fit => try fits.fitAll(p, t, host), + .values => blk: { + const t0v = clock.mono(); + const was = p.v.judging; + const r = try values.valueOnce(p, t, host); + if (!was) clock.add(.values_host, clock.mono() - t0v); + break :blk r; + }, .check => try values.checkOnce(p, t, host), .done => true, }; @@ -321,6 +425,16 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { /// The open fact's neurons back to zero and free, and the earlier neurons it fitted again as they were. pub fn undo(p: *Self, t: *T, host: anytype) !void { const d = p.hidden; + if (try p.restore(t, host)) { + p.refits.clearRetainingCapacity(); + p.refit_up.clearRetainingCapacity(); + p.refit_gate.clearRetainingCapacity(); + p.joint.clearRetainingCapacity(); + p.joint_down.clearRetainingCapacity(); + p.joint_answers.clearRetainingCapacity(); + p.taken.clearRetainingCapacity(); + return; + } p.learned.shrinkRetainingCapacity(p.learned_before); p.pos.shrinkRetainingCapacity(p.pos_before); var i = p.taken.items.len; @@ -340,8 +454,8 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { } p.refits.clearRetainingCapacity(); p.refit_up.clearRetainingCapacity(); - try joint.putBack(p, t, host, d); p.refit_gate.clearRetainingCapacity(); + try joint.putBack(p, t, host, d); p.taken.clearRetainingCapacity(); } @@ -357,6 +471,15 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { } else try host.pocket(p.moe.items[slot], up, down, p.used.items[slot]); } + /// The highest layer whose read rows are ever used: the last any key's neuron may sit at. + pub fn readTop(p: *const Self) usize { + var top: usize = 0; + for (p.moe.items) |l| for (0..3) |k| if (candidate(l, p.layers, @fromBackingInt(@intCast(k)))) { + top = @max(top, l); + }; + return top; + } + /// Example i and its kind: the fact's answers, then its other wordings, held-out answers and the other prompts. pub fn pickRead(p: *const Self, i: usize) ?struct { ex: Example, kind: Kind } { var at = i; @@ -381,120 +504,34 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { } } - /// Every key's candidate layers fitted in threads, the best taken; then keeps found, earlier neurons refitted. - fn fitAll(p: *Self, t: *T, host: anytype) !bool { + /// The highest input product u x of the open lesson's neurons. + pub fn highest(p: *Self, t: *T, at: usize, rows: usize) f32 { const d = p.hidden; - const n = p.slots(); - const m = p.labels.items.len; - if (std.c.getenv("TF_SLIDE_POCKET_DUMP")) |dir| pocket_dump.write(p, std.mem.span(dir), p.learned_before, d) catch |e| std.log.warn("slide pocket: the read rows were not written: {t}", .{e}); - const kinds = try p.gpa.alloc(Kind, 3 * m); - defer p.gpa.free(kinds); - for (p.labels.items, 0..) |l, i| for (0..3) |k| { - kinds[k * m + i] = kindFor(l, @fromBackingInt(@intCast(k))); - }; - const us = try p.gpa.alloc(f32, 3 * n * d); - defer p.gpa.free(us); - const fits = try p.gpa.alloc(Fit, 3 * n); - defer p.gpa.free(fits); - @memset(fits, .{ .fires = std.math.maxInt(usize) }); - const t0 = clock.now(host.io); - const threads = try p.gpa.alloc(?std.Thread, 3 * n); - defer p.gpa.free(threads); - @memset(threads, null); - var fitted: usize = 0; - const below = F.neuron.margin; - for (0..3) |k| for (p.moe.items, 0..) |l, j| if (p.split[k] > 0 and candidate(l, p.layers, @fromBackingInt(@intCast(k)))) { - threads[k * n + j] = std.Thread.spawn(.{}, fitLayer, .{ p.gpa, p.rows.items, kinds[k * m ..][0..m], n, j, d, us[(k * n + j) * d ..][0..d], &fits[k * n + j], below }) catch null; - fitted += 1; - }; - for (0..3) |k| for (p.moe.items, 0..) |l, j| if (p.split[k] > 0 and candidate(l, p.layers, @fromBackingInt(@intCast(k)))) { - if (threads[k * n + j]) |th| th.join() else fitLayer(p.gpa, p.rows.items, kinds[k * m ..][0..m], n, j, d, us[(k * n + j) * d ..][0..d], &fits[k * n + j], below); - }; - const t1 = clock.now(host.io); - for (0..3) |k| if (p.split[k] > 0) { - const key: Key = @fromBackingInt(@intCast(k)); - var order: std.ArrayList(usize) = .empty; - defer order.deinit(p.gpa); - // a layer whose pocket is full is passed over - for (p.moe.items, 0..) |l, j| if (candidate(l, p.layers, key) and p.used.items[j] < neurons) try order.append(p.gpa, j); - if (order.items.len == 0) return error.PocketFull; - std.mem.sort(usize, order.items, @as([]const Fit, fits[k * n ..][0..n]), better); - for (order.items[0..@min(p.split[k], order.items.len)]) |j| try p.take(j, key, us[(k * n + j) * d ..][0..d], fits[k * n + j], kinds[k * m ..][0..m], d); - }; - p.logSources(d, m, kinds); - try p.findKeeps(d); - try quieting.quiet(p, t, host); - std.log.info("slide pocket: {d} candidate neurons fitted on {d} read rows in {d:.1} s; earlier neurons checked in {d:.1} s", .{ fitted, m, t1 - t0, clock.now(host.io) - t1 }); - try joint.find(p, d); - try p.v.begin(p.gpa, p.taken.items.len + p.joint.items.len, d, p.answered.len + p.joint_answers.items.len + p.keeps.items.len); - joint.seed(p, d); - p.next(.values); - return false; - } - - /// Logs each key's first neuron's firing share by source: answers, short and long wordings, held-out answers. - fn logSources(p: *const Self, d: usize, m: usize, kinds: []const Kind) void { - const n = p.slots(); - for (p.taken.items) |x| { - if (x.neuron + 1 != p.used.items[x.slot]) continue; - const k = @backingInt(x.key); - var on: [4]usize = @splat(0); - var all: [4]usize = @splat(0); - const u = p.neuron(@constCast(p.up.items), x.slot, x.neuron, d); - for (p.labels.items, 0..) |l, i| { - const kind = kinds[k * m + i]; - if (kind != .fact and kind != .held) continue; - const src: usize = if (l.ex < p.answered.len) 0 else if (l.ex < p.answered.len + p.prompts.len) (if (p.pickRead(l.ex).?.ex.ids.len > 60) 2 else 1) else 3; - all[src] += 1; - on[src] += @intFromBool(dotBf16(u, p.rows.items[(i * n + x.slot) * d ..][0..d]) >= 0.5); + var best: f32 = -std.math.inf(f32); + for (0..2) |which| { + const list = if (which == 0) p.taken.items else p.joint.items; + for (list) |x| { + const l = p.moe.items[x.slot]; + const u = p.neuron(p.up.items, x.slot, x.neuron, d); + for (0..rows) |r| best = @max(best, dotBf16(u, t.normed(l, at + r))); } - std.log.info("slide pocket: layer {d} at the {s} fires on answers {d}/{d}, short wordings {d}/{d}, long ones {d}/{d}, held-out {d}/{d}", .{ p.moe.items[x.slot], @tagName(x.key), on[0], all[0], on[1], all[1], on[2], all[2], on[3], all[3] }); } + return best; } - /// Slot j's next neuron taken for the open fact on `key`, its input weights `u` as fitted (`f`, on `kinds`). - fn take(p: *Self, j: usize, key: Key, u: []const f32, f: Fit, kinds: []const Kind, d: usize) !void { - const n = p.slots(); - const k = p.used.items[j]; - p.used.items[j] += 1; - try p.taken.append(p.gpa, .{ .slot = j, .neuron = k, .key = key }); - @memcpy(p.neuron(p.up.items, j, k, d), u); - p.gateFrom(j, k); - @memset(p.neuron(p.down.items, j, k, d), 0); - std.log.info("slide pocket: layer {d}, neuron {d}, at the {s}: on for {d:.0}% of the fact's questions (least {d:.2}), held-out {d:.0}% (mean {d:.2}); other prompts at most {d:.2}, other rows {d:.2}, {d} above zero", .{ p.moe.items[j], k, @tagName(key), 100 * f.fact_on, f.fact_least, 100 * f.held_on, f.held_mean, f.steady_most, f.other_most, f.fires }); - const start = p.pos.items.len / d; - for (kinds, 0..) |kind, i| if (kind == .fact) try p.pos.appendSlice(p.gpa, p.rows.items[(i * n + j) * d ..][0..d]); - const subject: u32 = if (key == .subject and p.subjects.items.len > 0) p.subjects.items[0] else 0; - try p.learned.append(p.gpa, .{ .slot = j, .neuron = k, .key = key, .start = start, .count = p.pos.items.len / d - start, .subject = subject, .lesson = p.lesson }); - } - - /// Other answers where the fact's subject neurons fire, each at its strongest row: these stay as they were. - fn findKeeps(p: *Self, d: usize) !void { - if (p.split[1] == 0 or !p.keeping) return; - const n = p.slots(); - var i: usize = 0; - while (i < p.labels.items.len) { - const which = p.labels.items[i].ex; - var most: f32 = 0; - var at: ?usize = null; - while (i < p.labels.items.len and p.labels.items[i].ex == which) : (i += 1) { - const l = p.labels.items[i]; - // the fact's own mentions are free but already its answers, not ones to keep - if (l.kind != .none or l.ex < p.answered.len + p.prompts.len + p.held.len) continue; - var sum: f32 = 0; - for (p.taken.items) |x| if (x.key == .subject) { - sum += @max(p.act(x.slot, x.neuron, p.rows.items[(i * n + x.slot) * d ..][0..d]), 0); - }; - if (sum > most) { - most = sum; - at = l.row; - } - } - const row = at orelse continue; - const ex = p.pickRead(which).?.ex; - if (ex.ids.len > ex.start + 1) try p.keeps.append(p.gpa, .{ .ex = ex, .row = row }); - } - std.log.info("slide pocket: {d} other answers name the fact's subject where its neurons fire; they are to stay as they were", .{p.keeps.items.len}); + /// Earlier neurons firing on this fact's rows refitted silent there (pocket_quiet.zig). + pub fn quiet(p: *Self, t: *T, host: anytype) !void { + return quieting.quiet(p, t, host); + } + + /// A replaced fact's neurons, (layer, neuron) each, zeroed where they sit (pocket_retire.zig). + pub fn retire(p: *Self, t: *T, host: anytype, gone: []const [2]u16) !void { + return retiring.retire(p, t, host, gone); + } + + /// The last retire undone (pocket_retire.zig). + pub fn unretire(p: *Self, t: *T, host: anytype) !void { + return retiring.unretire(p, t, host); } /// Whether no neuron is in use at any layer. @@ -503,7 +540,7 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { return true; } - /// Learned neurons into the shards, then into the forward as the shards hold them (quantized); the bytes. + /// Learned neurons into the shards, then into the forward as the shards hold them (quantized). pub fn save(p: *Self, t: *T, host: anytype) !usize { const bytes = if (swiglu) blk: { // written as gate rows and up rows u / sharp, handed back as written: u from the up rows again @@ -515,6 +552,7 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { break :blk got; } else try host.pocketSave(p.moe.items, neurons, p.up.items, p.down.items); for (0..p.slots()) |j| if (p.used.items[j] > 0) try p.upload(t, host, j); + p.snap.valid = false; // the shards hold this pocket now: no lesson before it is taken out to an older one return bytes; } @@ -536,7 +574,7 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { } /// The examples the read phase goes through: the fact's own, then every prompt its neurons stay silent on. - fn reads(p: *const Self) usize { + pub fn reads(p: *const Self) usize { var n = p.answered.len + p.prompts.len + p.held.len; for (p.steady) |xs| n += xs.len; return n; @@ -550,37 +588,3 @@ pub fn Pocket(comptime T: type, comptime F: family.Family) type { } }; } - -test "a fact keys as many neurons on its subject as the share of its questions that name it, at least half, else none" { - const P = Pocket(struct {}, @import("families.zig").nemotron_h); - var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; - defer p.deinit(); - // ids: a question's tokens, the subject's last token at row 2, the answer from row 4 - const ids = [_]u32{ 1, 2, 7, 3, 4, 5 }; - const named: Example = .{ .ids = &ids, .start = 4, .decide = 3, .subject = 2 }; - const plain: Example = .{ .ids = &ids, .start = 4, .decide = 3 }; - try std.testing.expectEqual([3]usize{ 5, 5, 0 }, p.pickSplit(&.{ &.{ named, plain }, &.{} }, &.{})); - try std.testing.expectEqual([3]usize{ 0, 10, 0 }, p.pickSplit(&.{ &.{ named, named }, &.{named} }, &.{})); - try std.testing.expectEqual([3]usize{ 3, 7, 0 }, p.pickSplit(&.{&.{ named, named, plain }}, &.{})); - try std.testing.expectEqual([3]usize{ 10, 0, 0 }, p.pickSplit(&.{&.{ named, plain, plain }}, &.{})); - try std.testing.expectEqual([3]usize{ 10, 0, 0 }, p.pickSplit(&.{&.{}}, &.{})); - // answers whose value comes after row 4: none there unless asked, then four, the rest shared as before - const valued: Example = .{ .ids = &ids, .start = 4, .decide = 3, .subject = 2, .value = 4 }; - try std.testing.expectEqual([3]usize{ 0, 10, 0 }, p.pickSplit(&.{&.{ valued, valued }}, &.{ valued, valued })); - p.valuing = true; - try std.testing.expectEqual([3]usize{ 0, 6, 4 }, p.pickSplit(&.{&.{ valued, valued }}, &.{ valued, valued })); - p.mode = .subject; - try std.testing.expectEqual([3]usize{ 0, 10, 0 }, p.pickSplit(&.{&.{ named, plain, plain }}, &.{})); - p.mode = .reply; - try std.testing.expectEqual([3]usize{ 10, 0, 0 }, p.pickSplit(&.{&.{ named, named }}, &.{})); -} - -test "a read row is a fact's row only to its own key's neurons; another prompt's mention of the subject is left free" { - try std.testing.expectEqual(Kind.fact, kindFor(.{ .kind = .fact, .key = .subject, .ex = 0, .row = 2 }, .subject)); - try std.testing.expectEqual(Kind.other, kindFor(.{ .kind = .fact, .key = .subject, .ex = 0, .row = 2 }, .reply)); - try std.testing.expectEqual(Kind.held, kindFor(.{ .kind = .held, .key = .reply, .ex = 3, .row = 7 }, .reply)); - try std.testing.expectEqual(Kind.steady, kindFor(.{ .kind = .steady, .key = .reply, .ex = 1, .row = 9 }, .subject)); - try std.testing.expectEqual(Kind.none, kindFor(.{ .kind = .none, .key = .subject, .ex = 1, .row = 4 }, .subject)); - try std.testing.expectEqual(Kind.other, kindFor(.{ .kind = .none, .key = .subject, .ex = 1, .row = 4 }, .reply)); - try std.testing.expectEqual(Kind.other, kindFor(.{ .kind = .other, .key = null, .ex = 1, .row = 5 }, .subject)); -} diff --git a/zig/src/living/pocket_clock.zig b/zig/src/living/pocket_clock.zig index f4b539472b..36620e0801 100644 --- a/zig/src/living/pocket_clock.zig +++ b/zig/src/living/pocket_clock.zig @@ -23,6 +23,7 @@ pub const Clock = struct { /// The round's line, then the counts cleared for the next round. pub fn end(c: *Clock) void { + logDetail(c.round); const s = c.seconds; var total: f64 = 0; for (s) |x| total += x; @@ -35,3 +36,34 @@ pub const Clock = struct { pub fn now(io: std.Io) f64 { return @as(f64, @floatFromInt(std.Io.Clock.awake.now(io).toNanoseconds())) / 1e9; } + +/// Seconds on the monotonic clock, for the detail sections below (no Io at hand). +pub fn mono() f64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(f64, @floatFromInt(ts.sec)) + @as(f64, @floatFromInt(ts.nsec)) / 1e9; +} + +/// Where a lesson's fitting spends its time inside the round's parts (TF_SLIDE_CLOCK=detail logs it a round). +pub const Section = enum { read_pass, read_copy, read_tap, fit_layers, fit_quiet, values_pass, values_host, judge_pass }; +pub var detail: [std.enums.values(Section).len]f64 = @splat(0); +pub var detail_n: [std.enums.values(Section).len]usize = @splat(0); + +pub fn add(s: Section, seconds: f64) void { + detail[@backingInt(s)] += seconds; + detail_n[@backingInt(s)] += 1; +} + +/// The sections' line, logged and cleared (only with TF_SLIDE_CLOCK=detail). +pub fn logDetail(round: usize) void { + defer { + detail = @splat(0); + detail_n = @splat(0); + } + const v = std.c.getenv("TF_SLIDE_CLOCK") orelse return; + if (!std.mem.eql(u8, std.mem.span(v), "detail")) return; + var buf: [1024]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + for (std.enums.values(Section), 0..) |sec, i| w.print(" {t} {d:.1} s ({d})", .{ sec, detail[i], detail_n[i] }) catch {}; + std.log.info("slide pocket: round {d} detail:{s}", .{ round, w.buffered() }); +} diff --git a/zig/src/living/pocket_decouple.zig b/zig/src/living/pocket_decouple.zig new file mode 100644 index 0000000000..1cbb6e9d0a --- /dev/null +++ b/zig/src/living/pocket_decouple.zig @@ -0,0 +1,171 @@ +//! Pocket neurons kept from driving one another along the residual stream. +const std = @import("std"); +const subspace = @import("subspace.zig"); +const pocket_fit = @import("pocket_fit.zig"); + +const Kind = pocket_fit.Kind; +const Fit = pocket_fit.Fit; + +/// Whether lessons keep pocket neurons decoupled (the default). +pub fn on() bool { + const v = std.c.getenv("TF_SLIDE_POCKET_COUPLE") orelse return true; + return !std.mem.eql(u8, std.mem.span(v), "on"); +} + +/// Each slot's read scale. +pub const Scales = struct { + rows: std.ArrayList(f32) = .empty, + + pub fn deinit(s: *Scales, gpa: std.mem.Allocator) void { + s.rows.deinit(gpa); + } + + pub fn get(s: *Scales, p: anytype, t: anytype) ![]const f32 { + const d = p.hidden; + const n = p.moe.items.len; + if (s.rows.items.len == n * d) return s.rows.items; + s.rows.clearRetainingCapacity(); + try s.rows.appendNTimes(p.gpa, 1, n * d); + const T = @TypeOf(t.*); + if (comptime @hasDecl(T, "readScale")) { + for (p.moe.items, 0..) |l, j| try t.readScale(l, s.rows.items[j * d ..][0..d]); + } + return s.rows.items; + } +}; + +/// v less its part along the first `count` orthonormal rows of `basis` ([*, d]), twice for accuracy. +pub fn project(v: []f32, basis: []const f32, count: usize, d: usize) void { + for (0..2) |_| for (0..count) |r| { + const b = basis[r * d ..][0..d]; + subspace.axpy(v, -subspace.dot(v, b), b); + }; +} + +/// `v` added to the orthonormal rows `basis` if it is not (nearly) in their span: Gram-Schmidt, run twice. +fn add(gpa: std.mem.Allocator, basis: *std.ArrayList(f32), v: []f32, d: usize) !bool { + const before = @sqrt(subspace.dot(v, v)); + if (before == 0) return false; + project(v, basis.items, basis.items.len / d, d); + const len = @sqrt(subspace.dot(v, v)); + if (len <= 1e-4 * before) return false; + for (v) |*x| x.* /= len; + try basis.appendSlice(gpa, v); + return true; +} + +/// What the neurons above each slot read: orthonormal rows built from the top slot down. +pub const Above = struct { + rows: std.ArrayList(f32) = .empty, + above: std.ArrayList(usize) = .empty, + + pub fn deinit(a: *Above, gpa: std.mem.Allocator) void { + a.rows.deinit(gpa); + a.above.deinit(gpa); + } + + pub fn build(a: *Above, p: anytype, scales: []const f32) !void { + const d = p.hidden; + const n = p.moe.items.len; + a.rows.clearRetainingCapacity(); + a.above.clearRetainingCapacity(); + try a.above.appendNTimes(p.gpa, 0, n); + const v = try p.gpa.alloc(f32, d); + defer p.gpa.free(v); + var j = n; + while (j > 0) { + j -= 1; + a.above.items[j] = a.rows.items.len / d; + for (0..p.used.items[j]) |k| { + const u = p.neuron(p.up.items, j, k, d); + for (v, u, scales[j * d ..][0..d]) |*o, x, s| o.* = x * s; + _ = try add(p.gpa, &a.rows, v, d); + } + } + } + + /// Slot j's output row `v` off what every neuron above it reads. + pub fn keepOff(a: *const Above, v: []f32, j: usize, d: usize) void { + project(v, a.rows.items, a.above.items[j], d); + } +}; + +/// What the neurons below slot j write where it reads: orthonormal rows of s_j ⊙ v_i for every live output v_i at a. +pub fn below(p: anytype, gpa: std.mem.Allocator, scales: []const f32, j: usize, out: *std.ArrayList(f32)) !usize { + const d = p.hidden; + out.clearRetainingCapacity(); + const v = try gpa.alloc(f32, d); + defer gpa.free(v); + for (0..j) |i| for (0..p.used.items[i]) |k| { + const w = p.neuron(p.down.items, i, k, d); + for (v, w, scales[j * d ..][0..d]) |*o, x, s| o.* = x * s; + _ = try add(gpa, out, v, d); + }; + return out.items.len / d; +} + +/// How input row `u` (unscaled, as a neuron multiplies x) sits on each kind of read row `xs`, as pocket_fit reports it. +pub fn evaluate(xs: []const []const u16, kinds: []const Kind, u: []const f32, gpa: std.mem.Allocator) !Fit { + const copy = try gpa.dupe(f32, u); + defer gpa.free(copy); + return pocket_fit.finish(xs, kinds, copy, 1, 1); +} + +test "an output kept off what the neurons above read moves none of their products; a slot's own and lower ones are free" { + const gpa = std.testing.allocator; + const d = 32; + var prng = std.Random.DefaultPrng.init(5); + const r = prng.random(); + const P = struct { + gpa: std.mem.Allocator, + hidden: usize, + moe: std.ArrayList(usize) = .empty, + up: std.ArrayList(f32) = .empty, + down: std.ArrayList(f32) = .empty, + used: std.ArrayList(usize) = .empty, + pub fn neuron(_: *const @This(), which: []f32, slot: usize, n: usize, dd: usize) []f32 { + return which[(slot * 4 + n) * dd ..][0..dd]; + } + }; + var p: P = .{ .gpa = gpa, .hidden = d }; + defer { + p.moe.deinit(gpa); + p.up.deinit(gpa); + p.down.deinit(gpa); + p.used.deinit(gpa); + } + try p.moe.appendSlice(gpa, &.{ 3, 5, 9 }); + try p.used.appendSlice(gpa, &.{ 2, 3, 1 }); + try p.up.appendNTimes(gpa, 0, 3 * 4 * d); + try p.down.appendNTimes(gpa, 0, 3 * 4 * d); + for (p.up.items, p.down.items) |*u, *v| { + u.* = r.floatNorm(f32); + v.* = r.floatNorm(f32); + } + const scales = try gpa.alloc(f32, 3 * d); + defer gpa.free(scales); + for (scales) |*s| s.* = 0.5 + r.float(f32); + var a: Above = .{}; + defer a.deinit(gpa); + try a.build(&p, scales); + try std.testing.expectEqualSlices(usize, &.{ 4, 1, 0 }, a.above.items); + // slot 0's first output, kept off: every neuron at slots 1 and 2 reads (s ⊙ u) . v = 0; slot 0's own do not + const v = p.neuron(p.down.items, 0, 0, d); + a.keepOff(v, 0, d); + for (1..3) |j| for (0..p.used.items[j]) |k| { + var dot: f32 = 0; + for (p.neuron(p.up.items, j, k, d), scales[j * d ..][0..d], v) |u, s, x| dot += u * s * x; + try std.testing.expectApproxEqAbs(@as(f32, 0), dot, 1e-4); + }; + // an input row at slot 2 kept off what slots 0 and 1 write there reads none of their outputs + var basis: std.ArrayList(f32) = .empty; + defer basis.deinit(gpa); + try std.testing.expectEqual(@as(usize, 5), try below(&p, gpa, scales, 2, &basis)); + const u = p.neuron(p.up.items, 2, 0, d); + project(u, basis.items, 5, d); + for (0..2) |i| for (0..p.used.items[i]) |k| { + var dot: f32 = 0; + for (u, scales[2 * d ..][0..d], p.neuron(p.down.items, i, k, d)) |x, s, w| dot += x * s * w; + try std.testing.expectApproxEqAbs(@as(f32, 0), dot, 1e-4); + }; +} diff --git a/zig/src/living/pocket_fit.zig b/zig/src/living/pocket_fit.zig index ab37028d73..296860701b 100644 --- a/zig/src/living/pocket_fit.zig +++ b/zig/src/living/pocket_fit.zig @@ -147,6 +147,76 @@ pub fn fit(gpa: std.mem.Allocator, xs: []const []const u16, kinds: []const Kind, return f; } +/// A neuron's fit as the trainer runs its Adam steps on the device. +pub const DeviceFit = struct { rows: []const u16, slots: usize, slot: usize, d: usize, kinds: []const Kind, u: []f32, inv: f32, below: f32, steps: usize }; + +/// fit's start for a cold fit with no fixed rows, as fit runs it. +pub fn prepare(gpa: std.mem.Allocator, xs: []const []const u16, kinds: []const Kind, d: usize, u: []f32) !struct { scale: f32, inv: f32 } { + const n = kinds.len; + var scale: f32 = 0; + for (xs) |x| scale += @sqrt(squares(x)); + scale /= @floatFromInt(@max(n, 1)); + const inv = 1 / scale; + var counts: [5]f32 = @splat(0); + for (kinds) |k| counts[@backingInt(k)] += 1; + const w = try gpa.alloc(f32, 2 * d); + defer gpa.free(w); + @memset(w, 0); + const mean_fact = w[0..d]; + const mean_rest = w[d..][0..d]; + for (kinds, xs) |k, x| switch (k) { + .fact => axpyRow(mean_fact, inv / @max(counts[0], 1), x), + .steady, .other => axpyRow(mean_rest, inv / @max(counts[2] + counts[3], 1), x), + .held, .none => {}, + }; + for (u, mean_fact, mean_rest) |*o, a, b| o.* = a - b; + const at_fact = subspace.dot(u, mean_fact); + if (at_fact > 0) for (u) |*o| { + o.* /= at_fact; + }; + return .{ .scale = scale, .inv = inv }; +} + +/// fit's end: how `u` (scaled) sits on each kind of row, then `u` back out of the scaled space. +pub fn finish(xs: []const []const u16, kinds: []const Kind, u: []f32, inv: f32, scale: f32) Fit { + var counts: [5]f32 = @splat(0); + for (kinds) |k| counts[@backingInt(k)] += 1; + var f: Fit = .{ .fact_least = std.math.inf(f32), .steady_most = -std.math.inf(f32), .other_most = -std.math.inf(f32) }; + for (kinds, xs) |k, x| { + const zi = dotRow(u, x) * inv; + switch (k) { + .fact => { + f.fact_least = @min(f.fact_least, zi); + f.fact_on += @floatFromInt(@intFromBool(zi >= 0.5)); + }, + .held => { + f.held_mean += if (zi > 0) zi * zi else 0; + f.held_on += @floatFromInt(@intFromBool(zi >= 0.5)); + }, + .steady => { + f.steady_most = @max(f.steady_most, zi); + f.fires += @intFromBool(zi > 0); + }, + .other => { + f.other_most = @max(f.other_most, zi); + f.fires += @intFromBool(zi > 0); + }, + .none => {}, + } + } + f.fact_on /= @max(counts[0], 1); + f.held_on /= @max(counts[1], 1); + f.held_mean /= @max(counts[1], 1); + for (u) |*o| o.* /= scale; + return f; +} + +/// Adam's two bias corrections at step s, as fit's steps form them. +pub fn corrections(s: usize) [2]f32 { + const tt: f32 = @floatFromInt(s); + return .{ 1 - std.math.pow(f32, 0.9, tt), 1 - std.math.pow(f32, 0.999, tt) }; +} + const V = @Vector(8, f32); /// Eight bf16 values widened to f32, exactly. @@ -160,7 +230,7 @@ fn bf(b: u16) f32 { } /// a . b for f32 `a` and bf16 `b`: four sums of eight lanes, so no add waits on the one before it. -fn dotRow(a: []const f32, b: []const u16) f32 { +pub fn dotRow(a: []const f32, b: []const u16) f32 { var acc: [4]V = @splat(@splat(0)); var i: usize = 0; while (i + 32 <= a.len) : (i += 32) { diff --git a/zig/src/living/pocket_fits.zig b/zig/src/living/pocket_fits.zig new file mode 100644 index 0000000000..c05fa9bd80 --- /dev/null +++ b/zig/src/living/pocket_fits.zig @@ -0,0 +1,240 @@ +//! A pocket lesson's input fits: every candidate layer fitted (host or device), kept off lower outputs, the best taken. +const std = @import("std"); +const pk = @import("pocket.zig"); +const pocket_fit = @import("pocket_fit.zig"); +const decouple = @import("pocket_decouple.zig"); +const subspace = @import("subspace.zig"); +const clock = @import("pocket_clock.zig"); +const pocket_dump = @import("pocket_dump.zig"); +const joint = @import("pocket_joint.zig"); +const quieting = @import("pocket_quiet.zig"); +const Kind = pocket_fit.Kind; +const Fit = pocket_fit.Fit; +const fit = pocket_fit.fit; +const fitLayer = pocket_fit.fitLayer; +const dotBf16 = pocket_fit.dotBf16; +const fit_steps = pocket_fit.fit_steps; + +/// Every key's candidate layers fitted in threads, the best taken; then keeps found, earlier neurons refitted. +pub fn fitAll(p: anytype, t: anytype, host: anytype) !bool { + const d = p.hidden; + const n = p.slots(); + const m = p.labels.items.len; + if (std.c.getenv("TF_SLIDE_POCKET_DUMP")) |dir| pocket_dump.write(p, std.mem.span(dir), p.learned_before, d) catch |e| std.log.warn("slide pocket: the read rows were not written: {t}", .{e}); + const kinds = try p.gpa.alloc(Kind, 3 * m); + defer p.gpa.free(kinds); + for (p.labels.items, 0..) |l, i| for (0..3) |k| { + kinds[k * m + i] = pk.kindFor(l, @fromBackingInt(@intCast(k))); + }; + const us = try p.gpa.alloc(f32, 3 * n * d); + defer p.gpa.free(us); + const fits = try p.gpa.alloc(Fit, 3 * n); + defer p.gpa.free(fits); + @memset(fits, .{ .fires = std.math.maxInt(usize) }); + const t0 = clock.now(host.io); + const below = @TypeOf(p.*).fam.neuron.margin; + var fitted: usize = 0; + for (0..3) |k| for (p.moe.items) |l| if (p.split[k] > 0 and pk.candidate(l, p.layers, @fromBackingInt(@intCast(k)))) { + fitted += 1; + }; + const device = comptime @hasDecl(@TypeOf(t.*), "fitDevice"); + if (device and !pk.set("TF_SLIDE_FIT", "host")) { + try fitOnDevice(p, t, kinds, us, fits, m, below); + } else try fitOnHost(p, kinds, us, fits, m, below); + if (p.decoupled) try inputsOff(p, t, kinds, us, fits, m); + const t1 = clock.now(host.io); + clock.add(.fit_layers, t1 - t0); + for (0..3) |k| if (p.split[k] > 0) { + const key: pk.Key = @fromBackingInt(@intCast(k)); + var order: std.ArrayList(usize) = .empty; + defer order.deinit(p.gpa); + // a layer whose pocket is full is passed over + for (p.moe.items, 0..) |l, j| if (pk.candidate(l, p.layers, key) and p.used.items[j] < @TypeOf(p.*).neurons) try order.append(p.gpa, j); + if (order.items.len == 0) return error.PocketFull; + std.mem.sort(usize, order.items, @as([]const Fit, fits[k * n ..][0..n]), pk.better); + for (order.items[0..@min(p.split[k], order.items.len)]) |j| try take(p, j, key, us[(k * n + j) * d ..][0..d], fits[k * n + j], kinds[k * m ..][0..m], d); + }; + logSources(p, d, m, kinds); + try quieting.findKeeps(p, d); + const tq = clock.now(host.io); + try p.quiet(t, host); + clock.add(.fit_quiet, clock.now(host.io) - tq); + std.log.info("slide pocket: {d} candidate @TypeOf(p.*).neurons fitted on {d} read rows in {d:.1} s; earlier @TypeOf(p.*).neurons checked in {d:.1} s", .{ fitted, m, t1 - t0, clock.now(host.io) - t1 }); + try joint.find(p, d); + try p.v.begin(p.gpa, p.taken.items.len + p.joint.items.len, d, p.answered.len + p.joint_answers.items.len + p.keeps.items.len); + joint.seed(p, d); + p.next(.values); + return false; +} + +/// Every key's candidate layers fitted in threads on the host (pocket_fit.fitLayer), into us and fits. +pub fn fitOnHost(p: anytype, kinds: []const Kind, us: []f32, fits: []Fit, m: usize, below: f32) !void { + const d = p.hidden; + const n = p.slots(); + const threads = try p.gpa.alloc(?std.Thread, 3 * n); + defer p.gpa.free(threads); + @memset(threads, null); + for (0..3) |k| for (p.moe.items, 0..) |l, j| if (p.split[k] > 0 and pk.candidate(l, p.layers, @fromBackingInt(@intCast(k)))) { + threads[k * n + j] = std.Thread.spawn(.{}, fitLayer, .{ p.gpa, p.rows.items, kinds[k * m ..][0..m], n, j, d, us[(k * n + j) * d ..][0..d], &fits[k * n + j], below }) catch null; + }; + for (0..3) |k| for (p.moe.items, 0..) |l, j| if (p.split[k] > 0 and pk.candidate(l, p.layers, @fromBackingInt(@intCast(k)))) { + if (threads[k * n + j]) |th| th.join() else fitLayer(p.gpa, p.rows.items, kinds[k * m ..][0..m], n, j, d, us[(k * n + j) * d ..][0..d], &fits[k * n + j], below); + }; +} + +/// The same fits with their Adam steps on the trainer's device (T.fitDevice). +pub fn fitOnDevice(p: anytype, t: anytype, kinds: []const Kind, us: []f32, fits: []Fit, m: usize, below: f32) !void { + const d = p.hidden; + const n = p.slots(); + const Job = struct { k: usize, j: usize, xs: [][]const u16 = &.{}, scale: f32 = 0, inv: f32 = 0, failed: bool = false }; + var jobs: std.ArrayList(Job) = .empty; + defer { + for (jobs.items) |jb| p.gpa.free(jb.xs); + jobs.deinit(p.gpa); + } + for (0..3) |k| for (p.moe.items, 0..) |l, j| if (p.split[k] > 0 and pk.candidate(l, p.layers, @fromBackingInt(@intCast(k)))) { + const xs = try p.gpa.alloc([]const u16, m); + for (xs, 0..) |*x, i| x.* = p.rows.items[(i * n + j) * d ..][0..d]; + try jobs.append(p.gpa, .{ .k = k, .j = j, .xs = xs }); + }; + const Ends = struct { + fn start(gpa: std.mem.Allocator, jb: *Job, ks: []const Kind, u: []f32, dd: usize) void { + const got = pocket_fit.prepare(gpa, jb.xs, ks, dd, u) catch { + jb.failed = true; + return; + }; + jb.scale = got.scale; + jb.inv = got.inv; + } + fn end(jb: *Job, ks: []const Kind, u: []f32, f: *Fit) void { + f.* = pocket_fit.finish(jb.xs, ks, u, jb.inv, jb.scale); + } + }; + var threads: [192]?std.Thread = @splat(null); + if (jobs.items.len > threads.len) return fitOnHost(p, kinds, us, fits, m, below); + for (jobs.items, threads[0..jobs.items.len]) |*jb, *th| th.* = std.Thread.spawn(.{}, Ends.start, .{ p.gpa, jb, kinds[jb.k * m ..][0..m], us[(jb.k * n + jb.j) * d ..][0..d], d }) catch null; + for (jobs.items, threads[0..jobs.items.len]) |*jb, th| if (th) |x| x.join() else Ends.start(p.gpa, jb, kinds[jb.k * m ..][0..m], us[(jb.k * n + jb.j) * d ..][0..d], d); + for (jobs.items) |jb| if (jb.failed) return error.OutOfMemory; + const dev = try p.gpa.alloc(pocket_fit.DeviceFit, jobs.items.len); + defer p.gpa.free(dev); + for (jobs.items, dev) |jb, *x| x.* = .{ .rows = p.rows.items, .slots = n, .slot = jb.j, .d = d, .kinds = kinds[jb.k * m ..][0..m], .u = us[(jb.k * n + jb.j) * d ..][0..d], .inv = jb.inv, .below = below, .steps = fit_steps }; + try t.fitDevice(dev); + @memset(threads[0..jobs.items.len], null); + for (jobs.items, threads[0..jobs.items.len]) |*jb, *th| th.* = std.Thread.spawn(.{}, Ends.end, .{ jb, kinds[jb.k * m ..][0..m], us[(jb.k * n + jb.j) * d ..][0..d], &fits[jb.k * n + jb.j] }) catch null; + for (jobs.items, threads[0..jobs.items.len]) |*jb, th| if (th) |x| x.join() else Ends.end(jb, kinds[jb.k * m ..][0..m], us[(jb.k * n + jb.j) * d ..][0..d], &fits[jb.k * n + jb.j]); + if (std.c.getenv("TF_SLIDE_FIT_CHECK") != null) { + const us2 = try p.gpa.dupe(f32, us); + defer p.gpa.free(us2); + const fits2 = try p.gpa.dupe(Fit, fits); + defer p.gpa.free(fits2); + try fitOnHost(p, kinds, us2, fits2, m, below); + var same: usize = 0; + for (jobs.items) |jb| { + const at = jb.k * n + jb.j; + const eq = std.mem.eql(u8, std.mem.sliceAsBytes(us[at * d ..][0..d]), std.mem.sliceAsBytes(us2[at * d ..][0..d])) and std.meta.eql(fits[at], fits2[at]); + same += @intFromBool(eq); + } + std.log.info("slide pocket: fit check: {d} of {d} @TypeOf(p.*).neurons fitted on the device have the host's bits", .{ same, jobs.items.len }); + } +} + +/// Every candidate neuron's input row kept off what the live neurons below its layer write there. +pub fn inputsOff(p: anytype, t: anytype, kinds: []const Kind, us: []f32, fits: []Fit, m: usize) !void { + const n = p.slots(); + const scales = try p.scales.get(p, t); + const Job = struct { j: usize, dirs: usize = 0, failed: bool = false, lost: f32 = 0, least: [3]f32 = @splat(0) }; + const jobs = try p.gpa.alloc(Job, n); + defer p.gpa.free(jobs); + for (jobs, 0..) |*jb, j| jb.* = .{ .j = j }; + const Run = struct { + fn one(pp: anytype, jb: *Job, sc: []const f32, ks: []const Kind, uu: []f32, ff: []Fit, mm: usize) void { + const dd = pp.hidden; + const nn = pp.slots(); + var any = false; + for (0..3) |k| any = any or (pp.split[k] > 0 and pk.candidate(pp.moe.items[jb.j], pp.layers, @fromBackingInt(@intCast(k))) and ff[k * nn + jb.j].fires != std.math.maxInt(usize)); + if (!any) return; + var basis: std.ArrayList(f32) = .empty; + defer basis.deinit(pp.gpa); + jb.dirs = decouple.below(pp, pp.gpa, sc, jb.j, &basis) catch { + jb.failed = true; + return; + }; + if (jb.dirs == 0) return; + const xs = pp.gpa.alloc([]const u16, mm) catch { + jb.failed = true; + return; + }; + defer pp.gpa.free(xs); + for (xs, 0..) |*x, i| x.* = pp.rows.items[(i * nn + jb.j) * dd ..][0..dd]; + for (0..3) |k| { + const at = k * nn + jb.j; + if (pp.split[k] == 0 or !pk.candidate(pp.moe.items[jb.j], pp.layers, @fromBackingInt(@intCast(k))) or ff[at].fires == std.math.maxInt(usize)) continue; + const u = uu[at * dd ..][0..dd]; + const was = subspace.dot(u, u); + decouple.project(u, basis.items, jb.dirs, dd); + jb.lost = @max(jb.lost, 1 - subspace.dot(u, u) / @max(was, 1e-30)); + jb.least[k] = ff[at].fact_least; + ff[at] = decouple.evaluate(xs, ks[k * mm ..][0..mm], u, pp.gpa) catch { + jb.failed = true; + return; + }; + } + } + }; + var threads: [192]?std.Thread = @splat(null); + const k_n = @min(n, threads.len); + for (jobs[0..k_n], threads[0..k_n]) |*jb, *th| th.* = std.Thread.spawn(.{}, Run.one, .{ p, jb, scales, kinds, us, fits, m }) catch null; + for (jobs[0..k_n], threads[0..k_n]) |*jb, th| if (th) |x| x.join() else Run.one(p, jb, scales, kinds, us, fits, m); + for (jobs[k_n..]) |*jb| Run.one(p, jb, scales, kinds, us, fits, m); + var most: usize = 0; + var lost: f32 = 0; + var drop: f32 = 0; + for (jobs) |jb| { + if (jb.failed) return error.OutOfMemory; + most = @max(most, jb.dirs); + lost = @max(lost, jb.lost); + for (0..3) |k| if (jb.dirs > 0 and p.split[k] > 0 and fits[k * n + jb.j].fires != std.math.maxInt(usize) and jb.least[k] != 0) { + drop = @max(drop, jb.least[k] - fits[k * n + jb.j].fact_least); + }; + } + std.log.info("slide pocket: candidate inputs kept off what the @TypeOf(p.*).neurons below them write (up to {d} directions a layer): at most {d:.1}% of an input's size removed, a fact's least product down by at most {d:.3}", .{ most, 100 * lost, drop }); +} + +/// Logs each key's first neuron's firing share by source: answers, short and long wordings, held-out answers. +pub fn logSources(p: anytype, d: usize, m: usize, kinds: []const Kind) void { + const n = p.slots(); + for (p.taken.items) |x| { + if (x.neuron + 1 != p.used.items[x.slot]) continue; + const k = @backingInt(x.key); + var on: [5]usize = @splat(0); + var all: [5]usize = @splat(0); + var quiet_most: f32 = -std.math.inf(f32); // the highest it reads on another prompt in a conversation + const u = p.neuron(@constCast(p.up.items), x.slot, x.neuron, d); + for (p.labels.items, 0..) |l, i| { + const kind = kinds[k * m + i]; + const ex = p.pickRead(l.ex).?.ex; + if (kind == .steady and ex.context > 0) quiet_most = @max(quiet_most, dotBf16(u, p.rows.items[(i * n + x.slot) * d ..][0..d])); + if (kind != .fact and kind != .held) continue; + const src: usize = if (ex.context > 0) 4 else if (l.ex < p.answered.len) 0 else if (l.ex < p.answered.len + p.prompts.len) (if (ex.ids.len > 60) 2 else 1) else 3; + all[src] += 1; + on[src] += @intFromBool(dotBf16(u, p.rows.items[(i * n + x.slot) * d ..][0..d]) >= 0.5); + } + std.log.info("slide pocket: layer {d} at the {s} fires on answers {d}/{d}, short wordings {d}/{d}, long ones {d}/{d}, held-out {d}/{d}, in a conversation {d}/{d} (other prompts there at most {d:.2})", .{ p.moe.items[x.slot], @tagName(x.key), on[0], all[0], on[1], all[1], on[2], all[2], on[3], all[3], on[4], all[4], quiet_most }); + } +} + +/// Slot j's next neuron taken for the open fact on `key`, its input weights `u` as fitted (`f`, on `kinds`). +pub fn take(p: anytype, j: usize, key: pk.Key, u: []const f32, f: Fit, kinds: []const Kind, d: usize) !void { + const n = p.slots(); + const k = p.used.items[j]; + p.used.items[j] += 1; + try p.taken.append(p.gpa, .{ .slot = j, .neuron = k, .key = key }); + @memcpy(p.neuron(p.up.items, j, k, d), u); + p.gateFrom(j, k); + @memset(p.neuron(p.down.items, j, k, d), 0); + std.log.info("slide pocket: layer {d}, neuron {d}, at the {s}: on for {d:.0}% of the fact's questions (least {d:.2}), held-out {d:.0}% (mean {d:.2}); other prompts at most {d:.2}, other rows {d:.2}, {d} above zero", .{ p.moe.items[j], k, @tagName(key), 100 * f.fact_on, f.fact_least, 100 * f.held_on, f.held_mean, f.steady_most, f.other_most, f.fires }); + const start = p.pos.items.len / d; + for (kinds, 0..) |kind, i| if (kind == .fact) try p.pos.appendSlice(p.gpa, p.rows.items[(i * n + j) * d ..][0..d]); + const subject: u32 = if (key == .subject and p.subjects.items.len > 0) p.subjects.items[0] else 0; + try p.learned.append(p.gpa, .{ .slot = j, .neuron = k, .key = key, .start = start, .count = p.pos.items.len / d - start, .subject = subject, .lesson = p.lesson }); +} diff --git a/zig/src/living/pocket_load.zig b/zig/src/living/pocket_load.zig deleted file mode 100644 index b76ec8d019..0000000000 --- a/zig/src/living/pocket_load.zig +++ /dev/null @@ -1,30 +0,0 @@ -//! The pocket's neurons as the shards hold them, read once, at the layers the family's layout learns at. -const std = @import("std"); -const neuron_math = @import("neuron.zig"); - -/// The pocket's neurons as the shards hold them, read once, at the layers the family's layout learns at. -pub fn load(p: anytype, host: anytype) !void { - const P = @TypeOf(p.*); - if (p.moe.items.len > 0) return; - const lay = host.layout(); - if (lay.layers > 64) return error.TooManyLayers; // a step's nudges mark their layers in a u64 - p.hidden = lay.hidden; - p.layers = lay.layers; - for (0..lay.layers) |l| if (lay.learn.isSet(l)) try p.moe.append(p.gpa, l); - const n = P.neurons * lay.hidden; - try p.up.appendNTimes(p.gpa, 0, p.moe.items.len * n); - try p.down.appendNTimes(p.gpa, 0, p.moe.items.len * n); - try p.used.appendNTimes(p.gpa, 0, p.moe.items.len); - if (P.swiglu) { - try p.gate.appendNTimes(p.gpa, 0, p.moe.items.len * n); - try p.scratch.appendNTimes(p.gpa, 0, n); - } - for (p.moe.items, 0..) |l, j| { - const up = p.up.items[j * n ..][0..n]; - const down = p.down.items[j * n ..][0..n]; - if (P.swiglu) { - p.used.items[j] = host.pocketReadSwiglu(l, p.gate.items[j * n ..][0..n], p.scratch.items, down); - neuron_math.fromUp(P.of.neuron, p.scratch.items, up); - } else p.used.items[j] = host.pocketRead(l, up, down); - } -} diff --git a/zig/src/living/pocket_quiet.zig b/zig/src/living/pocket_quiet.zig index a1e2d70364..eb9954c4dc 100644 --- a/zig/src/living/pocket_quiet.zig +++ b/zig/src/living/pocket_quiet.zig @@ -1,59 +1,170 @@ -//! Earlier facts' neurons that fire on the open fact's questions, fitted again to stay silent there. +//! A pocket lesson's earlier neurons: other answers its subject neurons fire on, and refits of those on its rows. const std = @import("std"); +const pk = @import("pocket.zig"); const pocket_fit = @import("pocket_fit.zig"); - +const decouple = @import("pocket_decouple.zig"); +const subspace = @import("subspace.zig"); +const clock = @import("pocket_clock.zig"); +const pocket_dump = @import("pocket_dump.zig"); +const joint = @import("pocket_joint.zig"); const Kind = pocket_fit.Kind; +const Fit = pocket_fit.Fit; const fit = pocket_fit.fit; +const fitLayer = pocket_fit.fitLayer; const dotBf16 = pocket_fit.dotBf16; const fit_steps = pocket_fit.fit_steps; -pub const kept_least: f32 = 0.5; // an earlier neuron refitted must still reach this on every one of its own fact's rows -pub const refit_above: f32 = 0.5; // an earlier neuron is refitted only where it fires above this on a new fact's rows +/// Other answers where the fact's subject neurons fire, each at its strongest row: these stay as they were. +pub fn findKeeps(p: anytype, d: usize) !void { + if (p.split[1] == 0 or !p.keeping) return; + const n = p.slots(); + var i: usize = 0; + while (i < p.labels.items.len) { + const which = p.labels.items[i].ex; + var most: f32 = 0; + var at: ?usize = null; + while (i < p.labels.items.len and p.labels.items[i].ex == which) : (i += 1) { + const l = p.labels.items[i]; + // the fact's own mentions are free but already its answers, not ones to keep + if (l.kind != .none or l.ex < p.answered.len + p.prompts.len + p.held.len) continue; + var sum: f32 = 0; + for (p.taken.items) |x| if (x.key == .subject) { + sum += @max(p.act(x.slot, x.neuron, p.rows.items[(i * n + x.slot) * d ..][0..d]), 0); + }; + if (sum > most) { + most = sum; + at = l.row; + } + } + const row = at orelse continue; + const ex = p.pickRead(which).?.ex; + if (ex.ids.len > ex.start + 1) try p.keeps.append(p.gpa, .{ .ex = ex, .row = row }); + } + std.log.info("slide pocket: {d} other answers name the fact's subject where its @TypeOf(p.*).neurons fire; they are to stay as they were", .{p.keeps.items.len}); +} /// Earlier neurons firing on this fact's rows refitted silent there, undo copies kept; same-subject ones stay. pub fn quiet(p: anytype, t: anytype, host: anytype) !void { - const P = @TypeOf(p.*); const d = p.hidden; - const n = p.moe.items.len; + const Job = struct { + e: pk.Learned, + most: f32, + u: []f32, // its input weights, refitted in this copy + xs: std.ArrayList([]const u16) = .empty, + kinds: std.ArrayList(Kind) = .empty, + fixed: usize = 0, + f: Fit = .{}, + failed: bool = false, + }; + var jobs: std.ArrayList(Job) = .empty; + defer { + for (jobs.items) |*j| { + p.gpa.free(j.u); + j.xs.deinit(p.gpa); + j.kinds.deinit(p.gpa); + } + jobs.deinit(p.gpa); + } for (p.learned.items[0..p.learned_before]) |e| { if (e.key == .subject and std.mem.indexOfScalar(u32, p.subjects.items, e.subject) != null) continue; const u = p.neuron(p.up.items, e.slot, e.neuron, d); var most: f32 = -std.math.inf(f32); + const n = p.slots(); for (p.labels.items, 0..) |l, i| if (l.kind == .fact or l.kind == .held) { most = @max(most, dotBf16(u, p.rows.items[(i * n + e.slot) * d ..][0..d])); }; - if (most <= refit_above) continue; // weak there: left exactly as it is, this fact's outputs fitted with it - try p.refits.append(p.gpa, .{ .slot = e.slot, .neuron = e.neuron }); - try p.refit_up.appendSlice(p.gpa, u); - if (P.swiglu) try p.refit_gate.appendSlice(p.gpa, p.neuron(p.gate.items, e.slot, e.neuron, d)); - var xs: std.ArrayList([]const u16) = .empty; - defer xs.deinit(p.gpa); - var kinds: std.ArrayList(Kind) = .empty; - defer kinds.deinit(p.gpa); - for (0..e.count) |r| { - try xs.append(p.gpa, p.pos.items[(e.start + r) * d ..][0..d]); - try kinds.append(p.gpa, .fact); + if (most <= pk.refit_above) continue; // weak there: left exactly as it is, this fact's outputs fitted with it + try jobs.append(p.gpa, .{ .e = e, .most = most, .u = try p.gpa.dupe(f32, u) }); + try refitRows(p, &jobs.items[jobs.items.len - 1]); + } + const scales: []const f32 = if (p.decoupled and jobs.items.len > 0) try p.scales.get(p, t) else &.{}; + const Run = struct { + fn one(pp: anytype, sc: []const f32, j: *Job, dd: usize) void { + const gpa = pp.gpa; + j.f = fit(gpa, j.xs.items, j.kinds.items, dd, j.u, true, fit_steps / 2, j.fixed, @TypeOf(p.*).fam.neuron.margin) catch { + j.failed = true; + return; + }; + if (sc.len == 0) return; + // refitted, still kept off what the neurons below it write, and judged as it is then + var basis: std.ArrayList(f32) = .empty; + defer basis.deinit(gpa); + const dirs = decouple.below(pp, gpa, sc, j.e.slot, &basis) catch { + j.failed = true; + return; + }; + if (dirs == 0) return; + decouple.project(j.u, basis.items, dirs, dd); + j.f = decouple.evaluate(j.xs.items, j.kinds.items, j.u, gpa) catch { + j.failed = true; + return; + }; } - for (p.labels.items, 0..) |l, i| { - try xs.append(p.gpa, p.rows.items[(i * n + e.slot) * d ..][0..d]); - try kinds.append(p.gpa, switch (l.kind) { - .fact, .held => .steady, // this fact's questions are another fact's to it - .none => .other, - else => l.kind, - }); + fn share(pp: anytype, sc: []const f32, js: []Job, cursor: *std.atomic.Value(usize), dd: usize) void { + while (true) { + const i = cursor.fetchAdd(1, .monotonic); + if (i >= js.len) return; + one(pp, sc, &js[i], dd); + } } - const f = try fit(p.gpa, xs.items, kinds.items, d, u, true, fit_steps / 2, e.count, P.of.neuron.margin); - if (f.fact_least < kept_least or @max(f.steady_most, f.other_most) > 0) { + }; + var cursor = std.atomic.Value(usize).init(0); + const workers = @min(jobs.items.len, @min(std.Thread.getCpuCount() catch 1, 32)); + var spawned: [32]?std.Thread = @splat(null); + for (spawned[0..workers]) |*th| th.* = std.Thread.spawn(.{}, Run.share, .{ p, scales, jobs.items, &cursor, d }) catch null; + Run.share(p, scales, jobs.items, &cursor, d); + for (spawned[0..workers]) |th| if (th) |x| x.join(); + for (jobs.items) |*j| { + if (j.failed) return error.OutOfMemory; + const e = j.e; + const u = p.neuron(p.up.items, e.slot, e.neuron, d); + const f = j.f; + if (f.fact_least < pk.kept_least or @max(f.steady_most, f.other_most) > 0) { // a refit that forgets its fact or spreads is undone; this fact's outputs are fitted with it firing - @memcpy(u, p.refit_up.items[p.refit_up.items.len - d ..]); - p.refits.shrinkRetainingCapacity(p.refits.items.len - 1); - p.refit_up.shrinkRetainingCapacity(p.refit_up.items.len - d); - if (P.swiglu) p.refit_gate.shrinkRetainingCapacity(p.refit_gate.items.len - d); - std.log.info("slide pocket: layer {d}, neuron {d}, an earlier fact's, fires on this fact's questions (up to {d:.2}); fitted again its own would read at least {d:.2} and other rows at most {d:.2}, so it stays as it was", .{ p.moe.items[e.slot], e.neuron, most, f.fact_least, @max(f.steady_most, f.other_most) }); + std.log.info("slide pocket: layer {d}, neuron {d}, an earlier fact's, fires on this fact's questions (up to {d:.2}); fitted again its own would read at least {d:.2} and other rows at most {d:.2}, so it stays as it was", .{ p.moe.items[e.slot], e.neuron, j.most, f.fact_least, @max(f.steady_most, f.other_most) }); continue; } + try p.refits.append(p.gpa, .{ .slot = e.slot, .neuron = e.neuron }); + try p.refit_up.appendSlice(p.gpa, u); + if (@TypeOf(p.*).swiglu) try p.refit_gate.appendSlice(p.gpa, p.neuron(p.gate.items, e.slot, e.neuron, d)); + @memcpy(u, j.u); p.gateFrom(e.slot, e.neuron); try p.upload(t, host, e.slot); - std.log.info("slide pocket: layer {d}, neuron {d}, an earlier fact's, fired on this fact's questions (up to {d:.2}); fitted again: there and elsewhere at most {d:.2}, its own questions' least {d:.2}", .{ p.moe.items[e.slot], e.neuron, most, @max(f.steady_most, f.other_most), f.fact_least }); + std.log.info("slide pocket: layer {d}, neuron {d}, an earlier fact's, fired on this fact's questions (up to {d:.2}); fitted again: there and elsewhere at most {d:.2}, its own questions' least {d:.2} ({d} rows held as they read, {d} of them read now)", .{ p.moe.items[e.slot], e.neuron, j.most, @max(f.steady_most, f.other_most), f.fact_least, j.fixed, j.fixed - e.count }); + } +} + +/// A refit's rows: its fact's stored rows, then the rows it fires on now held as they read, then the rest. +pub fn refitRows(p: anytype, j: anytype) !void { + const d = p.hidden; + const n = p.slots(); + const e = j.e; + const u = j.u; + const own = p.answered.len + p.prompts.len + p.held.len; // read examples below this are this fact's + for (0..e.count) |r| { + try j.xs.append(p.gpa, p.pos.items[(e.start + r) * d ..][0..d]); + try j.kinds.append(p.gpa, .fact); + } + // the rows of other prompts it fires on now are its own fact's as the model reads them today. + const live = try p.gpa.alloc(bool, p.labels.items.len); + defer p.gpa.free(live); + var fixed = e.count; + for (p.labels.items, live, 0..) |l, *on, i| { + const x = p.rows.items[(i * n + e.slot) * d ..][0..d]; + on.* = (l.ex >= own or l.row < p.pickRead(l.ex).?.ex.context) and dotBf16(u, x) > 0; + if (!on.*) continue; + try j.xs.append(p.gpa, x); + try j.kinds.append(p.gpa, .none); // fixed, so read as it was; a weak one is no stored row to judge by + fixed += 1; + } + for (p.labels.items, live, 0..) |l, on, i| { + if (on) continue; + try j.xs.append(p.gpa, p.rows.items[(i * n + e.slot) * d ..][0..d]); + try j.kinds.append(p.gpa, switch (l.kind) { + .fact, .held => .steady, // this fact's questions are another fact's to it + .none => .other, + else => l.kind, + }); } + j.fixed = fixed; } diff --git a/zig/src/living/pocket_read.zig b/zig/src/living/pocket_read.zig index 246652d6e3..95c8b351b8 100644 --- a/zig/src/living/pocket_read.zig +++ b/zig/src/living/pocket_read.zig @@ -4,6 +4,7 @@ const examples = @import("lesson_examples.zig"); const pocket = @import("pocket.zig"); const pack = @import("pocket_pack.zig"); const Kind = @import("pocket_fit.zig").Kind; +const clock = @import("pocket_clock.zig"); const Example = examples.Example; const Label = pocket.Label; @@ -11,15 +12,18 @@ const subjectRow = pocket.subjectRow; const valueRow = pocket.valueRow; const stride = 3; // every third row of another prompt is one the fact's neurons stay silent on +const sample = 8; // every eighth row of a conversation before a question, read with the first question asked after it /// What the last read phase read: each example's fingerprint, the pocket's weights' then, whether it read to its end. pub const Seen = struct { keys: std.ArrayList(u64) = .empty, state: u64 = 0, whole: bool = false, + talks: std.ArrayList(u64) = .empty, // the conversations whose own rows were read (each with its first question) pub fn deinit(s: *Seen, gpa: std.mem.Allocator) void { s.keys.deinit(gpa); + s.talks.deinit(gpa); } }; @@ -57,41 +61,175 @@ pub fn again(p: anytype) !usize { } } s.keys.clearRetainingCapacity(); + s.talks.clearRetainingCapacity(); s.state = now; s.whole = false; return 0; } -/// As many of the next examples as one pass holds, read side by side; the fit next once all are read. +/// As many of the next examples as one pass holds, read side by side. pub fn once(p: anytype, t: anytype) !bool { const per_pass = @typeInfo(@TypeOf(t.spans)).array.len; + const tapping = comptime @hasDecl(@TypeOf(t.*), "tapRows"); + const first = p.pickRead(p.at) orelse { + p.read.whole = true; + p.next(.fit); + return false; + }; + if (tapping and first.ex.context > 0) { + const t0 = clock.mono(); + defer clock.add(.read_tap, clock.mono() - t0); + if (comptime @hasDecl(@TypeOf(t.*), "tapMany")) { + if (!std.mem.eql(u8, std.mem.span(std.c.getenv("TF_SLIDE_TAPS") orelse "many"), "one")) { + p.at += try tapMany(p, t, @intCast(p.at)); + return false; + } + } + try tapOne(p, t, first.ex, first.kind, @intCast(p.at)); + try p.read.keys.append(p.gpa, key(first.ex, first.kind)); + p.at += 1; + return false; + } var seqs: [per_pass]pack.Seq = undefined; var kinds: [per_pass]Kind = undefined; var n: usize = 0; while (n < per_pass) : (n += 1) { const got = p.pickRead(p.at + n) orelse break; + if (tapping and got.ex.context > 0) break; seqs[n] = pack.seq(got.ex); kinds[n] = got.kind; } - if (n == 0) { - p.read.whole = true; - p.next(.fit); - return false; - } const m = pack.fits(t, seqs[0..n]); var out: [per_pass]pack.Result = undefined; + // the forward stops at the highest layer a neuron may sit at: no row above it is ever read + if (comptime @hasField(@TypeOf(t.*), "keys_top")) t.keys_top = p.readTop(); + defer { + if (comptime @hasField(@TypeOf(t.*), "keys_top")) t.keys_top = null; + } + const t0 = clock.mono(); try t.pass(seqs[0..m], .keys, pack.turn, out[0..m]); + const t1 = clock.mono(); + clock.add(.read_pass, t1 - t0); + defer clock.add(.read_copy, clock.mono() - t1); + var rows: std.ArrayList(Row) = .empty; + defer rows.deinit(p.gpa); for (0..m) |i| { const ex = p.pickRead(p.at + i).?.ex; - try label(p, t, ex, kinds[i], @intCast(p.at + i), t.spans[i].at); + rows.clearRetainingCapacity(); + try plan(p, ex, kinds[i], @intCast(p.at + i), 0, 0, &rows); + for (rows.items) |r| try keep(p, t, t.spans[i].at + r.row, r.l); try p.read.keys.append(p.gpa, key(ex, kinds[i])); } p.at += m; return false; } -/// Example `ex` (read `which`, of kind `kind`) labelled row by row, as the last pass read it from row `base`. -fn label(p: anytype, t: anytype, ex: Example, kind: Kind, which: u32, base: usize) !void { +/// A read row: its place in its example and what it is to the fact. +const Row = struct { row: u32, l: Label }; + +/// A prompt asked after a conversation (`ex.context` its rows), read through the trainer's taps. +fn tapOne(p: anytype, t: anytype, ex: Example, kind: Kind, which: u32) !void { + const talk = std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(ex.ids[0..ex.context])); + const fresh = std.mem.indexOfScalar(u64, p.read.talks.items, talk) == null; + if (fresh) try p.read.talks.append(p.gpa, talk); + var rows: std.ArrayList(Row) = .empty; + defer rows.deinit(p.gpa); + try plan(p, ex, kind, which, ex.context, if (fresh) sample else 0, &rows); + std.mem.sort(Row, rows.items, {}, struct { + fn less(_: void, a: Row, b: Row) bool { + return a.row < b.row; + } + }.less); + const want = try p.gpa.alloc(u32, rows.items.len); + defer p.gpa.free(want); + for (rows.items, want) |r, *w| w.* = r.row; + const d = p.hidden; + const slots = p.moe.items.len; + const got = try p.gpa.alloc(u16, rows.items.len * slots * d); + defer p.gpa.free(got); + // the rows a pass reads: all but the last token, which only a pass's target reads + try t.tapRows(ex.ids[0 .. ex.ids.len - 1], ex.context, want, p.moe.items, got); + if (std.c.getenv("TF_SLIDE_TAP_CHECK") != null) tapCheck(p, t, ex, want, got); + try p.rows.appendSlice(p.gpa, got); + for (rows.items) |r| try p.labels.append(p.gpa, r.l); +} + +/// The next examples asked after one conversation (as many as the trainer's tapMany takes), read as tapOne reads each. +fn tapMany(p: anytype, t: anytype, first: u32) !usize { + const Item = @typeInfo(@TypeOf(@TypeOf(t.*).tapMany)).@"fn".param_types[1].?; + const It = @typeInfo(Item).pointer.child; + const most = 8; + var exs: [most]Example = undefined; + var kinds: [most]Kind = undefined; + var n: usize = 0; + const talk0 = blk: { + const ex = p.pickRead(first).?.ex; + break :blk std.mem.sliceAsBytes(ex.ids[0..ex.context]); + }; + while (n < most) : (n += 1) { + const got = p.pickRead(first + n) orelse break; + if (got.ex.context == 0 or !std.mem.eql(u8, std.mem.sliceAsBytes(got.ex.ids[0..got.ex.context]), talk0)) break; + exs[n] = got.ex; + kinds[n] = got.kind; + } + const d = p.hidden; + const slots = p.moe.items.len; + var plans: [most]std.ArrayList(Row) = @splat(.empty); + defer for (&plans) |*x| x.deinit(p.gpa); + var wants: [most][]u32 = @splat(&.{}); + defer for (wants) |w| p.gpa.free(w); + var outs: [most][]u16 = @splat(&.{}); + defer for (outs) |o| p.gpa.free(o); + var items: [most]It = undefined; + for (0..n) |i| { + const ex = exs[i]; + const talk = std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(ex.ids[0..ex.context])); + const fresh = std.mem.indexOfScalar(u64, p.read.talks.items, talk) == null; + if (fresh) try p.read.talks.append(p.gpa, talk); + try plan(p, ex, kinds[i], first + @as(u32, @intCast(i)), ex.context, if (fresh) sample else 0, &plans[i]); + std.mem.sort(Row, plans[i].items, {}, struct { + fn less(_: void, a: Row, b: Row) bool { + return a.row < b.row; + } + }.less); + wants[i] = try p.gpa.alloc(u32, plans[i].items.len); + for (plans[i].items, wants[i]) |r, *w| w.* = r.row; + outs[i] = try p.gpa.alloc(u16, plans[i].items.len * slots * d); + items[i] = .{ .ids = ex.ids[0 .. ex.ids.len - 1], .context = ex.context, .rows = wants[i], .out = outs[i] }; + } + try t.tapMany(items[0..n], p.moe.items); + for (0..n) |i| { + try p.rows.appendSlice(p.gpa, outs[i]); + for (plans[i].items) |r| try p.labels.append(p.gpa, r.l); + try p.read.keys.append(p.gpa, key(exs[i], kinds[i])); + } + return n; +} + +/// A diagnostic (TF_SLIDE_TAP_CHECK): the tapped rows of a prompt short enough for a pass, against the pass's own. +fn tapCheck(p: anytype, t: anytype, ex: Example, rows: []const u32, got: []const u16) void { + const d = p.hidden; + const slots = p.moe.items.len; + var out: [1]pack.Result = undefined; + t.pass(&.{pack.seq(ex)}, .keys, pack.turn, &out) catch |e| return std.log.info("slide pocket: tap check: no pass of {d} rows ({t})", .{ ex.ids.len, e }); + var most: f32 = 0; + var differ: usize = 0; + for (rows, 0..) |r, i| for (p.moe.items, 0..) |layer, j| { + const a = t.normed(layer, t.spans[0].at + r); + const b = got[(i * slots + j) * d ..][0..d]; + for (a, b) |x, y| { + const fx: f32 = @bitCast(@as(u32, x) << 16); + const fy: f32 = @bitCast(@as(u32, y) << 16); + most = @max(most, @abs(fx - fy)); + differ += @intFromBool(x != y); + } + }; + std.log.info("slide pocket: tap check: {d} rows of a {d}-token prompt: {d} values differ from the pass's, most by {d:.4}", .{ rows.len, ex.ids.len, differ, most }); +} + +/// Example `ex` (read `which`, of kind `kind`) planned row by row from row `from` on. +fn plan(p: anytype, ex: Example, kind: Kind, which: u32, from: usize, every: usize, out: *std.ArrayList(Row)) !void { + const a = p.gpa; const own = kind != .steady; // the fact's own subjects and the tokens before them: another prompt naming the same is where its neurons may fire const subject = if (own and p.split[1] > 0) subjectRow(ex) else null; @@ -101,18 +239,19 @@ fn label(p: anytype, t: anytype, ex: Example, kind: Kind, which: u32, base: usiz } // its value row: the fact's own where the value comes, another answer's (an earlier fact's) one to stay silent on const value = if (p.split[2] > 0) valueRow(ex) else null; - try keep(p, t, base + ex.decide, .{ .kind = kind, .key = .reply, .ex = which, .row = @intCast(ex.decide) }); - if (subject) |r| try keep(p, t, base + r, .{ .kind = kind, .key = .subject, .ex = which, .row = @intCast(r) }); - if (value) |r| try keep(p, t, base + r, if (own) .{ .kind = kind, .key = .value, .ex = which, .row = @intCast(r) } else .{ .kind = .other, .key = null, .ex = which, .row = @intCast(r) }); - // rows to stay silent on: every row of the fact's own examples, every third of others', each naming the subject - var r: usize = 0; + try out.append(a, .{ .row = ex.decide, .l = .{ .kind = kind, .key = .reply, .ex = which, .row = ex.decide } }); + if (subject) |r| try out.append(a, .{ .row = @intCast(r), .l = .{ .kind = kind, .key = .subject, .ex = which, .row = @intCast(r) } }); + if (value) |r| try out.append(a, .{ .row = @intCast(r), .l = if (own) .{ .kind = kind, .key = .value, .ex = which, .row = @intCast(r) } else .{ .kind = .other, .key = null, .ex = which, .row = @intCast(r) } }); + // rows to stay silent on: every row of the fact's own examples, every third of others', each naming the subject. + var r: usize = if (every > 0) 0 else from; while (r < ex.ids.len - 1) : (r += 1) { if (r == ex.decide or (subject != null and r == subject.?) or (value != null and r == value.?)) continue; const named = p.split[1] > 0 and std.mem.indexOfScalar(u32, p.subjects.items, ex.ids[r]) != null; + const before = r < from; // a conversation's row, read only every `every`-th if (named and (own or !p.strict or (!p.silencing and r > 0 and std.mem.indexOfScalar(u32, p.leads.items, ex.ids[r - 1]) != null))) { // the fact's own subject (in its examples, or after the token its questions put first): left free - try keep(p, t, base + r, .{ .kind = .none, .key = .subject, .ex = which, .row = @intCast(r) }); - } else if (own or named or r % stride == 0) try keep(p, t, base + r, .{ .kind = .other, .key = null, .ex = which, .row = @intCast(r) }); + try out.append(a, .{ .row = @intCast(r), .l = .{ .kind = .none, .key = .subject, .ex = which, .row = @intCast(r) } }); + } else if (if (before) named or r % every == 0 else own or named or r % stride == 0) try out.append(a, .{ .row = @intCast(r), .l = .{ .kind = .other, .key = null, .ex = which, .row = @intCast(r) } }); } } diff --git a/zig/src/living/pocket_retire.zig b/zig/src/living/pocket_retire.zig new file mode 100644 index 0000000000..a79fda2645 --- /dev/null +++ b/zig/src/living/pocket_retire.zig @@ -0,0 +1,55 @@ +//! A replaced fact's neurons zeroed where they sit, and put back if the newer fact is not learned. +const std = @import("std"); +const pk = @import("pocket.zig"); +const pocket_fit = @import("pocket_fit.zig"); +const decouple = @import("pocket_decouple.zig"); +const subspace = @import("subspace.zig"); +const clock = @import("pocket_clock.zig"); +const pocket_dump = @import("pocket_dump.zig"); +const joint = @import("pocket_joint.zig"); +const Kind = pocket_fit.Kind; +const Fit = pocket_fit.Fit; +const fit = pocket_fit.fit; +const fitLayer = pocket_fit.fitLayer; +const dotBf16 = pocket_fit.dotBf16; +const fit_steps = pocket_fit.fit_steps; + +/// A replaced fact's neurons, (layer, neuron) each, zeroed where they sit; their places stay taken. +pub fn retire(p: anytype, t: anytype, host: anytype, gone: []const [2]u16) !void { + try p.load(t, host); + const d = p.hidden; + p.retired.clearRetainingCapacity(); + p.retired_w.clearRetainingCapacity(); + p.retired_marks = p.retired_lessons.items.len; + for (gone) |g| { + const slot = std.mem.indexOfScalar(usize, p.moe.items, g[0]) orelse continue; + if (g[1] >= p.used.items[slot]) continue; + for (p.learned.items) |e| if (e.slot == slot and e.neuron == g[1] and std.mem.indexOfScalar(u32, p.retired_lessons.items, e.lesson) == null) try p.retired_lessons.append(p.gpa, e.lesson); + try p.retired.append(p.gpa, .{ slot, g[1] }); + try p.retired_w.appendSlice(p.gpa, p.neuron(p.up.items, slot, g[1], d)); + try p.retired_w.appendSlice(p.gpa, p.neuron(p.down.items, slot, g[1], d)); + if (@TypeOf(p.*).swiglu) try p.retired_w.appendSlice(p.gpa, p.neuron(p.gate.items, slot, g[1], d)); + @memset(p.neuron(p.up.items, slot, g[1], d), 0); + @memset(p.neuron(p.down.items, slot, g[1], d), 0); + if (@TypeOf(p.*).swiglu) @memset(p.neuron(p.gate.items, slot, g[1], d), 0); + try p.upload(t, host, slot); + } + std.log.info("slide pocket: {d} @TypeOf(p.*).neurons of replaced facts zeroed", .{gone.len}); +} + +/// The last retire undone: its neurons as they were (the fact that replaced theirs was not learned). +pub fn unretire(p: anytype, t: anytype, host: anytype) !void { + try p.load(t, host); + const d = p.hidden; + for (p.retired.items, 0..) |r, i| { + const w = p.retired_w.items[@TypeOf(p.*).retired_rows * i * d ..][0 .. @TypeOf(p.*).retired_rows * d]; + @memcpy(p.neuron(p.up.items, r[0], r[1], d), w[0..d]); + @memcpy(p.neuron(p.down.items, r[0], r[1], d), w[d..][0..d]); + if (@TypeOf(p.*).swiglu) @memcpy(p.neuron(p.gate.items, r[0], r[1], d), w[2 * d ..][0..d]); + try p.upload(t, host, r[0]); + } + std.log.info("slide pocket: {d} @TypeOf(p.*).neurons of replaced facts put back", .{p.retired.items.len}); + p.retired_lessons.shrinkRetainingCapacity(p.retired_marks); + p.retired.clearRetainingCapacity(); + p.retired_w.clearRetainingCapacity(); +} diff --git a/zig/src/living/pocket_test.zig b/zig/src/living/pocket_test.zig new file mode 100644 index 0000000000..bb5421cc36 --- /dev/null +++ b/zig/src/living/pocket_test.zig @@ -0,0 +1,232 @@ +//! The tests of pocket.zig, beside it so the file stays under 600 lines. +const pocket_mod = @import("pocket.zig"); +const std = @import("std"); +const examples = @import("lesson_examples.zig"); +const pocket_fit = @import("pocket_fit.zig"); +const Example = examples.Example; +const Kind = pocket_fit.Kind; +const fit = pocket_fit.fit; +const dotBf16 = pocket_fit.dotBf16; +const fit_steps = pocket_fit.fit_steps; +const Pocket = pocket_mod.Pocket; +const kept_least = pocket_mod.kept_least; +const kindFor = pocket_mod.kindFor; +const refit_above = pocket_mod.refit_above; + +test "a fact keys as many neurons on its subject as the share of its questions that name it, at least half, else none" { + const P = Pocket(struct {}, @import("families.zig").nemotron_h); + var p: P = .{ .gpa = std.testing.allocator, .mode = .auto }; + defer p.deinit(); + // ids: a question's tokens, the subject's last token at row 2, the answer from row 4 + const ids = [_]u32{ 1, 2, 7, 3, 4, 5 }; + const named: Example = .{ .ids = &ids, .start = 4, .decide = 3, .subject = 2 }; + const plain: Example = .{ .ids = &ids, .start = 4, .decide = 3 }; + try std.testing.expectEqual([3]usize{ 5, 5, 0 }, p.pickSplit(&.{ &.{ named, plain }, &.{} }, &.{})); + try std.testing.expectEqual([3]usize{ 0, 10, 0 }, p.pickSplit(&.{ &.{ named, named }, &.{named} }, &.{})); + try std.testing.expectEqual([3]usize{ 3, 7, 0 }, p.pickSplit(&.{&.{ named, named, plain }}, &.{})); + try std.testing.expectEqual([3]usize{ 10, 0, 0 }, p.pickSplit(&.{&.{ named, plain, plain }}, &.{})); + try std.testing.expectEqual([3]usize{ 10, 0, 0 }, p.pickSplit(&.{&.{}}, &.{})); + // answers whose value comes after row 4: none there unless asked, then four, the rest shared as before + const valued: Example = .{ .ids = &ids, .start = 4, .decide = 3, .subject = 2, .value = 4 }; + try std.testing.expectEqual([3]usize{ 0, 10, 0 }, p.pickSplit(&.{&.{ valued, valued }}, &.{ valued, valued })); + p.valuing = true; + try std.testing.expectEqual([3]usize{ 0, 6, 4 }, p.pickSplit(&.{&.{ valued, valued }}, &.{ valued, valued })); + p.mode = .subject; + try std.testing.expectEqual([3]usize{ 0, 10, 0 }, p.pickSplit(&.{&.{ named, plain, plain }}, &.{})); + p.mode = .reply; + try std.testing.expectEqual([3]usize{ 10, 0, 0 }, p.pickSplit(&.{&.{ named, named }}, &.{})); +} + +test "a read row is a fact's row only to its own key's neurons; another prompt's mention of the subject is left free" { + try std.testing.expectEqual(Kind.fact, kindFor(.{ .kind = .fact, .key = .subject, .ex = 0, .row = 2 }, .subject)); + try std.testing.expectEqual(Kind.other, kindFor(.{ .kind = .fact, .key = .subject, .ex = 0, .row = 2 }, .reply)); + try std.testing.expectEqual(Kind.held, kindFor(.{ .kind = .held, .key = .reply, .ex = 3, .row = 7 }, .reply)); + try std.testing.expectEqual(Kind.steady, kindFor(.{ .kind = .steady, .key = .reply, .ex = 1, .row = 9 }, .subject)); + try std.testing.expectEqual(Kind.none, kindFor(.{ .kind = .none, .key = .subject, .ex = 1, .row = 4 }, .subject)); + try std.testing.expectEqual(Kind.other, kindFor(.{ .kind = .none, .key = .subject, .ex = 1, .row = 4 }, .reply)); + try std.testing.expectEqual(Kind.other, kindFor(.{ .kind = .other, .key = null, .ex = 1, .row = 5 }, .subject)); +} + +test "an earlier fact's neuron fitted quiet on a new fact's rows reads as before on its own fact's rows as read now" { + const gpa = std.testing.allocator; + const F = @import("families.zig").nemotron_h; + const T = struct {}; + const P = Pocket(T, F); + const d = 64; + const NoHost = struct { + pub fn pocket(_: @This(), _: usize, _: []const f32, _: []const f32, _: usize) !void {} + }; + var prng = std.Random.DefaultPrng.init(11); + const r = prng.random(); + // hidden states: a shared offset, noise, and a direction each fact's questions lean along. + var common: [d]f32 = undefined; + var old_dir: [d]f32 = undefined; + var new_dir: [d]f32 = undefined; + var push: [d]f32 = undefined; // what the pocket's lower neurons add to the earlier fact's rows since it was read + for (&common, &old_dir, &push) |*c, *o, *u| { + c.* = 1 + r.floatNorm(f32) * 0.1; + o.* = r.floatNorm(f32); + u.* = r.floatNorm(f32) * 1.2; + } + for (&new_dir, old_dir) |*n, o| n.* = 0.8 * o + 0.6 * r.floatNorm(f32); + const n_old = 12; + const n_new = 12; + const n_rest = 160; + const Row = [d]u16; + const rowOf = struct { + fn f(rr: std.Random, cm: []const f32, lean: ?[]const f32, extra: ?[]const f32) Row { + var out: Row = undefined; + for (&out, 0..) |*x, k| { + var v = cm[k] + rr.floatNorm(f32) * 0.5; + if (lean) |dir| v += 1.5 * dir[k]; + if (extra) |e| v += e[k]; + x.* = @truncate(@as(u32, @bitCast(v)) >> 16); + } + return out; + } + }.f; + var stored: [n_old]Row = undefined; // the earlier fact's rows as its lesson read them + var live: [n_old]Row = undefined; // the same questions as read now, in the replay + for (&stored, &live) |*s, *l| { + s.* = rowOf(r, &common, &old_dir, null); + l.* = rowOf(r, &common, &old_dir, &push); + } + var p: P = .{ .gpa = gpa, .mode = .reply }; + defer p.deinit(); + p.hidden = d; + p.layers = 8; + try p.moe.append(gpa, 3); + try p.up.appendNTimes(gpa, 0, P.neurons * d); + try p.down.appendNTimes(gpa, 0, P.neurons * d); + try p.used.append(gpa, 1); + // the earlier fact's neuron, fitted on its stored rows against the rest + var xs: std.ArrayList([]const u16) = .empty; + defer xs.deinit(gpa); + var kinds: std.ArrayList(Kind) = .empty; + defer kinds.deinit(gpa); + var rest: [n_rest]Row = undefined; + for (&rest) |*x| x.* = rowOf(r, &common, null, null); + for (&stored) |*x| { + try xs.append(gpa, x); + try kinds.append(gpa, .fact); + try p.pos.appendSlice(gpa, x); + } + for (&rest) |*x| { + try xs.append(gpa, x); + try kinds.append(gpa, .other); + } + const u = p.neuron(p.up.items, 0, 0, d); + _ = try fit(gpa, xs.items, kinds.items, d, u, false, fit_steps, 0, F.neuron.margin); + try p.learned.append(gpa, .{ .slot = 0, .neuron = 0, .key = .reply, .start = 0, .count = n_old, .subject = 0, .lesson = 0 }); + p.learned_before = 1; + // the new fact's read: its questions (its own examples), then other prompts: the earlier fact's in the replay first + var news: [n_new]Row = undefined; + for (&news) |*x| x.* = rowOf(r, &common, &new_dir, null); + const ex: Example = .{ .ids = &.{ 1, 2, 3 }, .start = 2, .decide = 1 }; + const answered: [n_new]Example = @splat(ex); + p.answered = &answered; + for (&news, 0..) |*x, i| { + try p.rows.appendSlice(gpa, x); + try p.labels.append(gpa, .{ .kind = .fact, .key = .reply, .ex = @intCast(i), .row = 1 }); + } + for (&live, 0..) |*x, i| { + try p.rows.appendSlice(gpa, x); + try p.labels.append(gpa, .{ .kind = .steady, .key = .reply, .ex = @intCast(n_new + i), .row = 1 }); + } + for (rest[0 .. n_rest / 2], 0..) |*x, i| { + try p.rows.appendSlice(gpa, x); + try p.labels.append(gpa, .{ .kind = .steady, .key = .reply, .ex = @intCast(n_new + n_old + i), .row = 1 }); + } + var most: f32 = -1; + for (&news) |*x| most = @max(most, dotBf16(u, x)); + try std.testing.expect(most > refit_above); // it fires on the new fact's questions: a refit is due + const before = try gpa.dupe(f32, u); + defer gpa.free(before); + var t: T = .{}; + try p.quiet(&t, NoHost{}); + try std.testing.expectEqual(@as(usize, 1), p.refits.items.len); + for (&news) |*x| try std.testing.expect(dotBf16(u, x) <= 0); + // its own questions as read now and as stored read exactly as they did: it still answers its own fact + for (&live) |*x| try std.testing.expectApproxEqAbs(dotBf16(before, x), dotBf16(u, x), 1e-3); + for (&stored) |*x| try std.testing.expectApproxEqAbs(dotBf16(before, x), dotBf16(u, x), 1e-3); + // as rows of other prompts (the old refit), its own questions read now were pushed silent with the stored ones. + xs.clearRetainingCapacity(); + kinds.clearRetainingCapacity(); + for (&stored) |*x| { + try xs.append(gpa, x); + try kinds.append(gpa, .fact); + } + for (&news) |*x| { + try xs.append(gpa, x); + try kinds.append(gpa, .steady); + } + for (&live) |*x| { + try xs.append(gpa, x); + try kinds.append(gpa, .steady); + } + const old = try gpa.dupe(f32, before); + defer gpa.free(old); + const of = try fit(gpa, xs.items, kinds.items, d, old, true, fit_steps / 2, n_old, F.neuron.margin); + // (its stored rows, the only ones it checked, still read as before, so nothing told it it had forgotten) + try std.testing.expect(of.fact_least >= kept_least); + var silenced: usize = 0; + for (&live) |*x| silenced += @intFromBool(dotBf16(old, x) < 0.5 and dotBf16(before, x) >= 0.5); + try std.testing.expect(silenced > n_old / 2); +} + +test "a lesson taken out puts the pocket back bit for bit: its neurons, an earlier one it refitted, the rounding" { + const gpa = std.testing.allocator; + const F = @import("families.zig").nemotron_h; + const T = struct {}; + const P = Pocket(T, F); + const d = 64; + const NoHost = struct { + pub fn pocket(_: @This(), _: usize, _: []const f32, _: []const f32, _: usize) !void {} + }; + var prng = std.Random.DefaultPrng.init(3); + const r = prng.random(); + var p: P = .{ .gpa = gpa, .mode = .reply }; + defer p.deinit(); + p.hidden = d; + p.layers = 8; + try p.moe.appendSlice(gpa, &.{ 3, 5 }); + try p.up.appendNTimes(gpa, 0, 2 * P.neurons * d); + try p.down.appendNTimes(gpa, 0, 2 * P.neurons * d); + try p.used.appendSlice(gpa, &.{ 1, 0 }); + // an earlier fact's neuron at the first layer + for (p.neuron(p.up.items, 0, 0, d), p.neuron(p.down.items, 0, 0, d)) |*u, *v| { + u.* = r.floatNorm(f32); + v.* = r.floatNorm(f32) * 0.01; + } + try p.learned.append(gpa, .{ .slot = 0, .neuron = 0, .key = .reply, .start = 0, .count = 0, .subject = 0, .lesson = 0 }); + var t: T = .{}; + try p.mark(); + const before = p.hash(); + // the lesson: a neuron of its own beside the earlier one (sharing its output's groups), the earlier one refitted. + p.used.items[0] = 2; + p.used.items[1] = 1; + for ([_][2]usize{ .{ 0, 1 }, .{ 1, 0 } }) |at| { + for (p.neuron(p.up.items, at[0], at[1], d), p.neuron(p.down.items, at[0], at[1], d)) |*u, *v| { + u.* = r.floatNorm(f32); + v.* = r.floatNorm(f32); + } + try p.taken.append(gpa, .{ .slot = at[0], .neuron = at[1], .key = .reply }); + } + try p.refits.append(gpa, .{ .slot = 0, .neuron = 0 }); + try p.refit_up.appendSlice(gpa, p.neuron(p.up.items, 0, 0, d)); + p.neuron(p.up.items, 0, 0, d)[0] += 1; + try p.learned.append(gpa, .{ .slot = 0, .neuron = 1, .key = .reply, .start = 0, .count = 0, .subject = 0, .lesson = 1 }); + try p.asWritten(&t, NoHost{}); + try std.testing.expect(p.hash() != before); + try p.undo(&t, NoHost{}); + try std.testing.expectEqual(before, p.hash()); + try std.testing.expectEqualSlices(usize, &.{ 1, 0 }, p.used.items); + try std.testing.expectEqual(@as(usize, 1), p.learned.items.len); + // a save since the mark: no lesson before it is put back, the old undo runs (its own neurons out, nothing else) + p.snap.valid = false; + p.used.items[1] = 1; + try p.taken.append(gpa, .{ .slot = 1, .neuron = 0, .key = .reply }); + @memset(p.neuron(p.up.items, 1, 0, d), 1); + try p.undo(&t, NoHost{}); + try std.testing.expectEqual(before, p.hash()); +} diff --git a/zig/src/living/pocket_values.zig b/zig/src/living/pocket_values.zig index 46b1a96acb..ff0aebd93c 100644 --- a/zig/src/living/pocket_values.zig +++ b/zig/src/living/pocket_values.zig @@ -7,6 +7,7 @@ const pocket_fit = @import("pocket_fit.zig"); const pack = @import("pocket_pack.zig"); const train_mode = @import("train_mode.zig"); const prefix = @import("pocket_prefix.zig"); +const clock = @import("pocket_clock.zig"); const Example = examples.Example; const Acting = lesson_route.Acting; @@ -137,7 +138,16 @@ pub fn valueOnce(p: anytype, t: anytype, host: anytype) !bool { const grad = s.adam.items[3 * k * d ..][0 .. k * d]; if (s.judging) return judgeOnce(p, t, host, vals); if (p.answered.len == 0) return error.NoKeyedAnswers; - if (s.round == 0) prefix.round(p, &s.prefixes); + if (s.round == 0) { + prefix.round(p, &s.prefixes); + // what the neurons above each layer read, as this round's outputs are kept off it (pocket_decouple.zig) + if (p.decoupled) { + try p.above.build(p, try p.scales.get(p, t)); + keepOff(p, vals, d); + } + // nor is an output fitted through what it makes the pocket's other neurons do. + if (comptime @hasField(@TypeOf(t.*), "pocket_back")) t.pocket_back = !p.decoupled; + } // usize: @min with a comptime operand narrows its type (to u4 for 8), and their sum would overflow it const take: usize = @min(batch, p.answered.len); const joins: usize = @min(joint_batch, p.joint_answers.items.len); @@ -216,7 +226,9 @@ pub fn valueOnce(p: anytype, t: anytype, host: anytype) !bool { var bits = mask; while (bits != 0) : (bits &= bits - 1) @memset(t.deltaAt(i, key, @ctz(bits)), 0); }; + const t0 = clock.mono(); try t.pass(seqs[at..][0..m], .target, pack.turn, got[0..m]); + clock.add(.values_pass, clock.mono() - t0); for (drawn[at..][0..m], seqs[at..][0..m], got[0..m], 0..) |dr, q, r, i| { absorb(p, t, dr, i, r, grad); prefix.learn(p, t, &s.prefixes, q, t.spans[i], dr.which); @@ -236,6 +248,7 @@ pub fn valueOnce(p: anytype, t: anytype, host: anytype) !bool { p.at = 0; s.round += 1; if (s.round <= value_steps) adam(s, vals, grad, k, d, take + joins + keeps); + if (p.decoupled) keepOff(p, vals, d); @memset(grad, 0); if (s.round % judge_every == 0 or s.round > value_steps) { if (p.held.len == 0) { @@ -284,13 +297,21 @@ fn absorb(p: anytype, t: anytype, dr: Drawn, i: usize, got: Result, grad: []f32) // the earlier neurons on its subject, in the forward unscaled, pushed by every answer whose subject row they read if (masks[1] != 0) for (p.joint.items, p.taken.items.len..) |x, j| { const l = p.moe.items[x.slot]; - const z = dotBf16(p.neuron(p.up.items, x.slot, x.neuron, d), t.normed(l, sp.row(rows[1]))); - if (z <= 0) continue; - subspace.axpy(grad[j * d ..][0..d], z * z, t.pushAt(i, 1, l)); + const row = sp.row(rows[1]); + var a = p.act(x.slot, x.neuron, t.normed(l, row)); + if (@TypeOf(p.*).gated) a *= t.gateAt(l, row); + if (a == 0) continue; + subspace.axpy(grad[j * d ..][0..d], a, t.pushAt(i, 1, l)); if (s.size.items[j] == 0) s.size.items[j] = normBf16(t.residual(l + 1, sp.row(rows[1]))); }; } +/// Each output being fitted (the open fact's, then the earlier ones fitted with them) kept off what the neurons above. +fn keepOff(p: anytype, vals: []f32, d: usize) void { + for (p.taken.items, 0..) |x, j| p.above.keepOff(vals[j * d ..][0..d], x.slot, d); + for (p.joint.items, p.taken.items.len..) |x, j| p.above.keepOff(vals[j * d ..][0..d], x.slot, d); +} + /// The fitted outputs into the pocket and the forward: the open fact's neurons, then the earlier ones fitted with them. fn put(p: anytype, t: anytype, host: anytype, vals: []const f32, d: usize) !void { for (p.taken.items, 0..) |x, j| @memcpy(p.neuron(p.down.items, x.slot, x.neuron, d), vals[j * d ..][0..d]); @@ -335,7 +356,9 @@ fn judgeOnce(p: anytype, t: anytype, host: anytype, vals: []f32) !bool { const s = &p.v; const got = try p.gpa.alloc(Result, p.held.len); defer p.gpa.free(got); + const t0 = clock.mono(); try pack.read(p.gpa, t, p.held, .loss, got); + clock.add(.judge_pass, clock.mono() - t0); s.held_loss = 0; for (got) |r| s.held_loss += r.loss; const loss = s.held_loss / @as(f32, @floatFromInt(p.held.len)); @@ -382,6 +405,8 @@ fn finish(p: anytype, t: anytype, host: anytype, vals: []const f32) !bool { /// The held-out answers judged token for token with the pocket in the forward, side by side; true once judged. pub fn checkOnce(p: anytype, t: anytype, host: anytype) !bool { + // judged, and asked after, as a save writes it + try p.asWritten(t, host); if (p.held.len > 0) try verifyForward(p, t, host, p.held[0]); const got = try p.gpa.alloc(Result, p.held.len); defer p.gpa.free(got); diff --git a/zig/src/living/probe.zig b/zig/src/living/probe.zig index 1d2089f2ec..1175275c7a 100644 --- a/zig/src/living/probe.zig +++ b/zig/src/living/probe.zig @@ -1,4 +1,4 @@ -//! A measure, not a lesson: how far vectors fitted at a few layers bring a fact back (Nemotron's Metal trainer only). +//! A measure, not a lesson: how far vectors fitted at one row of a few layers bring a fact's held-out answers back. const std = @import("std"); const examples = @import("lesson_examples.zig"); const lesson_route = @import("lesson_route.zig"); diff --git a/zig/src/living/shards.zig b/zig/src/living/shards.zig index f0899b8de6..a3da435921 100644 --- a/zig/src/living/shards.zig +++ b/zig/src/living/shards.zig @@ -1,4 +1,4 @@ -//! The pocket in the shards, for any family: every shared expert widened once (config.json told), then in place. +//! The pocket in the shards, for any family: every shared expert widened once (config.json told). const std = @import("std"); const family = @import("family.zig"); const affine = @import("affine.zig"); @@ -10,7 +10,7 @@ pub fn Io(comptime core: type) type { const st = core.safetensors; const se = core.shard_edit; return struct { - /// The learned neurons of `layers` into `dir`'s shards, quantized as `F` stores them, handed back; the bytes. + /// The learned neurons of layers `layers` into `dir`'s shards (widened first if new). pub fn write(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, comptime F: Family, lay: Layout, layers: []const usize, neurons: usize, inputs: []const []f32, down: []f32) !usize { const q = F.quant; const d = lay.hidden; @@ -122,7 +122,7 @@ pub fn Io(comptime core: type) type { } }; - /// One shared expert with `neurons` learned after its `own`: a row a neuron per input, a column out; the bytes. + /// One shared expert with `neurons` learned after its `own`, into `edits`. fn expert(comptime F: Family, arena: std.mem.Allocator, files: *Files, edits: *std.ArrayList(se.Replacement), base: []const u8, own: usize, neurons: usize, d: usize, inputs: []const []f32, v: []f32) !usize { const q = F.quant; const g = q.group; @@ -196,6 +196,71 @@ pub fn Io(comptime core: type) type { }; } +/// One layer's pocket rounded in place as `write` hands it back. +pub fn roundAsWritten(comptime F: Family, gpa: std.mem.Allocator, neurons: usize, d: usize, inputs: []const []f32, down: []f32) !void { + const q = F.quant; + const per_word = 32 / q.bits; + const width = @max(d, neurons); + const w = try gpa.alloc(u32, width / per_word); + defer gpa.free(w); + const sc = try gpa.alloc(u16, width / q.group); + defer gpa.free(sc); + const bi = try gpa.alloc(u16, width / q.group); + defer gpa.free(bi); + for (inputs) |x| for (0..neurons) |k| { + const row = x[k * d ..][0..d]; + affine.quantize(q, row, w[0 .. d / per_word], sc[0 .. d / q.group], bi[0 .. d / q.group]); + affine.dequantize(q, w[0 .. d / per_word], sc[0 .. d / q.group], bi[0 .. d / q.group], row); + }; + const col = try gpa.alloc(f32, neurons); + defer gpa.free(col); + for (0..d) |o| { + for (col, 0..) |*x, k| x.* = down[k * d + o]; + affine.quantize(q, col, w[0 .. neurons / per_word], sc[0 .. neurons / q.group], bi[0 .. neurons / q.group]); + affine.dequantize(q, w[0 .. neurons / per_word], sc[0 .. neurons / q.group], bi[0 .. neurons / q.group], col); + for (col, 0..) |x, k| down[k * d + o] = x; + } +} + +test "a layer rounded as written is a fixed point, and its output groups span neighbouring neurons" { + const gpa = std.testing.allocator; + const F = @import("families.zig").qwen4_exp; + const n = F.neurons; + const d = 64; + var prng = std.Random.DefaultPrng.init(5); + const r = prng.random(); + const gate = try gpa.alloc(f32, n * d); + defer gpa.free(gate); + const up = try gpa.alloc(f32, n * d); + defer gpa.free(up); + const down = try gpa.alloc(f32, n * d); + defer gpa.free(down); + for (gate, up) |*g, *u| { + g.* = r.floatNorm(f32); + u.* = r.floatNorm(f32) * 0.1; + } + @memset(down, 0); + // two neurons in one output group, one with outputs a hundred times the other's + for (0..d) |o| { + down[0 * d + o] = r.floatNorm(f32) * 0.01; + down[1 * d + o] = r.floatNorm(f32); + } + const small = try gpa.dupe(f32, down[0..d]); + defer gpa.free(small); + try roundAsWritten(F, gpa, n, d, &.{ gate, up }, down); + // the small neuron's outputs land on the big one's grid: most of them lost + var lost: usize = 0; + for (small, down[0..d]) |a, b| lost += @intFromBool(@abs(a - b) > 0.5 * @abs(a)); + try std.testing.expect(lost > d / 4); + const again = try gpa.dupe(f32, down); + defer gpa.free(again); + const g2 = try gpa.dupe(f32, gate); + defer gpa.free(g2); + try roundAsWritten(F, gpa, n, d, &.{ g2, up }, again); + for (down, again) |a, b| try std.testing.expectApproxEqAbs(a, b, 1e-6); + for (gate, g2) |a, b| try std.testing.expectApproxEqAbs(a, b, 1e-6); +} + fn zeros(arena: std.mem.Allocator, n: usize) ![]f32 { const z = try arena.alloc(f32, n); @memset(z, 0); diff --git a/zig/src/living/swiglu_test.zig b/zig/src/living/swiglu_test.zig index 994a52f8c3..b43157620c 100644 --- a/zig/src/living/swiglu_test.zig +++ b/zig/src/living/swiglu_test.zig @@ -1,11 +1,11 @@ -//! A SwiGLU pocket neuron on the host: fitted, written in 4-bit groups of 32 and read back, it fires as relu^2 would. +//! A SwiGLU pocket neuron end to end on the host: fitted with Flash Next's margin. const std = @import("std"); const pocket_fit = @import("pocket_fit.zig"); const neuron = @import("neuron.zig"); const affine = @import("affine.zig"); const families = @import("families.zig"); -const f = @import("test_families.zig").swiglu; +const f = families.qwen4_exp; const d = 128; fn bf(x: f32) u16 { diff --git a/zig/src/living/test_families.zig b/zig/src/living/test_families.zig deleted file mode 100644 index 89a9255cf1..0000000000 --- a/zig/src/living/test_families.zig +++ /dev/null @@ -1,18 +0,0 @@ -//! A family for tests: a SwiGLU shared expert shaped as Qwen3.8 Flash Next's, which no checkpoint learns into yet. -const Family = @import("family.zig").Family; - -/// A SwiGLU shared expert at every layer, gated by its own router logit, in 4-bit groups of 32, keys under text_config. -pub const swiglu: Family = .{ - .model_type = "swiglu_test", - .names = .{ - .layers = "language_model.model.layers.", - .expert = "mlp.shared_expert.", - .inputs = &.{ "gate_proj", "up_proj" }, - .mtp = .{ .base = "language_model.mtp.layers.0.mlp.shared_expert." }, - }, - // silu(gate) is not zero below it as relu is: a wider margin keeps sigmoid(-16 * 0.5) = 3e-4 of it there - .neuron = .{ .act = .swiglu, .gated = true, .margin = 0.5, .sharp = 16 }, - .quant = .{ .bits = 4, .group = 32 }, - .keys = .{ .scope = "text_config", .width = "shared_expert_intermediate_size" }, - .experts = .every, -}; diff --git a/zig/src/living/whole.zig b/zig/src/living/whole.zig index f6a5b34ad0..d6a340d26d 100644 --- a/zig/src/living/whole.zig +++ b/zig/src/living/whole.zig @@ -85,7 +85,11 @@ pub fn begin(l: anytype, lesson: Lesson) !void { try l.probe.begin(l.trainer.?, l.answers, l.owned.held); l.phase = .probe; }, - .pocket => try startPocket(l), + .pocket => { + try startPocket(l); + // what taking this lesson out puts back, bit for bit: the pocket as the new fact finds it + try l.pockets.mark(); + }, .edit => if (comptime !editing(@TypeOf(l.*))) return error.EditsUnsupported else { try openEmpty(l); try startEdit(l); diff --git a/zig/src/native/slide_adapter.zig b/zig/src/native/slide_adapter.zig index 39ab12037d..c09ffe65ca 100644 --- a/zig/src/native/slide_adapter.zig +++ b/zig/src/native/slide_adapter.zig @@ -1,4 +1,4 @@ -//! A family's Living Weights learner behind the lane host's learn hook: lessons in, learn events out. +//! A family's Sliding Weights learner (living/learner.zig over its host) behind the lane host's learn hook. const std = @import("std"); const api = @import("engine_api"); const Allocator = std.mem.Allocator; @@ -6,7 +6,7 @@ const Allocator = std.mem.Allocator; /// Neurons a learn event carries at most; a fact takes about ten. const max_neurons = 64; -/// Why --slide cannot learn into `dir` (`Checks`: linked and plainShared files; `copy`: the copy to make), or null. +/// Why --slide cannot learn into `dir`. pub fn refusal(comptime Checks: type, a: Allocator, io: std.Io, dir: []const u8, copy: []const u8) !?[]const u8 { if (@hasDecl(Checks, "plainShared")) if (try Checks.plainShared(a, io, dir)) |name| return try std.fmt.allocPrint(a, "--slide adds learned neurons beside every shared expert, and {s} in {s} is unquantized, as TensorFold 1.0.3 to 1.0.6 saved their lessons: serve this folder without --slide (what it learned stays), or teach a fresh copy", .{ name, dir }); if (try Checks.linked(a, io, dir)) |name| return try std.fmt.allocPrint(a, "--slide rewrites the model's own files, and {s} in {s} is a link to data another file shares (a Hugging Face cache's blob, or a hard link), so learning would change that file too: serve a copy made with {s}", .{ name, dir, copy }); @@ -41,7 +41,7 @@ pub fn Adapter(comptime slide: type) type { const a: *Self = @ptrCast(@alignCast(ctx)); _ = a.arena.reset(.retain_capacity); const al = a.arena.allocator(); - try a.learner.begin(.{ .train = try examples(al, request.train), .think = try examples(al, request.think), .held = try examples(al, request.held), .near = try examples(al, request.near), .keep = try examples(al, request.keep), .asked = try examples(al, request.asked), .unasked = try examples(al, request.unasked), .kept = try examples(al, request.kept), .undo = request.undo, .steps = request.steps, .more = request.more, .reroute = request.reroute, .drop = request.drop, .save = request.save, .retire = try retired(al, request.retire), .unretire = request.unretire }); + try a.learner.begin(.{ .train = try examples(al, request.train), .think = try examples(al, request.think), .held = try examples(al, request.held), .near = try examples(al, request.near), .keep = try examples(al, request.keep), .asked = try examples(al, request.asked), .unasked = try examples(al, request.unasked), .kept = try examples(al, request.kept), .undo = request.undo, .steps = request.steps, .more = request.more, .reroute = request.reroute, .drop = request.drop, .save = request.save, .retire = try retired(al, request.retire), .unretire = request.unretire, .score = try examples(al, request.score), .quiet = try examples(al, request.quiet) }); a.sink = sink; a.sent = null; } @@ -54,6 +54,7 @@ pub fn Adapter(comptime slide: type) type { if (s.report) |r| a.emit(switch (r) { .learned => |x| .{ .learned = .{ .recalled = x.recalled, .steps = x.steps, .loss = x.loss, .neurons = a.placed() } }, .failed => |message| .{ .done = .{ .message = message } }, + .scored => |same| .{ .scored = .{ .same = same } }, }); if (s.done and !failed) a.emit(.{ .done = .{} }); return .{ .done = s.done, .changed = s.changed }; @@ -100,7 +101,7 @@ pub fn Adapter(comptime slide: type) type { fn examples(al: Allocator, xs: []const api.Example) ![]slide.Example { const out = try al.alloc(slide.Example, xs.len); - for (xs, out) |x, *o| o.* = .{ .ids = x.ids, .start = x.start, .decide = x.decide, .subject = x.subject, .value = x.value }; + for (xs, out) |x, *o| o.* = .{ .ids = x.ids, .start = x.start, .decide = x.decide, .subject = x.subject, .value = x.value, .context = x.context }; return out; } diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index d3427ff4c0..29f14f479a 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -62,6 +62,9 @@ pub const Reply = struct { logprobs: ?Value = null, /// ``choices[0].prompt_logprobs`` (vLLM's form) for a request that asked; null otherwise. prompt_logprobs: ?Value = null, + /// The prompt's token ids as the engine read them, and the reply's as it decoded them (an end token included). + prompt_ids: []const u32 = &.{}, + tokens: []const u32 = &.{}, }; pub const Failure = error{ Refused, Cancelled, Failed, OutOfMemory }; @@ -204,7 +207,9 @@ pub fn generate(srv: *Server, cx: *Cx, prepared: Prepared, sink: ?Sink, gone: an const result: Failure!Reply = blk: { if (sink != null and input.tools.len > 0) gen.calls = tool_stream.Streamer.init(a, input.tools) catch |e| break :blk e; gen.loop(gone) catch |e| break :blk e; - break :blk gen.finish(cx, prepared.prompt_len, received, thinking, effort, prepared.sampled, prepared.drafts); + var reply = gen.finish(cx, prepared.prompt_len, received, thinking, effort, prepared.sampled, prepared.drafts) catch |e| break :blk e; + reply.prompt_ids = request.prompt; + break :blk reply; }; if (result) |_| {} else |e| logEnded(input.id, e, cx.message, prepared.prompt_len, gen.collected.items.len, seconds(nowNs(io) - received)); return result; @@ -488,6 +493,7 @@ const Generation = struct { .effort = effort, .logprobs = if (g.lp) |l| try @import("logprobs.zig").value(g.srv, cx, a, g.thinking, content_tokens, l.rows.items) else null, .prompt_logprobs = if (m.prompt_rows) |r| try @import("logprobs.zig").promptValue(g.srv, a, r) else null, + .tokens = g.collected.items, }; if (std.mem.eql(u8, reason, "length") and thinking and reply_text.pyStrip(content).len == 0) log.line("warning: a reply reached max_tokens while still thinking, so its content is empty and its text is all in reasoning_content; raise max_tokens, or send chat_template_kwargs {{\"enable_thinking\": false}} (server: --no-thinking)", .{}); diff --git a/zig/src/server/root.zig b/zig/src/server/root.zig index 61044adf53..58efa0f632 100644 --- a/zig/src/server/root.zig +++ b/zig/src/server/root.zig @@ -52,9 +52,13 @@ test { _ = @import("decisions_test.zig"); _ = @import("slide.zig"); _ = @import("slide_graph.zig"); + _ = @import("slide_graph_test.zig"); + _ = @import("slide_recheck.zig"); _ = @import("slide_model.zig"); _ = @import("slide_lesson.zig"); + _ = @import("slide_router.zig"); _ = @import("slide_words.zig"); + _ = @import("slide_words_test.zig"); _ = @import("slide_found.zig"); _ = @import("slide_untold.zig"); _ = @import("slide_replace.zig"); @@ -64,6 +68,8 @@ test { _ = @import("slide_take.zig"); _ = @import("slide_teacher.zig"); _ = @import("slide_pick.zig"); + _ = @import("slide_route.zig"); + _ = @import("slide_context.zig"); _ = @import("startup.zig"); _ = @import("responses_include_test.zig"); _ = @import("cortheon/cortheon.zig"); diff --git a/zig/src/server/slide.zig b/zig/src/server/slide.zig index 0312840011..0826253037 100644 --- a/zig/src/server/slide.zig +++ b/zig/src/server/slide.zig @@ -10,6 +10,7 @@ const teach = @import("slide_lesson.zig"); const found = @import("slide_found.zig"); const wording = @import("slide_words.zig"); const check = @import("slide_verify.zig"); +const recheck = @import("slide_recheck.zig"); const replace = @import("slide_replace.zig"); const slide_graph = @import("slide_graph.zig"); const slide_teacher = @import("slide_teacher.zig"); @@ -74,6 +75,8 @@ pub fn learn(srv: *Server, conn: *Conn, a: Allocator) void { }; const text = body.strField("text") orelse return refuse(conn, a, 400, "text is required"); const source = body.strField("source") orelse "chat"; + // whom the told facts are about: "self" (the model: "Your name is Ada."), "user"; else judged for each fact + const about: ?teach.About = if (body.strField("about")) |w| std.meta.stringToEnum(teach.About, w) orelse return refuse(conn, a, 400, "about must be \"self\" or \"user\"") else null; switch (run(srv, a, &.{}, 0)) { .refused => |e| return switch (e) { error.Unsupported => refuse(conn, a, 501, "this engine does not learn: serve its model with --slide"), @@ -87,7 +90,7 @@ pub fn learn(srv: *Server, conn: *Conn, a: Allocator) void { var out: Out = .{ .conn = conn, .a = a }; var cx: errors.Cx = .{ .a = a }; const gone: Gone = .{ .conn = conn }; - const facts = found.facts(srv, &cx, text, source, gone) catch |e| return out.fail(&cx, e); + const facts = found.facts(srv, &cx, text, source, about != null, gone) catch |e| return out.fail(&cx, e); if (facts.len == 0) { out.event("failed", .{ .message = "no facts found in the text: nothing was learned" }); sse.done(conn) catch {}; @@ -99,6 +102,10 @@ pub fn learn(srv: *Server, conn: *Conn, a: Allocator) void { out.event("fact", .{ .id = id.*, .text = fact }); } defer saveAll(srv, a); + // facts learned before this server started, never checked since, asked once. + if (recheck.check(srv, &cx, 0, .unjudged, &.{}, gone)) |before| { + for (before) |r| out.event("recheck", .{ .id = @as(u32, 0), .fact = r.fact.id, .text = r.fact.text, .recalled = r.recalled, .was = r.recalled }); + } else |e| log.line("slide: the facts learned before could not be asked again: {s}", .{words(&cx, e)}); // each fact its own lesson and block, so each keeps a gate of its own for (facts, ids) |fact, id| { if (gone.check()) break; @@ -107,10 +114,13 @@ pub fn learn(srv: *Server, conn: *Conn, a: Allocator) void { out.event("learning", .{ .id = id }); var kept = [1]bool{false}; const written = now(srv); - // a chat fact not about the user ("The Quillon bridge is 1,312 metres long.") learns as a document's does - const document = !std.mem.eql(u8, source, "chat") or !wording.firstPerson(fact); - const gave = if (document) &.{} else giveWay(srv, a, &cx, fact, id, gone); - const plan = (teach.lesson(srv, &cx, &srv.teacher, &.{fact}, &kept, document, facts, gone) catch |e| { + // a chat fact told to the model about itself ("Your name is Ada.") is the model's own, asked of it. + const chat = std.mem.eql(u8, source, "chat"); + const self = chat and (if (about) |w| w == .self else teach.aboutSelf(srv, &cx, fact, gone) catch false); + const document = !chat or (!self and about == null and !wording.firstPerson(fact)); + if (chat) log.line("slide: fact {d} \"{s}\" is learned as {s}", .{ id, fact, if (self) "a fact about the model itself" else if (document) "a document's fact (it is not about the user)" else "a fact about the user" }); + const gave = if (document) &.{} else giveWay(srv, a, &cx, &out, fact, id, self, gone); + const plan = (teach.lesson(srv, &cx, &srv.teacher, &.{fact}, &kept, document, if (document) null else @as(?teach.About, if (self) .self else .user), facts, gone) catch |e| { missed(srv, &out, id, words(&cx, e)); putBack(srv, a, gave, id); continue; @@ -119,15 +129,18 @@ pub fn learn(srv: *Server, conn: *Conn, a: Allocator) void { putBack(srv, a, gave, id); continue; }; - log.line("slide: fact {d}'s lesson written in {d:.1} s", .{ id, seconds(srv, written) }); - srv.slide.asked(id, questions(a, plan)); - const result = rounds(srv, a, &cx, plan, gone, id); + const writing = seconds(srv, written); + log.line("slide: fact {d}'s lesson written in {d:.1} s", .{ id, writing }); + srv.slide.asked(id, wordings(a, plan)); + const result = rounds(srv, a, &cx, plan, gone, id, &out); + const tk = result.took; + log.line("slide: fact {d}'s lesson took {d:.1} s: writing {d:.1}, fitting {d:.1}, checking {d:.1} (held-out {d:.1}, the facts before {d:.1}, broad questions {d:.1})", .{ id, seconds(srv, written), writing, tk.fit, tk.check + tk.recheck + tk.broad, tk.check, tk.recheck, tk.broad }); const back = result.recalled.len == 1 and result.recalled[0]; if (!back) putBack(srv, a, gave, id); if (back) slide_teacher.refresh(srv, &cx, &srv.teacher, plan.stale, gone) catch srv.teacher.forgetAnswers(srv.io); if (result.why) |why| srv.slide.note(id, why); srv.slide.mark(id, if (back) .learned else .missed); - if (back and document) for (plan.held) |h| if (h.subject.len > 0) srv.teacher.remember(h.subject, h.question, h.answer) catch {}; + if (back and document) for (plan.held) |h| if (h.subject.len > 0 and h.context.len == 0) srv.teacher.remember(h.subject, h.question, h.answer) catch {}; if (result.why) |why| { out.event("learned", .{ .id = id, .recalled = back, .steps = result.steps, .message = why }); } else out.event("learned", .{ .id = id, .recalled = back, .steps = result.steps }); @@ -135,26 +148,45 @@ pub fn learn(srv: *Server, conn: *Conn, a: Allocator) void { sse.done(conn) catch {}; } +/// Rounds in a row whose held-out questions all come back when asked that end a lesson. +fn confirm() u32 { + const v = std.c.getenv("TF_SLIDE_ROUNDS") orelse return 2; + return if (std.mem.eql(u8, std.mem.span(v), "one")) 1 else 2; +} + /// Rounds a lesson gets to bring its facts back when asked once, before it is given up. const give_up = 5; /// What a lesson's rounds left: which facts come back, the steps taken, and why it stopped early (null: it did not). -const Rounds = struct { recalled: []bool, steps: u32 = 0, why: ?[]const u8 = null }; +const Rounds = struct { recalled: []bool, steps: u32 = 0, why: ?[]const u8 = null, took: Took = .{} }; + +/// Where a lesson's rounds spent their time (s): fitting (the learner's runs), its held-out checks. +const Took = struct { fit: f64 = 0, check: f64 = 0, recheck: f64 = 0, broad: f64 = 0 }; /// A lesson in checked rounds until its fact comes back; a question it took is handed back (a few times at most). -fn rounds(srv: *Server, a: Allocator, cx: *errors.Cx, plan: teach.Plan, gone: Gone, id: u32) Rounds { +fn rounds(srv: *Server, a: Allocator, cx: *errors.Cx, plan: teach.Plan, gone: Gone, id: u32, o: *Out) Rounds { var out: Rounds = .{ .recalled = a.alloc(bool, plan.facts.len) catch &.{} }; @memset(out.recalled, false); var routed: u32 = 0; + var repaired: u32 = 0; + // the facts learned before, as they stood when this lesson began: what its checks find forgotten is against these + const before = srv.slide.earlier(a, id) catch &.{}; + // broad questions as answered before it, which a kept lesson's answers are compared with for made-up names + var at = now(srv); + const broad_before = recheck.askBroad(srv, cx, gone) catch &.{}; + out.took.broad += seconds(srv, at); + var unchecked = false; // the lesson was fitted again after its last check var streak: u32 = 0; // rounds in a row whose held-out questions came back when asked var ever = false; // a round whose held-out questions all came back when asked - for (0..teach.rounds + teach.reroutes) |round| { + for (0..teach.rounds + teach.reroutes + recheck.repairs) |round| { const began = now(srv); var request = plan.full; request.more = round > 0; var held = false; srv.slide.round(id, @intCast(round + 1)); - switch (run(srv, a, &request, id)) { + const ran = run(srv, a, &request, id); + out.took.fit += seconds(srv, began); + switch (ran) { .learned => |l| { out.steps += l.steps; held = l.recalled; @@ -166,9 +198,11 @@ fn rounds(srv: *Server, a: Allocator, cx: *errors.Cx, plan: teach.Plan, gone: Go else => return out, } const learned = seconds(srv, began); + unchecked = false; const checked = now(srv); srv.slide.phase(id, .checking); const verdict = check.verify(srv, cx, plan, held or round + 1 >= teach.rounds, gone) catch |e| check.Verdict{ .recalled = out.recalled, .damage = words(cx, e) }; + out.took.check += seconds(srv, checked); srv.slide.checked(id, verdict.damage == null and std.mem.allEqual(bool, verdict.recalled, true)); log.line("slide: round {d}: {d} steps ({d:.1} s learning, {d:.1} s checking); the held-out answers {s} token for token, and {s} when asked", .{ round + 1, out.steps, learned, seconds(srv, checked), if (held) "come back" else "do not come back", if (std.mem.allEqual(bool, verdict.recalled, true)) "come back" else "do not come back" }); if (verdict.took) |took| { @@ -184,7 +218,10 @@ fn rounds(srv: *Server, a: Allocator, cx: *errors.Cx, plan: teach.Plan, gone: Go out.why = words(cx, e); return out; }; - switch (run(srv, a, &.{ .unasked = &.{back.prompt}, .kept = &.{back.kept}, .reroute = true }, id)) { + at = now(srv); + const rerouted = run(srv, a, &.{ .unasked = &.{back.prompt}, .kept = &.{back.kept}, .reroute = true }, id); + out.took.fit += seconds(srv, at); + switch (rerouted) { .failed => |message| { out.why = message; return out; @@ -207,10 +244,61 @@ fn rounds(srv: *Server, a: Allocator, cx: *errors.Cx, plan: teach.Plan, gone: Go ever = ever or streak > 0; // rounds that never once brought the fact back when asked do not start to: give up rather than learn on if (!ever and round + 1 >= give_up) break; - // done once its answers come back token for token, or come back when asked two rounds running - if ((held or streak >= 2) and std.mem.allEqual(bool, out.recalled, true) and round + 1 >= teach.min_rounds) return out; + // done once its answers come back token for token, or come back when asked two rounds running. + if ((held or streak >= confirm()) and std.mem.allEqual(bool, out.recalled, true) and round + 1 >= teach.min_rounds) { + at = now(srv); + const lost = earlierLost(srv, cx, o, id, before, gone) catch |e| { + takeOut(srv, a, &out, id, std.fmt.allocPrint(a, "taken out: the facts learned before could not be asked again ({s})", .{words(cx, e)}) catch "taken out"); + return out; + }; + out.took.recheck += seconds(srv, at); + if (lost.len == 0) { + at = now(srv); + if (broad_before.len > 0) drift(srv, cx, o, id, plan, broad_before, gone); + out.took.broad += seconds(srv, at); + // a diagnostic: every kept lesson taken out again, to see the facts before it as they were + if (std.c.getenv("TF_SLIDE_TAKE_OUT_CHECK") != null) { + takeOut(srv, a, &out, id, "taken out to check that a take-out puts the facts before it back (TF_SLIDE_TAKE_OUT_CHECK)"); + afterTakeOut(srv, cx, o, id, before, &.{}, gone); + } + return out; + } + const who = recheck.names(a, lost) catch "an earlier fact"; + if (repaired < recheck.repairs) { + const back = recheck.keeps(srv, cx, lost) catch |e| { + takeOut(srv, a, &out, id, words(cx, e)); + return out; + }; + if (back.kept.len > 0) { + repaired += 1; + log.line("slide: fact {d}'s lesson made the model forget {s}: fitted again with their held-out answers kept as they were (repair {d} of {d})", .{ id, who, repaired, recheck.repairs }); + o.event("repair", .{ .id = id, .message = std.fmt.allocPrint(a, "it made the model forget {s}: fitted again with their answers kept", .{who}) catch who }); + at = now(srv); + const refit = run(srv, a, &.{ .unasked = back.prompts, .kept = back.kept, .reroute = true }, id); + out.took.fit += seconds(srv, at); + switch (refit) { + .failed => |message| { + takeOut(srv, a, &out, id, message); + return out; + }, + else => {}, + } + unchecked = true; + continue; + } + } + takeOut(srv, a, &out, id, if (repaired > 0) std.fmt.allocPrint(a, "taken out: it made the model forget {s}, still after {d} repairs", .{ who, repaired }) catch who else std.fmt.allocPrint(a, "taken out: it made the model forget {s}", .{who}) catch who); + // the facts asked once more with it out, as they will be saved: the ones it made forget are back + afterTakeOut(srv, cx, o, id, before, lost, gone); + return out; + } + } + // it never came back when asked, or was fitted again and never checked: nothing of it stays in the model + if (unchecked) { + takeOut(srv, a, &out, id, "taken out: its last repair was never checked"); + afterTakeOut(srv, cx, o, id, before, &.{}, gone); + return out; } - // it never came back when asked: nothing of it stays in the model if (!std.mem.allEqual(bool, out.recalled, true)) { _ = run(srv, a, &.{ .drop = true }, 0); srv.slide.placed(id, &.{}); @@ -218,14 +306,66 @@ fn rounds(srv: *Server, a: Allocator, cx: *errors.Cx, plan: teach.Plan, gone: Go return out; } -/// The wordings a lesson's checks ask: its held-out questions, then the ones it never learned. -fn questions(a: Allocator, plan: teach.Plan) []const []const u8 { - const out = a.alloc([]const u8, plan.held.len + plan.probes.len) catch return &.{}; - for (plan.held, out[0..plan.held.len]) |h, *q| q.* = h.question; - for (plan.probes, out[plan.held.len..]) |h, *q| q.* = h.question; +/// The wordings a lesson's checks ask: its held-out questions, then the ones it never learned, with their answers. +fn wordings(a: Allocator, plan: teach.Plan) []const slide_graph.Asked { + const out = a.alloc(slide_graph.Asked, plan.held.len + plan.probes.len) catch return &.{}; + for (plan.held, out[0..plan.held.len]) |h, *w| w.* = .{ .question = h.question, .answer = h.answer, .short = h.short, .context = h.context }; + for (plan.probes, out[plan.held.len..]) |h, *w| w.* = .{ .question = h.question, .answer = h.answer, .short = h.short, .probe = true }; return out; } +/// The facts learned before fact `id` asked again, each verdict on the stream; those that came back before and not now. +fn earlierLost(srv: *Server, cx: *errors.Cx, o: *Out, id: u32, before: []const slide_graph.Earlier, gone: Gone) ![]const recheck.Result { + const began = now(srv); + const results = try recheck.check(srv, cx, id, .all, before, gone); + var back: u32 = 0; + for (results) |r| { + back += @intFromBool(r.recalled); + o.event("recheck", .{ .id = id, .fact = r.fact.id, .text = r.fact.text, .recalled = r.recalled, .was = r.was }); + } + const lost = try recheck.forgotten(cx.a, results); + if (results.len == 0) return lost; + const took = seconds(srv, began); + log.line("slide: fact {d}'s lesson: the {d} facts learned before asked again in {d:.1} s: {d} come back, {d} forgotten", .{ id, results.len, took, back, lost.len }); + o.event("rechecked", .{ .id = id, .facts = @as(u32, @intCast(results.len)), .recalled = back, .forgotten = @as(u32, @intCast(lost.len)), .seconds = took }); + return lost; +} + +/// The broad questions asked again after a kept lesson: a reply that names what no learned fact said is flagged. +fn drift(srv: *Server, cx: *errors.Cx, o: *Out, id: u32, plan: teach.Plan, before: []const []const u8, gone: Gone) void { + const a = cx.a; + const now_said = recheck.askBroad(srv, cx, gone) catch return; + var facts: std.ArrayList([]const u8) = .empty; + facts.appendSlice(a, plan.facts) catch return; + for (srv.slide.earlier(a, id) catch &.{}) |e| facts.append(a, e.text) catch return; + for (recheck.broad, before, now_said) |q, was, reply| if (recheck.invented(reply, was, q, facts.items)) |name| { + log.line("slide: fact {d}'s lesson: \"{s}\" now names \"{s}\", which no learned fact says: {s}", .{ id, q, name, reply }); + o.event("drift", .{ .id = id, .question = q, .name = name, .reply = reply }); + }; +} + +/// The facts learned before asked again once a lesson is taken out (the pocket put back as the lesson found it). +fn afterTakeOut(srv: *Server, cx: *errors.Cx, o: *Out, id: u32, before: []const slide_graph.Earlier, lost: []const recheck.Result, gone: Gone) void { + const still = earlierLost(srv, cx, o, id, before, gone) catch |e| return log.line("slide: fact {d}: the facts learned before could not be asked again after its take-out: {s}", .{ id, words(cx, e) }); + var back: u32 = 0; + for (lost) |l| { + for (still) |x| { + if (x.fact.id == l.fact.id) break; + } else back += 1; + } + log.line("slide: fact {d} taken out: of the {d} facts it made forget, {d} come back; {d} facts that came back before it do not now", .{ id, lost.len, back, still.len }); + o.event("restored", .{ .id = id, .forgotten = @as(u32, @intCast(lost.len)), .back = back, .lost = @as(u32, @intCast(still.len)) }); +} + +/// The open lesson taken out whole (its neurons free, earlier ones it fitted again as they were), and why. +fn takeOut(srv: *Server, a: Allocator, out: *Rounds, id: u32, why: []const u8) void { + _ = run(srv, a, &.{ .drop = true }, 0); + srv.slide.placed(id, &.{}); + @memset(out.recalled, false); + out.why = why; + log.line("slide: fact {d}: {s}", .{ id, why }); +} + /// Every kept lesson into the model's shards, timed, with the shards it changed. fn saveAll(srv: *Server, a: Allocator) void { srv.slide.saving(folder(srv)); @@ -240,8 +380,8 @@ fn saveAll(srv: *Server, a: Allocator) void { } /// Earlier chat facts `fact` replaces ("I like blue." for "Now I like red."): their neurons zeroed, marked replaced. -fn giveWay(srv: *Server, a: Allocator, cx: *errors.Cx, fact: []const u8, id: u32, gone: Gone) []const slide_graph.Fact { - const olds = replace.replaced(srv, cx, fact, id, gone) catch return &.{}; +fn giveWay(srv: *Server, a: Allocator, cx: *errors.Cx, out: *Out, fact: []const u8, id: u32, self: bool, gone: Gone) []const slide_graph.Fact { + const olds = replace.replaced(srv, cx, fact, id, self, gone) catch return &.{}; if (olds.len == 0) return &.{}; var neurons: std.ArrayList(api.Neuron) = .empty; for (olds) |o| neurons.appendSlice(a, o.neurons) catch return &.{}; @@ -252,6 +392,7 @@ fn giveWay(srv: *Server, a: Allocator, cx: *errors.Cx, fact: []const u8, id: u32 for (olds) |o| { srv.slide.note(o.id, std.fmt.allocPrint(a, "replaced by fact {d}", .{id}) catch "replaced"); srv.slide.mark(o.id, .replaced); + out.event("replaces", .{ .id = id, .fact = o.id, .text = o.text }); } srv.teacher.forgetBank(srv.io); return olds; @@ -284,10 +425,11 @@ const Outcome = union(enum) { learned: struct { recalled: bool, steps: u32 }, failed: []const u8, refused: api.LearnError, + scored: []const bool, }; /// One lesson through the engine's learner, waited for to its end; fact `id`'s progress and neurons go to the graph. -fn run(srv: *Server, a: Allocator, request: *const api.LearnRequest, id: u32) Outcome { +pub fn run(srv: *Server, a: Allocator, request: *const api.LearnRequest, id: u32) Outcome { var box: Box = .{ .io = srv.io, .gpa = srv.gpa }; defer box.deinit(); srv.engine.learn(request, box.sink()) catch |e| return .{ .refused = e }; @@ -310,9 +452,11 @@ fn run(srv: *Server, a: Allocator, request: *const api.LearnRequest, id: u32) Ou .done => if (c.text.len > 0) { outcome = .{ .failed = a.dupe(u8, c.text) catch "the learner failed" }; }, + .scored => outcome = if (a.dupe(bool, c.same)) |same| .{ .scored = same } else |_| .none, } srv.gpa.free(c.text); srv.gpa.free(c.neurons); + srv.gpa.free(c.same); } batch.clearRetainingCapacity(); if (finished) return outcome; @@ -333,6 +477,7 @@ const Out = struct { const value: json.Value = switch (@TypeOf(v)) { bool => .{ .bool = v }, u32 => json.intValue(o.a, v) catch return, + f64 => .{ .float = @round(v * 10) / 10 }, else => .{ .string = v }, }; obj.put(o.a, name, value) catch return; @@ -384,7 +529,7 @@ const Box = struct { events: std.ArrayList(Copy) = .empty, done: bool = false, - const Copy = struct { kind: std.meta.Tag(api.LearnEvent), text: []const u8 = "", recalled: bool = false, steps: u32 = 0, progress: api.LearnProgress = .{ .phase = .reading }, neurons: []const api.Neuron = &.{} }; + const Copy = struct { kind: std.meta.Tag(api.LearnEvent), text: []const u8 = "", recalled: bool = false, steps: u32 = 0, progress: api.LearnProgress = .{ .phase = .reading }, neurons: []const api.Neuron = &.{}, same: []const bool = &.{} }; fn sink(b: *Box) api.LearnSink { return .{ .ctx = b, .event = onEvent }; @@ -405,12 +550,14 @@ const Box = struct { c.neurons = b.gpa.dupe(api.Neuron, p.neurons) catch &.{}; }, .done => |d| c.text = b.gpa.dupe(u8, d.message) catch "", + .scored => |x| c.same = b.gpa.dupe(bool, x.same) catch &.{}, } b.mutex.lockUncancelable(b.io); defer b.mutex.unlock(b.io); b.events.append(b.gpa, c) catch { b.gpa.free(c.text); b.gpa.free(c.neurons); + b.gpa.free(c.same); }; if (e.* == .done) b.done = true; b.cond.signal(b.io); @@ -430,6 +577,7 @@ const Box = struct { for (b.events.items) |c| { b.gpa.free(c.text); b.gpa.free(c.neurons); + b.gpa.free(c.same); } b.events.deinit(b.gpa); } diff --git a/zig/src/server/slide_ask.zig b/zig/src/server/slide_ask.zig index fca6c989ef..456ddda098 100644 --- a/zig/src/server/slide_ask.zig +++ b/zig/src/server/slide_ask.zig @@ -2,6 +2,7 @@ const std = @import("std"); const api = @import("engine_api"); const json = @import("json.zig"); +const known = @import("slide_known.zig"); const chat = @import("chat.zig"); const prompt = @import("prompt.zig"); const errors = @import("errors.zig"); @@ -66,7 +67,27 @@ pub fn ask(srv: *Server, cx: *Cx, system: ?[]const u8, user: []const u8, max_tok try fields.put(a, "enable_thinking", .{ .bool = false }); try fields.put(a, "temperature", .{ .float = 0 }); const prepared = try chat.prepare(srv, cx, .{ .messages = .{ .array = list.items }, .fields = .{ .object = fields }, .max_tokens = max_tokens, .temperature = 0 }, gone); - return chat.generate(srv, cx, prepared, null, gone); + const reply = try chat.generate(srv, cx, prepared, null, gone); + srv.teacher.replies.remember(srv.io, known.key(system, &.{}, user, max_tokens), reply); + return reply; +} + +/// One greedy reply without thinking to `user` asked after conversation `before` (user lines and the model's replies). +pub fn askIn(srv: *Server, cx: *Cx, before: []const [2][]const u8, user: []const u8, max_tokens: i64, gone: anytype) chat.Failure!chat.Reply { + const a = cx.a; + var list: std.ArrayList(Value) = .empty; + for (before) |t| { + try list.append(a, try message(a, "user", t[0])); + try list.append(a, try message(a, "assistant", t[1])); + } + try list.append(a, try message(a, "user", user)); + const fields = try json.newObject(a); + try fields.put(a, "enable_thinking", .{ .bool = false }); + try fields.put(a, "temperature", .{ .float = 0 }); + const prepared = try chat.prepare(srv, cx, .{ .messages = .{ .array = list.items }, .fields = .{ .object = fields }, .max_tokens = max_tokens, .temperature = 0 }, gone); + const reply = try chat.generate(srv, cx, prepared, null, gone); + srv.teacher.replies.remember(srv.io, known.key(null, before, user, max_tokens), reply); + return reply; } /// One greedy reply as `ask` gives it, from the model as shipped (no lesson acts): a lesson's writer hears none. diff --git a/zig/src/server/slide_context.zig b/zig/src/server/slide_context.zig new file mode 100644 index 0000000000..18541a2e32 --- /dev/null +++ b/zig/src/server/slide_context.zig @@ -0,0 +1,167 @@ +//! Conversations a fact's questions are also learned and checked in. +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json.zig"); +const chat = @import("chat.zig"); +const prompt = @import("prompt.zig"); +const errors = @import("errors.zig"); +const log = @import("log.zig"); +const slide_ask = @import("slide_ask.zig"); +const side = @import("slide_side.zig"); +const Server = @import("server.zig").Server; +const Allocator = std.mem.Allocator; +const Value = json.Value; +const Cx = errors.Cx; + +/// A user's line and the model's reply to it. +pub const Turn = [2][]const u8; + +/// A conversation's user lines, and how long each reply may run. +const Script = struct { name: []const u8, lines: []const []const u8, max: i64 }; + +/// The conversations: those a lesson learns in, then those only its checks ask in (never learned from). +pub const scripts = [_]Script{ + .{ .name = "talk", .max = 64, .lines = &.{ + "Morning! I just made a pot of coffee. How are you today?", + "I'm thinking about getting back into running after a long break. Any advice?", + "Thanks, that helps. What's a good stretch to do after a run?", + } }, + .{ .name = "task", .max = 360, .lines = &.{ + "How do I write a debounce function in JavaScript? I want a search box to stop firing on every keystroke.", + "Can you rewrite it in TypeScript with proper generic types?", + "How would I test it with Jest's fake timers?", + } }, + .{ .name = "long", .max = 440, .lines = &.{ + "I'm writing a bash script that backs up my photos folder to an external drive every night. Can you sketch one with rsync?", + "How do I make it skip the run when the drive isn't mounted?", + "Now I'd like it to keep the last seven nightly copies and delete older ones. How?", + "How do I schedule it with cron, and where do its logs go?", + "Separate question: what's the difference between git merge and git rebase, and when should I use each?", + "And how do I undo a rebase that went wrong?", + } }, + // the opening of a chain of questions: one the model answers, one about the user it was never told + .{ .name = "opener", .max = 48, .lines = &.{ + "How many legs does a spider have?", + "What did I eat for breakfast today?", + } }, + // checks only + .{ .name = "check", .max = 360, .lines = &.{ + "I want to run a small Go web server in Docker. Can you write a minimal main.go that answers 'hello' on port 8080?", + "Now a Dockerfile for it, as small as you can make it.", + "How do I pass a setting in through an environment variable?", + "What's the difference between CMD and ENTRYPOINT?", + } }, + .{ .name = "recall", .max = 48, .lines = &.{ + "What's the tallest mountain in Africa?", + "What's the name of my first pet?", + } }, +}; + +/// The conversations a lesson learns its questions in: small talk, a short and a long unrelated task. +pub const learned = [_][]const u8{ "talk", "task", "long", "chain" }; + +/// The conversations a held-out question is checked in, one a held-out question. +pub const checked = [_][]const u8{ "check", "recall" }; + +/// Earlier facts' questions a chain carries at most, the latest first. +const chained = 2; + +fn script(name: []const u8) ?Script { + for (scripts) |s| if (std.mem.eql(u8, s.name, name)) return s; + return null; +} + +/// Conversation `name` as the model replies to its lines (greedy, thinking off). +pub fn turns(srv: *Server, cx: *Cx, name: []const u8, gone: anytype) ![]const Turn { + if (name.len == 0) return &.{}; + if (std.mem.eql(u8, name, "chain")) return chain(srv, cx, gone); + return written(srv, cx, name, gone); +} + +/// A scripted conversation, from the graph or written now (and kept there). +fn written(srv: *Server, cx: *Cx, name: []const u8, gone: anytype) ![]const Turn { + if (try srv.slide.talk(cx.a, name)) |kept| return kept; + const s = script(name) orelse return &.{}; + const a = cx.a; + const out = try a.alloc(Turn, s.lines.len); + for (s.lines, out, 0..) |line, *t, i| { + const reply = try slide_ask.askIn(srv, cx, out[0..i], line, s.max, gone); + t.* = .{ line, std.mem.trim(u8, reply.content, " \t\r\n") }; + } + srv.slide.keepTalk(name, out); + var tokens: usize = 0; + for (out) |t| tokens += t[0].len + t[1].len; + log.line("slide: the \"{s}\" conversation written: {d} turns, {d} characters", .{ name, out.len, tokens }); + return out; +} + +/// Scripted conversations among `names` not yet in the graph, written side by side (each one's turns in order). +pub fn prewrite(srv: *Server, cx: *Cx, names: []const []const u8, gone: anytype) !void { + var missing: std.ArrayList([]const u8) = .empty; + for (names) |name| if (script(name) != null and try srv.slide.talk(cx.a, name) == null) try missing.append(cx.a, name); + if (missing.items.len < 2) return; + const Job = struct { + srv: *Server, + a: Allocator, + names: []const []const u8, + gone: @TypeOf(gone), + + pub fn run(j: *const @This(), i: usize) !void { + var jcx: Cx = .{ .a = j.a }; + _ = try written(j.srv, &jcx, j.names[i], j.gone); + } + }; + try side.each(missing.items.len, &Job{ .srv = srv, .a = cx.a, .names = missing.items, .gone = gone }); +} + +/// The chain a fact's questions are learned after: the opener, then the latest learned facts' first questions with the. +fn chain(srv: *Server, cx: *Cx, gone: anytype) ![]const Turn { + const a = cx.a; + var out: std.ArrayList(Turn) = .empty; + try out.appendSlice(a, try written(srv, cx, "opener", gone)); + const facts = try srv.slide.earlier(a, 0); + var i = facts.len; + var n: usize = 0; + var picked: std.ArrayList(Turn) = .empty; + while (i > 0 and n < chained) : (i -= 1) { + const f = facts[i - 1]; + for (f.asked) |w| if (w.context.len == 0 and !w.probe and w.answer.len > 0) { + try picked.append(a, .{ w.question, w.answer }); + n += 1; + break; + }; + } + std.mem.reverse(Turn, picked.items); + try out.appendSlice(a, picked.items); + return out.items; +} + +/// `before` and then `question` as chat messages. +pub fn messages(a: Allocator, before: []const Turn, question: []const u8) ![]Value { + var out: std.ArrayList(Value) = .empty; + for (before) |t| { + try out.append(a, try slide_ask.message(a, "user", t[0])); + try out.append(a, try slide_ask.message(a, "assistant", t[1])); + } + try out.append(a, try slide_ask.message(a, "user", question)); + return out.items; +} + +/// `question` as the model reads it after conversation `before`, its prompt rows only. +pub fn promptIn(srv: *Server, cx: *Cx, keep: Allocator, before: []const Turn, question: []const u8) !api.Example { + const a = cx.a; + const head = try prompt.renderIds(srv, cx, .{ .array = try messages(a, before, question) }, &.{}, false, null, true); + if (head.len < 3) return cx.refuse("a question renders too short to route"); + // the rows any other question after the same conversation shares + const other = try prompt.renderIds(srv, cx, .{ .array = try messages(a, before, "?") }, &.{}, false, null, true); + var cut: usize = 0; + while (cut < head.len and cut < other.len and head[cut] == other[cut]) cut += 1; + const decide = prompt.decideOf(srv, head); + return .{ .ids = try keep.dupe(u32, head), .start = @intCast(head.len - 1), .decide = decide, .context = if (before.len > 0 and cut < decide) @intCast(cut) else 0 }; +} + +test "the conversations a lesson learns in are not the ones its checks ask in" { + for (learned) |l| for (checked) |c| try std.testing.expect(!std.mem.eql(u8, l, c)); + for (checked) |c| try std.testing.expect(script(c) != null); + for (learned) |l| try std.testing.expect(std.mem.eql(u8, l, "chain") or script(l) != null); +} diff --git a/zig/src/server/slide_found.zig b/zig/src/server/slide_found.zig index dbb401b2e0..a68476c9f8 100644 --- a/zig/src/server/slide_found.zig +++ b/zig/src/server/slide_found.zig @@ -13,11 +13,11 @@ const Cx = errors.Cx; const chunk_chars = 6000; // text a fact-finding call reads at once -/// The facts in `text`: short chat's sentences, else what the model finds worth remembering in it; then the other way -pub fn facts(srv: *Server, cx: *Cx, text: []const u8, source: []const u8, gone: anytype) ![]const []const u8 { +/// The facts in `text`: short chat's sentences, else what the model finds worth remembering in it. +pub fn facts(srv: *Server, cx: *Cx, text: []const u8, source: []const u8, as_told: bool, gone: anytype) ![]const []const u8 { const a = cx.a; const told = try wording.sentences(a, text); - if (std.mem.eql(u8, source, "chat") and told.len <= 4) return reversed(srv, cx, told, text, gone); + if (std.mem.eql(u8, source, "chat") and told.len <= 4) return if (as_told) told else reversed(srv, cx, told, text, gone); var out: std.ArrayList([]const u8) = .empty; var at: usize = 0; while (at < text.len) : (at += chunk_chars) try find(srv, cx, &out, text[at..@min(text.len, at + chunk_chars)], text, gone); @@ -38,7 +38,8 @@ fn reversed(srv: *Server, cx: *Cx, found: []const []const u8, text: []const u8, replies: [][]const u8, pub fn run(j: *const @This(), i: usize) !void { - if (wording.firstPerson(j.found[i])) return; + // the user's own facts, and those told to the model about itself. + if (wording.firstPerson(j.found[i]) or wording.addressesModel(j.found[i])) return; var jcx: Cx = .{ .a = j.a }; const r = try askBase(j.srv, &jcx, null, try std.fmt.allocPrint(j.a, prompts.reverse_prompt, .{j.found[i]}), 48, j.gone); j.replies[i] = r.content; diff --git a/zig/src/server/slide_graph.zig b/zig/src/server/slide_graph.zig index 596da2b110..30cf01efbf 100644 --- a/zig/src/server/slide_graph.zig +++ b/zig/src/server/slide_graph.zig @@ -19,6 +19,10 @@ pub const Fact = struct { state: State, neurons: []const api.Neuron = &.{}, // where its neurons sit in the pocket, once placed questions: []const []const u8 = &.{}, // the wordings its checks ask + answers: []const []const u8 = &.{}, // the answer its lesson wrote for each ("": none known), what a later check looks for + shorts: []const []const u8 = &.{}, // and the fewest words that answer each ("": none) + contexts: []const []const u8 = &.{}, // the conversation each is asked after ("": none; slide_context.zig) + probes: u32 = 0, // the last ones of its questions are wordings it never learned: half of those must bring it back message: []const u8 = "", // why it stopped, or what its lesson last did round: u32 = 0, // its lesson's round now, or the rounds it took checks: u32 = 0, // asked checks done, this session @@ -30,6 +34,15 @@ pub const Fact = struct { loss: ?f32 = null, // its outputs' loss at the last step }; +/// A wording a fact's checks ask: the answer its lesson wrote and the fewest words that answer it. +pub const Asked = struct { question: []const u8, answer: []const u8 = "", short: []const u8 = "", probe: bool = false, context: []const u8 = "" }; + +/// A conversation kept for every lesson and check to ask in: its name, its user lines and the model's replies. +pub const Talk = struct { name: []const u8, turns: []const [2][]const u8 }; + +/// A learned fact as a later lesson checks it again: what it says, its wordings, its last check's verdict (null: none). +pub const Earlier = struct { id: u32, text: []const u8, asked: []const Asked, recalled: ?bool }; + /// The last save of the pocket into the shards: when, how long, the files it changed and their shared experts' bytes. const Save = struct { state: enum { none, saving, saved, failed } = .none, @@ -60,6 +73,7 @@ pub const Graph = struct { model: ?slide_model.Model = null, // the served folder as last scanned model_arena: std.heap.ArenaAllocator, saved: Save = .{}, + talks: std.ArrayList(Talk) = .empty, // conversations written once, kept with the facts /// A graph that starts from `path`'s file when it reads, else empty. pub fn init(gpa: Allocator, io: Io, path: ?[]const u8) Graph { @@ -70,6 +84,7 @@ pub const Graph = struct { pub fn deinit(g: *Graph) void { g.facts.deinit(g.gpa); + g.talks.deinit(g.gpa); g.trace.deinit(g.gpa); g.cuts.deinit(g.gpa); g.arena.deinit(); @@ -200,15 +215,89 @@ pub const Graph = struct { g.save(); } - /// The wordings a fact's checks ask. - pub fn asked(g: *Graph, id: u32, questions: []const []const u8) void { + /// The wordings a fact's checks ask, held-out questions first, with the answers its lesson wrote for them. + pub fn asked(g: *Graph, id: u32, wordings: []const Asked) void { + g.mutex.lockUncancelable(g.io); + defer g.mutex.unlock(g.io); + const f = g.find(id) orelse return; + const a = g.arena.allocator(); + const qs = a.alloc([]const u8, wordings.len) catch return; + const answers = a.alloc([]const u8, wordings.len) catch return; + const shorts = a.alloc([]const u8, wordings.len) catch return; + const contexts = a.alloc([]const u8, wordings.len) catch return; + var probes: u32 = 0; + for (wordings, qs, answers, shorts, contexts) |w, *q, *ans, *short, *c| { + q.* = a.dupe(u8, w.question) catch return; + ans.* = a.dupe(u8, w.answer) catch return; + short.* = a.dupe(u8, w.short) catch return; + c.* = a.dupe(u8, w.context) catch return; + probes += @intFromBool(w.probe); + } + f.questions = qs; + f.answers = answers; + f.shorts = shorts; + f.contexts = contexts; + f.probes = probes; + g.save(); + } + + /// Every learned fact but `id`, in teaching order, copied into `a`: what a lesson checks again once it is done. + pub fn earlier(g: *Graph, a: Allocator, id: u32) ![]Earlier { + g.mutex.lockUncancelable(g.io); + defer g.mutex.unlock(g.io); + var out: std.ArrayList(Earlier) = .empty; + for (g.facts.items) |f| { + if (f.id == id or f.state != .learned or f.questions.len == 0) continue; + const asked_ = try a.alloc(Asked, f.questions.len); + const held = f.questions.len - @min(f.probes, f.questions.len); + for (asked_, f.questions, 0..) |*w, q, i| w.* = .{ + .question = try a.dupe(u8, q), + .answer = if (i < f.answers.len) try a.dupe(u8, f.answers[i]) else "", + .short = if (i < f.shorts.len) try a.dupe(u8, f.shorts[i]) else "", + .probe = i >= held, + .context = if (i < f.contexts.len) try a.dupe(u8, f.contexts[i]) else "", + }; + try out.append(a, .{ .id = f.id, .text = try a.dupe(u8, f.text), .asked = asked_, .recalled = f.recalled }); + } + return out.items; + } + + /// The reply a learned fact's question `i` brought it back with, kept as its answer when its lesson left none. + pub fn answered(g: *Graph, id: u32, i: usize, reply: []const u8) void { g.mutex.lockUncancelable(g.io); defer g.mutex.unlock(g.io); const f = g.find(id) orelse return; + if (i >= f.questions.len or (i < f.answers.len and f.answers[i].len > 0)) return; const a = g.arena.allocator(); - const out = a.alloc([]const u8, questions.len) catch return; - for (questions, out) |q, *o| o.* = a.dupe(u8, q) catch return; - f.questions = out; + if (f.answers.len != f.questions.len) { + const all = a.alloc([]const u8, f.questions.len) catch return; + for (all, 0..) |*x, j| x.* = if (j < f.answers.len) f.answers[j] else ""; + f.answers = all; + } + @constCast(f.answers)[i] = a.dupe(u8, reply) catch return; + g.save(); + } + + /// Conversation `name` as kept, copied into `a`; null when none is. + pub fn talk(g: *Graph, a: Allocator, name: []const u8) !?[]const [2][]const u8 { + g.mutex.lockUncancelable(g.io); + defer g.mutex.unlock(g.io); + for (g.talks.items) |t| if (std.mem.eql(u8, t.name, name)) { + const out = try a.alloc([2][]const u8, t.turns.len); + for (out, t.turns) |*o, x| o.* = .{ try a.dupe(u8, x[0]), try a.dupe(u8, x[1]) }; + return out; + }; + return null; + } + + /// Conversation `name` kept (copied) with the facts, for every later lesson and check to ask in. + pub fn keepTalk(g: *Graph, name: []const u8, turns: []const [2][]const u8) void { + g.mutex.lockUncancelable(g.io); + defer g.mutex.unlock(g.io); + const a = g.arena.allocator(); + const out = a.alloc([2][]const u8, turns.len) catch return; + for (out, turns) |*o, x| o.* = .{ a.dupe(u8, x[0]) catch return, a.dupe(u8, x[1]) catch return }; + g.talks.append(g.gpa, .{ .name = a.dupe(u8, name) catch return, .turns = out }) catch return; g.save(); } @@ -302,6 +391,10 @@ pub const Graph = struct { if (f.round > 0) try o.put(a, "round", try json.intValue(a, f.round)); if (f.message.len > 0) try o.put(a, "message", .{ .string = f.message }); if (f.questions.len > 0) try o.put(a, "questions", try strings(a, f.questions)); + if (f.answers.len > 0) try o.put(a, "answers", try strings(a, f.answers)); + if (f.shorts.len > 0) try o.put(a, "shorts", try strings(a, f.shorts)); + if (anyNonEmpty(f.contexts)) try o.put(a, "contexts", try strings(a, f.contexts)); + if (f.probes > 0) try o.put(a, "probes", try json.intValue(a, f.probes)); if (f.neurons.len > 0) try o.put(a, "neurons", try neuronList(a, f.neurons)); if (live) try g.liveFields(a, o, f); out.* = .{ .object = o }; @@ -309,6 +402,18 @@ pub const Graph = struct { const root = try json.newObject(a); try root.put(a, "next", try json.intValue(a, g.next)); try root.put(a, "facts", .{ .array = facts }); + if (g.talks.items.len > 0) { + const talks = try a.alloc(json.Value, g.talks.items.len); + for (g.talks.items, talks) |t, *v| { + const o = try json.newObject(a); + try o.put(a, "name", .{ .string = t.name }); + const ts = try a.alloc(json.Value, t.turns.len); + for (t.turns, ts) |x, *tv| tv.* = try strings(a, &x); + try o.put(a, "turns", .{ .array = ts }); + v.* = .{ .object = o }; + } + try root.put(a, "talks", .{ .array = talks }); + } if (live) if (g.model) |m| { const v = try slide_model.value(a, m); if (g.saved.state != .none) try v.object.put(a, "save", try saveValue(a, g.saved)); @@ -363,11 +468,11 @@ pub const Graph = struct { var fact: Fact = .{ .id = try int(u32, f.field("id")), .text = f.strField("text") orelse "", .source = f.strField("source") orelse "", .at = try int(i64, f.field("at")), .state = state }; fact.message = f.strField("message") orelse ""; fact.round = int(u32, f.field("round")) catch 0; - if (f.field("questions")) |qs| if (qs.items()) |xs| { - const out = try a.alloc([]const u8, xs.len); - for (xs, out) |x, *o| o.* = x.str() orelse ""; - fact.questions = out; - }; + fact.questions = try stringList(a, f.field("questions")); + fact.answers = try stringList(a, f.field("answers")); + fact.shorts = try stringList(a, f.field("shorts")); + fact.contexts = try stringList(a, f.field("contexts")); + fact.probes = int(u32, f.field("probes")) catch 0; if (f.field("neurons")) |ns| if (ns.items()) |xs| { var out: std.ArrayList(api.Neuron) = .empty; for (xs) |x| try out.append(a, .{ .layer = int(u16, x.field("layer")) catch continue, .neuron = int(u16, x.field("neuron")) catch continue, .key = std.meta.stringToEnum(api.NeuronKey, x.strField("key") orelse "") orelse continue }); @@ -375,6 +480,14 @@ pub const Graph = struct { }; try g.facts.append(g.gpa, fact); } + if (root.field("talks")) |ts| if (ts.items()) |xs| for (xs) |t| { + var turns: std.ArrayList([2][]const u8) = .empty; + for ((t.field("turns") orelse continue).items() orelse continue) |x| { + const pair = try stringList(a, x); + if (pair.len == 2) try turns.append(a, .{ pair[0], pair[1] }); + } + try g.talks.append(g.gpa, .{ .name = t.strField("name") orelse continue, .turns = turns.items }); + }; g.next = try int(u32, root.field("next")); } }; @@ -395,12 +508,25 @@ fn round4(x: f32) json.Value { return .{ .float = @round(v * 1e4) / 1e4 }; } +fn anyNonEmpty(xs: []const []const u8) bool { + for (xs) |x| if (x.len > 0) return true; + return false; +} + fn strings(a: Allocator, xs: []const []const u8) !json.Value { const out = try a.alloc(json.Value, xs.len); for (xs, out) |x, *v| v.* = .{ .string = x }; return .{ .array = out }; } +/// A JSON array of strings as read (none: empty). +fn stringList(a: Allocator, v: ?json.Value) ![]const []const u8 { + const xs = (v orelse return &.{}).items() orelse return &.{}; + const out = try a.alloc([]const u8, xs.len); + for (xs, out) |x, *o| o.* = x.str() orelse ""; + return out; +} + fn dupeAll(a: Allocator, xs: []const []const u8) ![]const []const u8 { const out = try a.alloc([]const u8, xs.len); for (xs, out) |x, *o| o.* = try a.dupe(u8, x); @@ -448,105 +574,3 @@ fn isCommon(w: []const u8) bool { for (common) |c| if (std.ascii.eqlIgnoreCase(w, c)) return true; return false; } - -test "facts persist across a reopen, link by a shared key word, and clear without reusing ids" { - const gpa = std.testing.allocator; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const path = try std.fs.path.join(gpa, &.{ ".zig-cache", "tmp", &tmp.sub_path, "graph.json" }); - defer gpa.free(path); - var g = Graph.init(gpa, io, path); - const a = g.add("My company, Larkspur Robotics, sells the Heron X2.", "file:company.md", 100); - const b = g.add("Larkspur Robotics made 4.7 million pounds in Q3.", "file:company.md", 101); - const c = g.add("My favourite colour is teal.", "chat", 102); - g.mark(a, .learned); - g.mark(c, .missed); - g.deinit(); - - var again = Graph.init(gpa, io, path); - defer again.deinit(); - try std.testing.expectEqual(@as(usize, 3), again.facts.items.len); - try std.testing.expectEqual(State.learned, again.facts.items[0].state); - try std.testing.expectEqual(State.missed, again.facts.items[2].state); - var arena = std.heap.ArenaAllocator.init(gpa); - defer arena.deinit(); - const doc = switch (try json.parse(arena.allocator(), try again.render(arena.allocator(), null))) { - .ok => |v| v, - .err => return error.BadGraph, - }; - const facts = doc.field("facts").?.items().?; - try std.testing.expectEqual(@as(usize, 1), facts[0].field("links").?.items().?.len); - try std.testing.expectEqualStrings(try std.fmt.allocPrint(arena.allocator(), "{d}", .{b}), facts[0].field("links").?.items().?[0].int); - try std.testing.expectEqual(@as(usize, 0), facts[2].field("links").?.items().?.len); - again.clear(); - try std.testing.expectEqual(c + 1, again.add("My dog is called Pickle.", "chat", 103)); -} - -test "a lesson's phases, loss trace and neurons show while it learns; a learned fact keeps its neurons on disk" { - const gpa = std.testing.allocator; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const path = try std.fs.path.join(gpa, &.{ ".zig-cache", "tmp", &tmp.sub_path, "graph.json" }); - defer gpa.free(path); - var arena = std.heap.ArenaAllocator.init(gpa); - defer arena.deinit(); - const ar = arena.allocator(); - var g = Graph.init(gpa, io, path); - const id = g.add("My sister is called Ana.", "chat", 100); - const other = g.add("I like blue.", "chat", 101); - g.mark(id, .learning); - g.phase(id, .writing); - g.asked(id, &.{ "What is my sister's name?", "Do you remember what my sister is called?" }); - g.round(id, 1); - g.progress(id, .{ .phase = .reading, .at = 3, .of = 40 }); - const ns = [_]api.Neuron{ .{ .layer = 13, .neuron = 0, .key = .subject }, .{ .layer = 15, .neuron = 2, .key = .subject } }; - for (1..4) |s| g.progress(id, .{ .phase = .values, .at = @intCast(s), .loss = 2.0 / @as(f32, @floatFromInt(s)), .neurons = &ns }); - g.round(id, 2); - for (1..3) |s| g.progress(id, .{ .phase = .values, .at = @intCast(s), .loss = 0.25, .neurons = &ns }); - g.checked(id, true); - var text = try g.render(ar, null); - try std.testing.expect(std.mem.indexOf(u8, text, "\"phase\":\"values\"") != null); - try std.testing.expect(std.mem.indexOf(u8, text, "\"trace\":[[2.0,1.0,0.6667],[0.25,0.25]]") != null); - try std.testing.expect(std.mem.indexOf(u8, text, "{\"layer\":13,\"neuron\":0,\"key\":\"subject\"}") != null); - try std.testing.expect(std.mem.indexOf(u8, text, "\"checks\":1,\"recalled\":true") != null); - g.mark(id, .learned); - g.placed(other, &ns); - g.mark(other, .missed); - text = try g.render(ar, null); - try std.testing.expect(std.mem.indexOf(u8, text, "\"phase\"") == null); - g.deinit(); - - var again = Graph.init(gpa, io, path); - defer again.deinit(); - try std.testing.expectEqual(@as(usize, 2), again.facts.items[0].neurons.len); - try std.testing.expectEqual(api.NeuronKey.subject, again.facts.items[0].neurons[1].key); - try std.testing.expectEqual(@as(u16, 15), again.facts.items[0].neurons[1].layer); - try std.testing.expectEqual(@as(usize, 2), again.facts.items[0].questions.len); - try std.testing.expectEqual(@as(u32, 2), again.facts.items[0].round); - try std.testing.expectEqual(@as(usize, 0), again.facts.items[1].neurons.len); -} - -test "a save is measured against the shards as they were before it: the files it changed, how long it took" { - const gpa = std.testing.allocator; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var arena = std.heap.ArenaAllocator.init(gpa); - defer arena.deinit(); - const ar = arena.allocator(); - const dir = try std.fs.path.join(ar, &.{ ".zig-cache", "tmp", &tmp.sub_path }); - try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = "{\"layers_block_type\": [\"mamba\", \"moe\"]}" }); - try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = "\x02\x00\x00\x00\x00\x00\x00\x00{}" }); - try tmp.dir.writeFile(io, .{ .sub_path = "other.safetensors", .data = "\x02\x00\x00\x00\x00\x00\x00\x00{}" }); - var g = Graph.init(gpa, io, null); - defer g.deinit(); - g.saving(dir); - try std.testing.expect(std.mem.indexOf(u8, try g.render(ar, dir), "\"save\":{\"state\":\"saving\"") != null); - try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = "\x03\x00\x00\x00\x00\x00\x00\x00{} " }); - g.saveEnded(dir, 3.14, null); - const text = try g.render(ar, dir); - try std.testing.expect(std.mem.indexOf(u8, text, "\"layers\":2,\"kinds\":\"ME\"") != null); - try std.testing.expect(std.mem.indexOf(u8, text, "\"seconds\":3.1,\"bytes\":0,\"files\":[\"model.safetensors\"]") != null); -} diff --git a/zig/src/server/slide_graph_test.zig b/zig/src/server/slide_graph_test.zig new file mode 100644 index 0000000000..485939c4d5 --- /dev/null +++ b/zig/src/server/slide_graph_test.zig @@ -0,0 +1,148 @@ +//! The tests of slide_graph.zig, beside it so the file stays under 600 lines. +const graph = @import("slide_graph.zig"); +const std = @import("std"); +const api = @import("engine_api"); +const json = @import("json.zig"); +const Graph = graph.Graph; +const State = graph.State; + +test "facts persist across a reopen, link by a shared key word, and clear without reusing ids" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try std.fs.path.join(gpa, &.{ ".zig-cache", "tmp", &tmp.sub_path, "graph.json" }); + defer gpa.free(path); + var g = Graph.init(gpa, io, path); + const a = g.add("My company, Larkspur Robotics, sells the Heron X2.", "file:company.md", 100); + const b = g.add("Larkspur Robotics made 4.7 million pounds in Q3.", "file:company.md", 101); + const c = g.add("My favourite colour is teal.", "chat", 102); + g.mark(a, .learned); + g.mark(c, .missed); + g.deinit(); + + var again = Graph.init(gpa, io, path); + defer again.deinit(); + try std.testing.expectEqual(@as(usize, 3), again.facts.items.len); + try std.testing.expectEqual(State.learned, again.facts.items[0].state); + try std.testing.expectEqual(State.missed, again.facts.items[2].state); + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const doc = switch (try json.parse(arena.allocator(), try again.render(arena.allocator(), null))) { + .ok => |v| v, + .err => return error.BadGraph, + }; + const facts = doc.field("facts").?.items().?; + try std.testing.expectEqual(@as(usize, 1), facts[0].field("links").?.items().?.len); + try std.testing.expectEqualStrings(try std.fmt.allocPrint(arena.allocator(), "{d}", .{b}), facts[0].field("links").?.items().?[0].int); + try std.testing.expectEqual(@as(usize, 0), facts[2].field("links").?.items().?.len); + again.clear(); + try std.testing.expectEqual(c + 1, again.add("My dog is called Pickle.", "chat", 103)); +} + +test "a wording's conversation and the conversations themselves persist across a reopen" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try std.fs.path.join(gpa, &.{ ".zig-cache", "tmp", &tmp.sub_path, "graph.json" }); + defer gpa.free(path); + var g = Graph.init(gpa, io, path); + const id = g.add("My name is Sam.", "chat", 100); + g.mark(id, .learned); + g.asked(id, &.{ .{ .question = "What is my name?", .answer = "Your name is Sam.", .short = "Sam" }, .{ .question = "What is my name?", .answer = "Your name is Sam.", .short = "Sam", .context = "check" } }); + g.keepTalk("check", &.{ .{ "Hi there.", "Hello! How can I help?" }, .{ "Tell me a joke.", "Why did the chicken cross the road?" } }); + g.deinit(); + + var again = Graph.init(gpa, io, path); + defer again.deinit(); + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const back = try again.earlier(a, 0); + try std.testing.expectEqualStrings("", back[0].asked[0].context); + try std.testing.expectEqualStrings("check", back[0].asked[1].context); + const talk = (try again.talk(a, "check")).?; + try std.testing.expectEqual(@as(usize, 2), talk.len); + try std.testing.expectEqualStrings("Why did the chicken cross the road?", talk[1][1]); + try std.testing.expect(try again.talk(a, "task") == null); +} + +test "a lesson's phases, loss trace and neurons show while it learns; a learned fact keeps its neurons on disk" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const path = try std.fs.path.join(gpa, &.{ ".zig-cache", "tmp", &tmp.sub_path, "graph.json" }); + defer gpa.free(path); + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const ar = arena.allocator(); + var g = Graph.init(gpa, io, path); + const id = g.add("My sister is called Ana.", "chat", 100); + const other = g.add("I like blue.", "chat", 101); + g.mark(id, .learning); + g.phase(id, .writing); + g.asked(id, &.{ .{ .question = "What is my sister's name?", .answer = "Your sister is called Ana.", .short = "Ana" }, .{ .question = "Do you remember what my sister is called?", .answer = "Yes, she is called Ana." }, .{ .question = "Who is my sister?", .probe = true } }); + g.round(id, 1); + g.progress(id, .{ .phase = .reading, .at = 3, .of = 40 }); + const ns = [_]api.Neuron{ .{ .layer = 13, .neuron = 0, .key = .subject }, .{ .layer = 15, .neuron = 2, .key = .subject } }; + for (1..4) |s| g.progress(id, .{ .phase = .values, .at = @intCast(s), .loss = 2.0 / @as(f32, @floatFromInt(s)), .neurons = &ns }); + g.round(id, 2); + for (1..3) |s| g.progress(id, .{ .phase = .values, .at = @intCast(s), .loss = 0.25, .neurons = &ns }); + g.checked(id, true); + var text = try g.render(ar, null); + try std.testing.expect(std.mem.indexOf(u8, text, "\"phase\":\"values\"") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "\"trace\":[[2.0,1.0,0.6667],[0.25,0.25]]") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "{\"layer\":13,\"neuron\":0,\"key\":\"subject\"}") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "\"checks\":1,\"recalled\":true") != null); + g.mark(id, .learned); + g.placed(other, &ns); + g.mark(other, .missed); + text = try g.render(ar, null); + try std.testing.expect(std.mem.indexOf(u8, text, "\"phase\"") == null); + g.deinit(); + + var again = Graph.init(gpa, io, path); + defer again.deinit(); + try std.testing.expectEqual(@as(usize, 2), again.facts.items[0].neurons.len); + try std.testing.expectEqual(api.NeuronKey.subject, again.facts.items[0].neurons[1].key); + try std.testing.expectEqual(@as(u16, 15), again.facts.items[0].neurons[1].layer); + try std.testing.expectEqual(@as(usize, 3), again.facts.items[0].questions.len); + try std.testing.expectEqualStrings("Ana", again.facts.items[0].shorts[0]); + try std.testing.expectEqual(@as(u32, 1), again.facts.items[0].probes); + // a later lesson checks the learned fact again on its wordings, the probe marked; a reply fills a missing answer + const back = try again.earlier(ar, 999); + try std.testing.expectEqual(@as(usize, 1), back.len); + try std.testing.expectEqual(id, back[0].id); + try std.testing.expect(back[0].asked[2].probe and !back[0].asked[1].probe); + try std.testing.expectEqualStrings("Yes, she is called Ana.", back[0].asked[1].answer); + again.answered(id, 2, "Your sister Ana."); + try std.testing.expectEqualStrings("Your sister Ana.", again.facts.items[0].answers[2]); + try std.testing.expectEqual(@as(usize, 0), (try again.earlier(ar, id)).len); + try std.testing.expectEqual(@as(u32, 2), again.facts.items[0].round); + try std.testing.expectEqual(@as(usize, 0), again.facts.items[1].neurons.len); +} + +test "a save is measured against the shards as they were before it: the files it changed, how long it took" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const ar = arena.allocator(); + const dir = try std.fs.path.join(ar, &.{ ".zig-cache", "tmp", &tmp.sub_path }); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = "{\"layers_block_type\": [\"mamba\", \"moe\"]}" }); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = "\x02\x00\x00\x00\x00\x00\x00\x00{}" }); + try tmp.dir.writeFile(io, .{ .sub_path = "other.safetensors", .data = "\x02\x00\x00\x00\x00\x00\x00\x00{}" }); + var g = Graph.init(gpa, io, null); + defer g.deinit(); + g.saving(dir); + try std.testing.expect(std.mem.indexOf(u8, try g.render(ar, dir), "\"save\":{\"state\":\"saving\"") != null); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = "\x03\x00\x00\x00\x00\x00\x00\x00{} " }); + g.saveEnded(dir, 3.14, null); + const text = try g.render(ar, dir); + try std.testing.expect(std.mem.indexOf(u8, text, "\"layers\":2,\"kinds\":\"ME\"") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "\"seconds\":3.1,\"bytes\":0,\"files\":[\"model.safetensors\"]") != null); +} diff --git a/zig/src/server/slide_known.zig b/zig/src/server/slide_known.zig new file mode 100644 index 0000000000..f31c4a37e6 --- /dev/null +++ b/zig/src/server/slide_known.zig @@ -0,0 +1,82 @@ +//! Replies a lesson's writer and checks got, kept with their tokens. +const std = @import("std"); +const chat = @import("chat.zig"); + +/// A kept reply: its prompt's tokens, its own (an end token included), and its text. +pub const Entry = struct { + prompt: []const u32, + tokens: []const u32, + content: []const u8, + finish: []const u8, + + /// The kept reply as `ask` returns it. + pub fn asReply(e: Entry) chat.Reply { + return .{ .content = e.content, .stop_sequence = null, .reasoning = null, .tool_calls_streamed = false, .finish_reason = e.finish, .prompt_tokens = e.prompt.len, .cached_tokens = 0, .completion_tokens = e.tokens.len, .reasoning_tokens = 0, .runtime = .null, .speculative = .null, .prompt_ids = e.prompt, .tokens = e.tokens }; + } +}; + +pub const Known = struct { + arena: std.heap.ArenaAllocator, + mutex: std.Io.Mutex = .init, + map: std.AutoHashMapUnmanaged(u64, Entry) = .empty, + // counts over the server's life: kept replies scored, found unchanged, generated anyway + scored: usize = 0, + same: usize = 0, + + pub fn init(gpa: std.mem.Allocator) Known { + return .{ .arena = .init(gpa) }; + } + + pub fn deinit(k: *Known) void { + k.map.deinit(k.arena.child_allocator); + k.arena.deinit(); + } + + /// The reply kept at `at`, if any (its slices live as long as the store). + pub fn get(k: *Known, io: std.Io, at: u64) ?Entry { + k.mutex.lockUncancelable(io); + defer k.mutex.unlock(io); + return k.map.get(at); + } + + /// Keep `reply` at `at` (a key): a greedy reply that ended at its end token or its length, with its tokens. + pub fn remember(k: *Known, io: std.Io, at: u64, reply: chat.Reply) void { + if (reply.prompt_ids.len == 0 or reply.tokens.len == 0 or reply.stop_sequence != null or reply.thinking) return; + const stop = std.mem.eql(u8, reply.finish_reason, "stop"); + if (!stop and !std.mem.eql(u8, reply.finish_reason, "length")) return; + k.mutex.lockUncancelable(io); + defer k.mutex.unlock(io); + const a = k.arena.allocator(); + const e: Entry = .{ + .prompt = a.dupe(u32, reply.prompt_ids) catch return, + .tokens = a.dupe(u32, reply.tokens) catch return, + .content = a.dupe(u8, reply.content) catch return, + .finish = if (stop) "stop" else "length", + }; + k.map.put(k.arena.child_allocator, at, e) catch {}; + } +}; + +/// A greedy question without thinking as one number: its system note, the conversation before it, it, its length. +pub fn key(system: ?[]const u8, before: []const [2][]const u8, question: []const u8, max_tokens: i64) u64 { + var h = std.hash.Wyhash.init(0x51de); + h.update(if (system) |s| s else "\x00none"); + h.update("\x00"); + for (before) |t| { + h.update(t[0]); + h.update("\x00"); + h.update(t[1]); + h.update("\x00"); + } + h.update(question); + h.update(std.mem.asBytes(&max_tokens)); + return h.final(); +} + +test "a question's key holds its system note, its conversation and its length" { + const q = "What is my name?"; + try std.testing.expect(key(null, &.{}, q, 32) != key(null, &.{}, q, 48)); + try std.testing.expect(key(null, &.{}, q, 32) != key("note", &.{}, q, 32)); + try std.testing.expect(key(null, &.{.{ "hi", "hello" }}, q, 32) != key(null, &.{}, q, 32)); + try std.testing.expectEqual(key(null, &.{}, q, 32), key(null, &.{}, q, 32)); +} diff --git a/zig/src/server/slide_lesson.zig b/zig/src/server/slide_lesson.zig index fbcb5eb609..10e99d8aa1 100644 --- a/zig/src/server/slide_lesson.zig +++ b/zig/src/server/slide_lesson.zig @@ -48,24 +48,37 @@ const kindsOf = slide_subject.kindsOf; const kindsList = slide_subject.kindsList; const slide_teacher = @import("slide_teacher.zig"); pub const Teacher = slide_teacher.Teacher; +pub const About = wording.About; const local = slide_teacher.local; const keepExamples = slide_teacher.keepExamples; +const broadExamples = slide_teacher.broadExamples; +const keep_tokens = slide_teacher.keep_tokens; const bankAnswers = slide_teacher.bankAnswers; const thinks = slide_teacher.thinks; const turnEnd = slide_teacher.turnEnd; const slide_pick = @import("slide_pick.zig"); +const talks = @import("slide_context.zig"); +const slide_router = @import("slide_router.zig"); +const heldBack = slide_router.heldBack; +const routerData = slide_router.routerData; +const conversations = slide_router.conversations; +const questionsFor = slide_router.questionsFor; +const replay = slide_router.replay; +const asksWho = slide_router.asksWho; +const aboutEntity = slide_router.aboutEntity; +const answered = slide_router.answered; const Unseen = slide_pick.Unseen; const heldPair = slide_pick.heldPair; const dice = slide_pick.dice; const swapped = 2; // a fact's questions whose subject is swapped for others of its kind, kept as the model answers them -const others = [_][]const u8{ "sister", "brother", "mother", "friend" }; // whom a fact's questions are also asked about +pub const others = [_][]const u8{ "sister", "brother", "mother", "friend" }; // whom a fact's questions are also asked about const probes = 12; -const extra_wordings = 12; // more of a fact's questions asked for, read by its router only (each judged first) -const probe_count = 4; // of those, asked after each round to see the lesson answers wordings it never learned -const wording_temperature = 0.9; // the extra wordings are sampled, so they differ from the greedy first list -const max_others = 96; // its questions asked about others, read by its router only +pub const extra_wordings = 12; // more of a fact's questions asked for, read by its router only (each judged first) +pub const probe_count = 4; // of those, asked after each round to see the lesson answers wordings it never learned +pub const wording_temperature = 0.9; // the extra wordings are sampled, so they differ from the greedy first list +pub const max_others = 96; // its questions asked about others, read by its router only const besides = 6; // questions about the fact's subject that it leaves unanswered, kept as the model answers them const other_values = 4; // yes-or-no questions naming another value than a told fact's, learned with its answers const neighbours = 4; // a document fact's questions for the same kind of answer about another of its subject's things @@ -73,20 +86,26 @@ const think_twins = 12; // near misses also kept with their thinking replies (ea const remember_probes = 4; // kept questions asked again as "Do you remember...?", which the model otherwise refuses pub const min_probes = 3; // two answers are held out to test recall const want_probes = 12; // questions a fact is learned from at least, when the model gives that many -const replayed = 24; // earlier answers about a subject a document lesson keeps at most, the latest first +pub const replayed = 24; // earlier answers about a subject a document lesson keeps at most, the latest first +pub const talk_questions = 6; // a fact's questions also asked after each conversation it learns in (talks.learned) +pub const talk_near = 4; // and its near misses there, which its neurons stay silent on +const talk_personal = 2; // and questions about the user no fact answers, likewise +pub const talk_answers = 3; // its answers also learned after the conversations short enough for the trainer's passes +pub const talk_rows = 512; // a conversation's answer the trainer reads whole at most (its passes' longest sequence) -const personal_checks = 3; +pub const personal_checks = 3; const bank_checks = 6; // one bank question in this many is held back from each lesson to check pub const check_tokens = 32; // a check's reply read before and after a lesson +pub const drift_tokens = 64; // a drift check's reply (slide_prompts.drift_checks), compared token for token /// A question about something else and the model's answer before the lesson. pub const Check = struct { question: []const u8, before: []const u8, thinking: []const u8 = "", invents: bool = false }; // invents: an untold check /// A held-out question, the answer the model wrote for it from its fact, and which fact. -pub const Held = struct { question: []const u8, answer: []const u8, fact: usize, subject: []const u8 = "", short: []const u8 = "" }; // subject: the word an edit keys on; short: the fewest words that answer it +pub const Held = struct { question: []const u8, answer: []const u8, fact: usize, subject: []const u8 = "", short: []const u8 = "", context: []const u8 = "" }; // subject: the word an edit keys on; short: the fewest words that answer it; context: the conversation it is asked after (slide_context.zig) /// A lesson for the learner, its facts, and what to ask after it; `probes` are wordings it never trains on. -pub const Plan = struct { full: api.LearnRequest, facts: []const []const u8, held: []const Held, probes: []const Held = &.{}, checks: []const Check, thinks: bool = false, document: bool = false, stale: slide_teacher.Stale = .{} }; +pub const Plan = struct { full: api.LearnRequest, facts: []const []const u8, held: []const Held, probes: []const Held = &.{}, checks: []const Check, drifts: []const Check = &.{}, thinks: bool = false, document: bool = false, stale: slide_teacher.Stale = .{}, selves: []const bool = &.{} }; // selves[f]: fact f is about the model; drifts: replies to unrelated prompts no round may change /// A lesson's rounds: steps each for every fact (at most max_round_steps), stopping once every fact comes back. pub const round_steps = 20; @@ -101,24 +120,54 @@ pub fn routed(srv: *Server, cx: *Cx, c: Check) !struct { prompt: api.Example, ke } /// One lesson for the facts `told` (kept[f]: fact f had enough clean answers), or null; `siblings`: all facts told. -pub fn lesson(srv: *Server, cx: *Cx, teacher: *Teacher, told: []const []const u8, kept: []bool, document: bool, siblings: []const []const u8, gone: anytype) !?Plan { +pub fn lesson(srv: *Server, cx: *Cx, teacher: *Teacher, told: []const []const u8, kept: []bool, document: bool, about: ?wording.About, siblings: []const []const u8, gone: anytype) !?Plan { const a = cx.a; const end = try turnEnd(srv, cx, teacher); - var parts: Parts = .{ .thinks = try thinks(srv, cx, teacher), .document = document, .siblings = siblings }; + var parts: Parts = .{ .thinks = try thinks(srv, cx, teacher), .document = document, .siblings = siblings, .about = about }; var count: u32 = 0; const language = try languageOf(srv, cx, told[0], gone); + // the conversations a fact's questions are learned in, written side by side before the facts' lessons read them + if (!document) try talks.prewrite(srv, cx, &talks.learned, gone); for (told, kept, 0..) |fact, *k, f| { k.* = try factLesson(srv, cx, &parts, fact, f, end, language, gone); count += @intFromBool(k.*); } if (count == 0) return null; + const selves = parts.selves.items; + const any_self = std.mem.indexOfScalar(bool, selves, true) != null; // what the change must never touch: questions about the user and prompts of every kind, as the model answers them var keep: std.ArrayList(api.Example) = .empty; var checks: std.ArrayList(Check) = .empty; teacher.lessons += 1; + // the facts learned before: a written-once answer one of them may have changed is asked again as the model gives. + var learned: std.ArrayList([]const u8) = .empty; + for (try srv.slide.earlier(a, 0)) |e| try learned.append(a, e.text); + var free: std.ArrayList([]const u8) = .empty; // questions about the user no fact of the lesson answers + // the questions about the user no fact of the lesson answers (personal, untold checked, untold kept). + var personal: std.ArrayList(usize) = .empty; + var about_user: std.ArrayList(side.Asking) = .empty; for (prompts.personal_prompts, 0..) |q, i| { - if (try answeredByAny(srv, cx, told, kept, parts.own.items, q, document, gone)) continue; - const reply = try ask(srv, cx, null, q, check_tokens, gone); + if (try answeredByAny(srv, cx, told, kept, selves, parts.own.items, q, document, gone)) continue; + try free.append(a, q); + try personal.append(a, i); + try about_user.append(a, .{ .question = q, .max = check_tokens }); + } + // questions about the user no lesson told: a self fact never answers them (secondPerson), "My name is Sam." does + var untold_checked: std.ArrayList([]const u8) = .empty; + for (untold.checked) |q| { + if (try answeredByAny(srv, cx, told, kept, selves, parts.own.items, q, document, gone)) continue; + try untold_checked.append(a, q); + try about_user.append(a, .{ .question = q, .max = check_tokens }); + } + var untold_kept: std.ArrayList([]const u8) = .empty; + for (untold.kept) |q| { + if (try answeredByAny(srv, cx, told, kept, selves, parts.own.items, q, document, gone)) continue; + try untold_kept.append(a, q); + try about_user.append(a, .{ .question = q, .max = check_tokens }); + } + const replies = try side.askAll(srv, cx, about_user.items, gone); + for (personal.items, replies[0..personal.items.len]) |i, reply| { + const q = prompts.personal_prompts[i]; if (heldBack(teacher.lessons, i)) { try checks.append(a, .{ .question = q, .before = reply.content }); continue; @@ -126,41 +175,66 @@ pub fn lesson(srv: *Server, cx: *Cx, teacher: *Teacher, told: []const []const u8 try keep.append(a, try example(srv, cx, a, null, q, reply.content, ending(reply, end))); if (parts.thinks) if (try thinkingSteady(srv, cx, a, q, gone)) |ex| try parts.think_keep.append(a, ex); } - for (untold.checked) |q| { - if (try answeredByAny(srv, cx, told, kept, parts.own.items, q, document, gone)) continue; - const reply = try ask(srv, cx, null, q, check_tokens, gone); - try checks.append(a, .{ .question = q, .before = reply.content, .invents = true }); + var at = personal.items.len; + for (untold_checked.items) |q| { + try checks.append(a, .{ .question = q, .before = replies[at].content, .invents = true }); + at += 1; } - for (untold.kept) |q| { - if (try answeredByAny(srv, cx, told, kept, parts.own.items, q, document, gone)) continue; - const reply = try ask(srv, cx, null, q, check_tokens, gone); - try keep.append(a, try example(srv, cx, a, null, q, reply.content, ending(reply, end))); + for (untold_kept.items) |q| { + try keep.append(a, try example(srv, cx, a, null, q, replies[at].content, ending(replies[at], end))); + at += 1; } const kept_answers = try keepExamples(srv, cx, teacher, end, parts.thinks, gone); - var stale_keep: std.ArrayList(usize) = .empty; + var stale_keep: std.ArrayList(usize) = .empty; // the written-once answers this lesson's fact answers: read again once it is learned var stale_bank: std.ArrayList(usize) = .empty; + var keep_fresh: std.ArrayList(side.Asking) = .empty; // keep prompts an earlier fact may answer, asked again now for (prompts.keep_prompts, 0..) |q, i| { - if (!wording.toModel(q) and try answeredByAny(srv, cx, told, kept, parts.own.items, q, document, gone)) { + // a question to the model is never a fact about the user's, but may be one about the model's + if ((any_self or !wording.toModel(q)) and try answeredByAny(srv, cx, told, kept, selves, parts.own.items, q, document, gone)) { try stale_keep.append(a, i); continue; } + if (stale(learned.items, q)) { + try keep_fresh.append(a, .{ .question = q, .max = keep_tokens }); + continue; + } try keep.append(a, kept_answers[i]); if (kept_answers.len > prompts.keep_prompts.len) try parts.think_keep.append(a, kept_answers[prompts.keep_prompts.len + i]); } + // prompts of kinds no keep prompt is (math, code, verse, other scripts), their longer answers held the same way + try keep.appendSlice(a, try broadExamples(srv, cx, teacher, end, gone)); // a document's earlier facts about this subject keep their answers: a later fact must not overwrite them if (document) try replay(srv, cx, teacher, told[0], end, &keep); // the personal bank: kept as first answered, some held back to check, except what a fact answers + var bank_fresh: std.ArrayList(side.Asking) = .empty; + var bank_held: std.ArrayList(bool) = .empty; // each asked again: held back to check, else kept for (try bankAnswers(srv, cx, teacher, end, gone), 0..) |b, i| { - if (try answeredByAny(srv, cx, told, kept, parts.own.items, b.question, document, gone)) { + if (try answeredByAny(srv, cx, told, kept, selves, parts.own.items, b.question, document, gone)) { try stale_bank.append(a, i); continue; } - if ((i + teacher.lessons) % bank_checks == 0) try checks.append(a, .{ .question = b.question, .before = b.before }) else try keep.append(a, b.ex); + const held = (i + teacher.lessons) % bank_checks == 0; + if (stale(learned.items, b.question)) { + try bank_fresh.append(a, .{ .question = b.question, .max = check_tokens }); + try bank_held.append(a, held); + continue; + } + if (held) try checks.append(a, .{ .question = b.question, .before = b.before }) else try keep.append(a, b.ex); } + // the answers written once before a fact learned since changed them: as the model gives them now, side by side + const fresh = try side.askAll(srv, cx, try std.mem.concat(a, side.Asking, &.{ keep_fresh.items, bank_fresh.items }), gone); + for (keep_fresh.items, fresh[0..keep_fresh.items.len]) |k, reply| { + try keep.append(a, try example(srv, cx, a, null, k.question, reply.content, ending(reply, end))); + if (parts.thinks) if (try thinkingSteady(srv, cx, a, k.question, gone)) |ex| try parts.think_keep.append(a, ex); + } + for (bank_fresh.items, bank_held.items, fresh[keep_fresh.items.len..]) |b, held, reply| { + if (held) try checks.append(a, .{ .question = b.question, .before = reply.content }) else try keep.append(a, try example(srv, cx, a, null, b.question, reply.content, ending(reply, end))); + } + if (fresh.len > 0) log.line("slide: {d} answers written before asked again, as facts learned since may have changed them", .{fresh.len}); // a fact in another language: its own language's prompts held and checked as the English ones are if (if (language) |name| try local(srv, cx, teacher, name, end, gone) else null) |l| { for (l.personal, 0..) |q, i| { - if (try answeredByAny(srv, cx, told, kept, parts.own.items, q, document, gone)) continue; + if (try answeredByAny(srv, cx, told, kept, selves, parts.own.items, q, document, gone)) continue; const reply = try ask(srv, cx, null, q, check_tokens, gone); if (heldBack(teacher.lessons, i)) { try checks.append(a, .{ .question = q, .before = reply.content }); @@ -172,6 +246,12 @@ pub fn lesson(srv: *Server, cx: *Cx, teacher: *Teacher, told: []const []const u8 try parts.unasked.append(a, try slide_ask.promptOnly(srv, cx, a, null, q)); try parts.unasked.append(a, try slide_ask.promptOnly(srv, cx, a, prompts.systems[i % prompts.systems.len], q)); } + // questions about the user no fact answers stay unanswered in a conversation too + if (!document and free.items.len > 0) for (talks.learned, 0..) |name, c| { + const before = try talks.turns(srv, cx, name, gone); + if (before.len == 0) continue; + for (0..talk_personal) |k| try parts.unasked.append(a, try talks.promptIn(srv, cx, a, before, free.items[(c * talk_personal + k) % free.items.len])); + }; // the near misses set aside, never trained on, check that the fact stays put try checks.appendSlice(a, parts.aside.items); log.line("slide: {d} near misses trained on, {d} set aside to check", .{ parts.near.items.len, parts.aside.items.len }); @@ -193,11 +273,19 @@ pub fn lesson(srv: *Server, cx: *Cx, teacher: *Teacher, told: []const []const u8 .unasked = parts.unasked.items, .steps = steps, }; - return .{ .full = full, .facts = told, .held = parts.held.items, .probes = parts.probes.items, .checks = checks.items, .thinks = parts.thinks, .document = document, .stale = .{ .keep = stale_keep.items, .bank = stale_bank.items } }; + // replies to unrelated prompts as the model gives them before this lesson. + var drifts: std.ArrayList(Check) = .empty; + const drifting = if (std.c.getenv("TF_SLIDE_DRIFT")) |v| !std.mem.eql(u8, std.mem.span(v), "off") else true; + if (drifting) { + var asking: [prompts.drift_checks.len]side.Asking = undefined; + for (&asking, prompts.drift_checks) |*x, q| x.* = .{ .question = q, .max = drift_tokens }; + for (prompts.drift_checks, try side.askAll(srv, cx, &asking, gone)) |q, reply| try drifts.append(a, .{ .question = q, .before = reply.content }); + } + return .{ .full = full, .facts = told, .held = parts.held.items, .probes = parts.probes.items, .checks = checks.items, .drifts = drifts.items, .thinks = parts.thinks, .document = document, .stale = .{ .keep = stale_keep.items, .bank = stale_bank.items }, .selves = selves }; } /// The facts' examples as a lesson gathers them. -const Parts = struct { +pub const Parts = struct { train: std.ArrayList(api.Example) = .empty, held_ex: std.ArrayList(api.Example) = .empty, held: std.ArrayList(Held) = .empty, @@ -217,6 +305,9 @@ const Parts = struct { words: []const []const u8 = &.{}, // the open fact's subject words (none: it is about the user) named: []const []const u8 = &.{}, // of those, the ones a question must say to name it siblings: []const []const u8 = &.{}, // every fact told with these, whose questions are theirs to answer + about: ?wording.About = null, // whom the user said the facts are about (null: judged for each) + self: bool = false, // the open fact is about the model itself: asked of the model, answered as itself + selves: std.ArrayList(bool) = .empty, // each fact's: whether it is about the model own: std.ArrayList([]const u8) = .empty, // the facts' kept questions: none is also checked or kept as it was }; @@ -260,7 +351,7 @@ fn keepNear(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, nears: []con var jcx: Cx = .{ .a = j.a }; const n = j.nears[i]; if (untold.protected(n.q)) return; // only ever checked, never trained - if (n.judge and try answered(j.srv, &jcx, j.fact, n.q, j.parts.document, j.gone)) return; + if (n.judge and try answered(j.srv, &jcx, j.fact, n.q, j.parts.document, j.parts.self, j.gone)) return; if (n.siblings and try siblingAnswers(j.srv, &jcx, j.parts.siblings, j.fact, n.q, j.parts.document, j.gone)) { j.out[i].sibling = true; return; @@ -309,9 +400,13 @@ fn keepNear(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, nears: []con /// One fact's part: its questions and answers (two held out), and twins about other things as the model answers them. fn factLesson(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, f: usize, end: []const u32, language: ?[]const u8, gone: anytype) !bool { const a = cx.a; - const asked = try askBase(srv, cx, null, try questionsFor(a, parts.document, fact, probes, language), 32 * probes, gone); + // a fact the user tells the model about itself is asked of the model and answered as itself, keyed on the reply + const self = !parts.document and (if (parts.about) |w| w == .self else try aboutSelf(srv, cx, fact, gone)); + parts.self = self; + try parts.selves.append(a, self); + const asked = try askBase(srv, cx, null, try questionsFor(a, parts.document, self, fact, probes, language), 32 * probes, gone); const qs = try wording.questions(a, asked.content, probes); - var got: Got = .{ .entity = try aboutEntity(srv, cx, fact, gone), .siblings = parts.siblings }; + var got: Got = .{ .entity = !self and try aboutEntity(srv, cx, fact, gone), .self = self, .siblings = parts.siblings }; var phrase: []const u8 = ""; if (got.entity) { const said = try askBase(srv, cx, null, try std.fmt.allocPrint(a, prompts.fact_subject_prompt, .{fact}), 16, gone); @@ -320,10 +415,18 @@ fn factLesson(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, f: usize, got.named = try slide_subject.named(a, got.words, fact, qs); log.line("slide: its subject is \"{s}\": {s} (a question names it by {s})", .{ phrase, try std.mem.join(a, " ", got.words), try std.mem.join(a, " or ", if (got.named.len > 0) got.named else got.words) }); if (got.words.len == 0) got.entity = false; + // a told fact's subject most of its questions do not name. + const why = if (got.entity and !parts.document) slide_subject.unkeyedBy(phrase, got.words, got.named, qs) else null; + if (why) |w| { + log.line("slide: its subject \"{s}\" {s}, so it keys on the reply", .{ phrase, w }); + got.entity = false; + got.words = &.{}; + got.named = &.{}; + } } parts.words = got.words; parts.named = got.named; - log.line("slide: \"{s}\" is about {s}", .{ fact, if (got.entity) "someone or something in particular, so its questions key on that subject" else "the user, so its questions key on the reply" }); + log.line("slide: \"{s}\" is about {s}", .{ fact, if (got.entity) "someone or something in particular, so its questions key on that subject" else if (self) "the model itself, so its questions ask the model about itself and key on the reply" else "the user, so its questions key on the reply" }); try take(srv, cx, &got, fact, f, qs, end, parts.thinks, parts.document, gone); // too few kept: ask again, sampled, up to twice; a fact reaches unseen wordings only when learned from many const naming = if (parts.document and got.entity and language == null) try std.mem.join(a, " ", if (got.named.len > 0) got.named else got.words) else ""; @@ -344,28 +447,28 @@ fn factLesson(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, f: usize, } } // a document's fact asked for by name: its first list asked for the subject, or about another fact told with it - const ask_for = if (naming.len > 0) try std.fmt.allocPrint(a, prompts.named_questions_prompt, .{ fact, count, naming, naming, count }) else try questionsFor(a, parts.document, fact, count, language); + const ask_for = if (naming.len > 0) try std.fmt.allocPrint(a, prompts.named_questions_prompt, .{ fact, count, naming, naming, count }) else try questionsFor(a, parts.document, self, fact, count, language); const again = try slide_ask.askBaseAt(srv, cx, null, ask_for, 32 * @as(i64, @intCast(count)), wording_temperature, gone); try take(srv, cx, &got, fact, f, try wording.questions(a, again.content, count), end, parts.thinks, parts.document, gone); } - // "Do I like blue?" (no) and the list's own "Do I like red?" (yes) learned as the model answers knowing the fact + // "Do I like blue?" (no) and the list's own "Do I like red?" (yes) learned as the model answers knowing the fact. if (!parts.document and language == null) { - const asked_other = try askBase(srv, cx, null, try std.fmt.allocPrint(a, prompts.other_values_prompt, .{ fact, other_values, other_values }), 32 * other_values, gone); + const asked_other = try askBase(srv, cx, null, try (if (self) std.fmt.allocPrint(a, prompts.self_other_values_prompt, .{ fact, other_values, other_values }) else std.fmt.allocPrint(a, prompts.other_values_prompt, .{ fact, other_values, other_values })), 32 * other_values, gone); var built: std.ArrayList([]const u8) = .empty; try built.appendSlice(a, try wording.questions(a, asked_other.content, other_values)); - for (qs) |q| if (wording.yesNo(q) and wording.tells(fact, "", "", q)) try built.append(a, q); + for (qs) |q| if (wording.asksYesNo(q, self) and wording.tells(fact, "", "", q)) try built.append(a, q); got.unjudged = true; try take(srv, cx, &got, fact, f, built.items, end, parts.thinks, parts.document, gone); got.unjudged = false; } - // the kept questions asked again as "Do you remember...?", which the model otherwise refuses + // the kept questions asked again as "Do you remember...?", which the model otherwise refuses. var plain: std.ArrayList(u8) = .empty; for (got.refs.items[0..@min(got.refs.items.len, remember_probes)], 1..) |r, i| try plain.print(a, "{d}. {s}\n", .{ i, r.question }); - if (plain.items.len > 0 and !parts.document) { + if (plain.items.len > 0 and !parts.document and !self) { const again = try askBase(srv, cx, null, try prompted(a, prompts.remember_prompt, remember_other, .{plain.items}, language), 32 * remember_probes, gone); var mine: std.ArrayList([]const u8) = .empty; for (try wording.questions(a, again.content, remember_probes)) |q| { - if (wording.firstPerson(q)) try mine.append(a, q) else log.line("slide: \"{s}\" is no longer the user's question, so it is dropped", .{q}); + if (wording.asksOf(q, false)) try mine.append(a, q) else log.line("slide: \"{s}\" is no longer the user's question, so it is dropped", .{q}); } try take(srv, cx, &got, fact, f, mine.items, end, parts.thinks, parts.document, gone); } @@ -398,6 +501,12 @@ fn factLesson(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, f: usize, thought += @intFromBool(think != null); if (held) try parts.held.append(a, r); } + // the held-out questions also checked after conversations the lesson never learns in. + for (pair, talks.checked) |i, name| { + var h = refs.items[i]; + h.context = name; + try parts.held.append(a, h); + } // each answer also learned under client system messages and after an unrelated exchange (ROME's prefixes) for (pairs.items, refs.items, 0..) |ex, r, i| { if (i == pair[0] or i == pair[1]) continue; @@ -416,9 +525,10 @@ fn factLesson(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, f: usize, if (!wording.gives(fact, asked_all, answered_all, twin)) try nears.append(a, .{ .q = twin, .judge = true }); }; const others_about: usize = if (got.entity) 2 * besides else besides; - const asked_besides = try askBase(srv, cx, null, try prompted(a, prompts.besides_prompt, besides_other, .{ fact, others_about }, language), 32 * @as(i64, @intCast(others_about)), gone); + const besides_for = if (self) try std.fmt.allocPrint(a, prompts.self_besides_prompt, .{ fact, others_about }) else try prompted(a, prompts.besides_prompt, besides_other, .{ fact, others_about }, language); + const asked_besides = try askBase(srv, cx, null, besides_for, 32 * @as(i64, @intCast(others_about)), gone); for (try wording.questions(a, asked_besides.content, others_about)) |q| { - if ((!parts.document and !wording.firstPerson(q)) or wording.gives(fact, asked_all, answered_all, q)) continue; + if ((!parts.document and !slide_take.whose(fact, q, self)) or wording.gives(fact, asked_all, answered_all, q)) continue; try nears.append(a, .{ .q = q, .judge = true, .siblings = true }); } // the same kind of answer about the subject's other things stays as answered now: sick leave is not annual leave @@ -440,99 +550,22 @@ fn factLesson(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, f: usize, if (got.entity and parts.document and language == null and phrase.len > 0) inline for (prompts.writing) |t| { try nears.append(a, .{ .q = try std.fmt.allocPrint(a, t, .{phrase}), .train = true }); }; - for (refs.items) |r| if (try wording.addressed(a, r.question)) |own| try nears.append(a, .{ .q = own }); + // a question about the user asked of the model (my as your), or one to the model asked of the user (your as my) + for (refs.items) |r| if (if (self) try wording.asUser(a, r.question) else try wording.addressed(a, r.question)) |own| try nears.append(a, .{ .q = own }); if (!got.entity) for (refs.items, 0..) |r, i| for ([_]usize{ i, i + 1 }) |j| { - const other = try wording.about(a, r.question, others[j % others.len]) orelse continue; + const mine = if (self) try wording.asUser(a, r.question) orelse continue else r.question; + const other = try wording.about(a, mine, others[j % others.len]) orelse continue; if (!wording.gives(fact, asked_all, answered_all, other)) try nears.append(a, .{ .q = other }); }; const kept = try keepNear(srv, cx, parts, fact, nears.items, end, gone); log.line("slide: near misses kept steady: {s}", .{try std.mem.join(a, " | ", kept)}); try routerData(srv, cx, parts, fact, f, refs.items, subjects.items, kept, asked_all, answered_all, language, gone); + try conversations(srv, cx, parts, refs.items, pairs.items, pair, kept, gone); return true; } -/// More of the fact's questions (judged as `take` judges them) and its questions asked about others, prompts only. -fn routerData(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, f: usize, refs: []const Held, subjects: []const ?[]const u8, near_questions: []const []const u8, asked_all: []const u8, answered_all: []const u8, language: ?[]const u8, gone: anytype) !void { - const a = cx.a; - var seen: std.StringHashMapUnmanaged(void) = .empty; - for (refs) |r| try seen.put(a, r.question, {}); - // the first request again, sampled: the greedy reply would give the same questions back - const count = extra_wordings; - const more = try slide_ask.askBaseAt(srv, cx, null, try questionsFor(a, parts.document, fact, count, language), 32 * count, wording_temperature, gone); - var taken: usize = 0; - var unseen: std.ArrayList(Unseen) = .empty; // wordings never learned, the most typical of them checked after a round - const wordings = try wording.questions(a, more.content, count); - if (wordings.len == 0) log.line("slide: no more wordings came back: {s}", .{more.content}); - for (wordings) |q| { - if ((try seen.getOrPut(a, q)).found_existing) continue; - const personal = !parts.document and (!wording.firstPerson(q) or wording.someoneElse(fact, q)); - const why: ?[]const u8 = if (personal or !units.sameScript(fact, q)) "is not the user asking about themselves" else if (wording.gives(fact, asked_all, answered_all, q)) "gives the fact away" else if (!try judged(srv, cx, fact, q, parts.document, gone)) "is not answered by the fact" else if (try siblingAnswers(srv, cx, parts.siblings, fact, q, parts.document, gone)) "is another fact's" else null; - if (why) |w| { - // a wording about the model or someone else is still one the lesson must not take - const other = !parts.document and !wording.firstPerson(q) and units.sameScript(fact, q) and !wording.gives(fact, asked_all, answered_all, q); - if (other) try parts.unasked.append(a, try slide_ask.promptOnly(srv, cx, a, null, q)); - log.line("slide: \"{s}\" {s}, so its router {s}", .{ q, w, if (other) "reads it as one it must not take" else "does not read it" }); - continue; - } - const word = slide_subject.keyWord(parts.words, parts.named, q); - if (parts.words.len > 0 and (word.len == 0 or !slide_subject.names(parts.named, parts.words, q))) { - // a wording that never names the subject ("my sibling", "the team") is another question, not this one's - log.line("slide: \"{s}\" does not name the fact's subject, so the lesson leaves it", .{q}); - continue; - } - var asked = try slide_ask.promptOnly(srv, cx, a, null, q); - asked.subject = try subjectRow(srv, cx, asked, word); - try parts.asked.append(a, asked); - var score: f32 = 0; - for (refs) |r| score += dice(q, r.question); - try unseen.append(a, .{ .q = q, .word = word, .score = score }); - taken += 1; - } - // the most typical of them check the fact after each round, so a vague one never decides - std.mem.sort(Unseen, unseen.items, {}, Unseen.more); - const note = if (parts.document) try std.fmt.allocPrint(a, prompts.read_note, .{fact}) else try std.fmt.allocPrint(a, prompts.told_note, .{fact}); - var probed: usize = 0; - for (unseen.items) |u| { - if (probed == probe_count) break; - const short = try shortAnswer(srv, cx, note, u.q, gone); - if (short.len > 0 and std.ascii.findIgnoreCase(u.q, short) != null) continue; // it says its own answer: nothing to recall - try parts.probes.append(a, .{ .question = u.q, .answer = fact, .fact = f, .subject = u.word, .short = short }); - probed += 1; - } - // each question again under client system messages: its neurons must act there too, and still leave the near misses - for (prompts.systems) |sys| { - for (refs) |r| { - var asked = try slide_ask.promptOnly(srv, cx, a, sys, r.question); - asked.subject = try subjectRow(srv, cx, asked, r.subject); - try parts.asked.append(a, asked); - } - for (near_questions) |q| try parts.unasked.append(a, try slide_ask.promptOnly(srv, cx, a, sys, q)); - } - // and after an unrelated exchange, as a question comes in a conversation already under way - for (prompts.turns, 0..) |before, i| { - for (refs, 0..) |r, k| if (k % prompts.turns.len == i) { - var asked = try slide_ask.promptAfter(srv, cx, a, before, r.question); - asked.subject = try subjectRow(srv, cx, asked, r.subject); - try parts.asked.append(a, asked); - }; - for (near_questions, 0..) |q, k| if (k % prompts.turns.len == i) try parts.unasked.append(a, try slide_ask.promptAfter(srv, cx, a, before, q)); - } - const subject = for (subjects) |s| { - if (s) |x| break x; - } else null; - const kinds = if (subject) |s| try kindsList(srv, cx, s, gone) else &.{}; - var swaps: usize = 0; - outer: for (refs) |r| for (try slide_route.others(a, r.question, subject, kinds)) |q| { - if (swaps == max_others) break :outer; - if ((try seen.getOrPut(a, q)).found_existing or wording.gives(fact, asked_all, answered_all, q)) continue; - try parts.unasked.append(a, try slide_ask.promptOnly(srv, cx, a, null, q)); - swaps += 1; - }; - log.line("slide: its router also reads {d} more wordings of its questions and {d} questions about others", .{ taken, swaps }); -} - /// An answer's tokens after another head (a question under a system message, or after an exchange), keyed as before. -fn under(srv: *Server, cx: *Cx, head: api.Example, body: []const u32, r: Held) !api.Example { +pub fn under(srv: *Server, cx: *Cx, head: api.Example, body: []const u32, r: Held) !api.Example { var ex: api.Example = .{ .ids = try std.mem.concat(cx.a, u32, &.{ head.ids, body }), .start = @intCast(head.ids.len), .decide = head.decide }; ex.subject = try subjectRow(srv, cx, ex, r.subject); ex.value = try slide_subject.valueRow(srv, cx, ex, r.short); @@ -540,54 +573,25 @@ fn under(srv: *Server, cx: *Cx, head: api.Example, body: []const u32, r: Held) ! } /// Whether the lesson teaches `question`: one of its own, or one a fact sharing a word with it answers. -fn answeredByAny(srv: *Server, cx: *Cx, told: []const []const u8, kept: []const bool, own: []const []const u8, question: []const u8, document: bool, gone: anytype) !bool { +fn answeredByAny(srv: *Server, cx: *Cx, told: []const []const u8, kept: []const bool, selves: []const bool, own: []const []const u8, question: []const u8, document: bool, gone: anytype) !bool { if (untold.taught(own, question)) return true; - for (told, kept) |fact, k| if (k and wording.shares(fact, question) and try answered(srv, cx, fact, question, document, gone)) return true; - return false; -} - -/// Whether personal prompt i is one this lesson asks again after it: three of them, turning with each lesson. -fn heldBack(lessons: usize, i: usize) bool { - const first = lessons * personal_checks % prompts.personal_prompts.len; - return (i + prompts.personal_prompts.len - first) % prompts.personal_prompts.len < personal_checks; -} - -/// The request for a fact's questions: as its teller would ask, or for a document's fact as a colleague would. -fn questionsFor(a: Allocator, document: bool, fact: []const u8, count: usize, language: ?[]const u8) ![]const u8 { - if (document) return prompted(a, prompts.doc_questions_prompt, slide_language.doc_questions_other, .{ fact, count, count }, language); - return prompted(a, prompts.questions_prompt, questions_other, .{ fact, count, count }, language); -} - -/// Earlier learned answers about the subject `fact` names, the latest `replayed` of them, into `keep`. -fn replay(srv: *Server, cx: *Cx, teacher: *Teacher, fact: []const u8, end: []const u32, keep: *std.ArrayList(api.Example)) !void { - var n: usize = 0; - var i = teacher.told.items.len; - while (i > 0 and n < replayed) : (i -= 1) { - const t = teacher.told.items[i - 1]; - if (std.ascii.findIgnoreCase(fact, t.subject) == null) continue; - try keep.append(cx.a, try example(srv, cx, cx.a, null, t.question, t.answer, end)); - n += 1; + for (told, kept, 0..) |fact, k, f| { + const self = f < selves.len and selves[f]; + const near = wording.shares(fact, question) or (self and wording.secondPerson(question)); + if (k and near and try answered(srv, cx, fact, question, document, self, gone)) return true; } - if (n > 0) log.line("slide: {d} answers of earlier facts about its subject are replayed for it to keep", .{n}); + return false; } -/// Whether most of a fact's questions ask who: its answer is someone. -fn asksWho(refs: []const Held) bool { - var who: usize = 0; - for (refs) |r| who += @intFromBool(std.ascii.startsWithIgnoreCase(r.question, "who")); - return 2 * who > refs.len; +/// Whether an answer written once (a keep prompt's, a bank question's) may be one a fact learned since has changed. +pub fn stale(learned: []const []const u8, question: []const u8) bool { + for (learned) |fact| if (wording.shares(fact, question) or (wording.toModel(question) and wording.addressesModel(fact))) return true; + return false; } -/// Whether the fact is about a particular person, place, organisation or thing rather than the speaker, as judged. -fn aboutEntity(srv: *Server, cx: *Cx, fact: []const u8, gone: anytype) !bool { - const reply = try askBase(srv, cx, null, try std.fmt.allocPrint(cx.a, prompts.about_prompt, .{fact}), 4, gone); +/// Whether a told fact is about the model itself: it speaks to the model (you, your), and the model judges it so. +pub fn aboutSelf(srv: *Server, cx: *Cx, fact: []const u8, gone: anytype) !bool { + if (!wording.addressesModel(fact)) return false; + const reply = try askBase(srv, cx, null, try std.fmt.allocPrint(cx.a, prompts.self_prompt, .{fact}), 4, gone); return std.ascii.startsWithIgnoreCase(std.mem.trim(u8, reply.content, " \t\r\n\"*"), "yes"); } - -/// Whether the fact answers `question`, as the model judges it when asked so (never one about someone it leaves out). -fn answered(srv: *Server, cx: *Cx, fact: []const u8, question: []const u8, document: bool, gone: anytype) !bool { - if (!document and wording.someoneElse(fact, question)) return false; - const yes = try slide_take.judged(srv, cx, fact, question, document, gone); - if (yes) log.line("slide: \"{s}\" is answered by the fact, so it is learned rather than kept", .{question}); - return yes; -} diff --git a/zig/src/server/slide_model.zig b/zig/src/server/slide_model.zig index db94df3e69..3f914f9dad 100644 --- a/zig/src/server/slide_model.zig +++ b/zig/src/server/slide_model.zig @@ -1,4 +1,4 @@ -//! The served model as the Living Weights view draws it: layers, pockets and shards, named as its family names them. +//! The served model as the Sliding Weights view draws it: its layers, its pockets, and the shards that hold them. const std = @import("std"); const json = @import("json.zig"); const families = @import("living").families; @@ -237,3 +237,32 @@ test "a folder's layers, pockets in use and shards; a save's files and bytes" { const text = try json.stringify(a, try value(a, again), .{ .compact = true }); try std.testing.expect(std.mem.indexOf(u8, text, "\"pocket\":{\"neurons\":64,\"layers\":[1,3],\"used\":[3,3]}") != null); } + +test "a Flash Next folder: every layer an MoE, its keys under text_config, the pocket read off gate_proj's rows" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = "{\"model_type\": \"qwen4_exp\", \"text_config\": {\"num_hidden_layers\": 3, \"tensorfold_learned_neurons\": 64}}" }); + // 64 own rows and 64 pocket rows of one bf16 scale: pocket row 1 in use at layer 2, so two neurons count + var scales: [128 * 2]u8 = @splat(0); + scales[(64 + 1) * 2 + 1] = 0x3f; + const zeros: [128 * 2]u8 = @splat(0); + try writeShard(io, tmp.dir, "model-00001-of-00001.safetensors", &.{ + .{ "language_model.model.layers.2.mlp.shared_expert.gate_proj.scales", "BF16", .{ 128, 1 }, &scales }, + .{ "language_model.model.layers.2.mlp.shared_expert.up_proj.scales", "BF16", .{ 128, 1 }, &zeros }, + .{ "language_model.model.layers.0.mlp.shared_expert_gate.scales", "BF16", .{ 128, 1 }, &scales }, + .{ "language_model.mtp.layers.0.mlp.shared_expert.gate_proj.scales", "BF16", .{ 128, 1 }, &scales }, + }); + const dir = try std.fs.path.join(a, &.{ ".zig-cache", "tmp", &tmp.sub_path }); + const m = try scan(a, io, dir); + try std.testing.expectEqualStrings("EEE", m.kinds); + try std.testing.expectEqual(@as(usize, 64), m.pocket); + try std.testing.expectEqualSlices(u16, &.{ 0, 1, 2 }, m.moe); + try std.testing.expectEqualSlices(u16, &.{ 0, 0, 2 }, m.used); + try std.testing.expectEqualSlices(u16, &.{2}, m.shards[0].layers); + // its experts' bytes (the MTP head's too), not the expert gate's + try std.testing.expectEqual(@as(u64, 3 * 256), m.shards[0].expert_bytes); +} diff --git a/zig/src/server/slide_pick.zig b/zig/src/server/slide_pick.zig index 234d90cfb0..4a7ee113d2 100644 --- a/zig/src/server/slide_pick.zig +++ b/zig/src/server/slide_pick.zig @@ -26,6 +26,9 @@ pub fn heldPair(fact: []const u8, refs: []const Held) [2]usize { }; // "What name is my little sister?" tests little, which no answer knowing the fact can bring back if (strays(fact, refs, i)) s -= @floatFromInt(refs.len); + // "Can you learn into your own weights?" says the whole fact: its yes shows no recall. + const words = @import("slide_words.zig"); + if (!words.lacks(fact, r.question) or words.asksYesNo(r.question, true)) s -= @floatFromInt(refs.len); if (s > score[0]) { score[1] = score[0]; best[1] = best[0]; diff --git a/zig/src/server/slide_prompts.zig b/zig/src/server/slide_prompts.zig index 88b3eef411..378b2dd092 100644 --- a/zig/src/server/slide_prompts.zig +++ b/zig/src/server/slide_prompts.zig @@ -44,6 +44,118 @@ pub const keep_prompts = [_][]const u8{ "How many legs does a spider have?", }; +/// Prompts of the kinds the keep prompts lack. +pub const broad_keep = [_][]const u8{ + "Write the Pythagorean theorem in LaTeX.", + "What is 23 times 19? Show the steps.", + "Solve 2x - 5 = 11 for x.", + "Differentiate e^(2x) cos(x).", + "What is the formula for the area of a circle?", + "Convert 100 degrees Fahrenheit to Celsius.", + "Write a C function that adds two integers.", + "Write a Python list comprehension that squares the numbers 1 to 10.", + "Write a SQL query that selects the ten newest users.", + "Explain how a binary search works.", + "Write a short poem about the moon.", + "Write a haiku about winter.", + "Write a dialogue line for a pirate captain.", + "List four vegetables that are green.", + "Give me three tips for sleeping better, as a numbered list.", + "Name the four largest oceans.", + "Traduce al español: \"Where is the train station?\"", + "Wie spät ist es in Berlin, wenn es in London 12 Uhr ist?", + "Quelle est la capitale de l'Italie ?", + "请用中文写一句关于春天的话。", + "東京タワーについて一文で説明してください。", + "Return a JSON array of the first five prime numbers.", + "Make a markdown table of three animals and their sounds.", + "What happened in 1969 on the Moon?", + "Write the formula for the volume of a sphere in LaTeX.", + "What is 156 divided by 12? Show the working.", + "Expand (x + 3)(x - 2).", + "What is the sum of the angles in a triangle?", + "Write Euler's identity in LaTeX.", + "Integrate x^2 from 0 to 2.", + "Compute 7 factorial.", + "What is 3/4 plus 2/3?", + "Write the matrix [[1, 2], [3, 4]] in LaTeX.", + "Find the slope of the line through (1, 2) and (3, 8).", + "Explain what a logarithm is with an example.", + "What is 2 to the power of 10?", + "Write a Rust function that returns the larger of two numbers.", + "Write a Go function that sums a slice of ints.", + "Write a TypeScript interface for a user with a name and an email.", + "Write a bash loop that prints the numbers 1 to 5.", + "Write a Python class for a bank account with deposit and withdraw.", + "What does the git rebase command do?", + "Write a CSS rule that centres a div.", + "Write an HTML form with a name field and a submit button.", + "Explain the difference between a list and a tuple in Python.", + "Write a Java method that checks whether a string is a palindrome.", + "Write a regular expression that matches a US ZIP code.", + "What is Big O notation?", + "Write a limerick about a dog who loves the beach.", + "Write a four-line poem about city lights.", + "Write a haiku about a cup of tea.", + "Write the first line of a fairy tale.", + "Describe a sunset in two sentences.", + "Write a short toast for a friend's wedding.", + "Write a riddle about a clock.", + "Write two rhyming lines about the stars.", + "List five countries in Africa.", + "Give me a numbered list of three ways to save water.", + "List the days of the week in French.", + "Name four instruments in an orchestra.", + "Make a markdown table of three fruits and their colours.", + "Return a YAML list of three cities.", + "Write a CSV header for a table of books.", + "Give me a bullet list of packing items for a beach trip.", + "¿Cuál es el río más largo del mundo?", + "Écris une phrase sur la mer en français.", + "Was ist Photosynthese? Erkläre kurz.", + "Qual è il piatto più famoso dell'Italia?", + "Qual é a capital de Portugal?", + "Как дела? Ответь по-русски.", + "ما هي عاصمة مصر؟", + "한국의 수도는 어디입니까?", + "请用中文解释什么是光合作用。", + "中国最长的河流是哪一条?", + "日本の有名な料理を三つ教えてください。", + "富士山の高さはどれくらいですか?", + "Wat is de hoofdstad van Nederland?", + "Hindi mein namaste ka matlab kya hai?", + "Explain how a rainbow forms.", + "Why do cats purr?", + "What is the theory of relativity in simple terms?", + "Describe the water cycle.", + "What causes earthquakes?", + "Explain inflation in economics in two sentences.", + "Who was Cleopatra?", + "What is a black hole?", + "How do bees make honey?", + "What is the difference between a virus and a bacterium?", + "Summarise the story of Cinderella in three sentences.", + "Give me advice for a job interview.", + "Explain what a contract is in legal terms.", + "What are the symptoms of the common cold?", +}; + +/// Prompts of those kinds again, none of them read by a lesson. +pub const drift_checks = [_][]const u8{ + "What is 64 divided by 8? Answer with the working.", + "Write the formula for kinetic energy in LaTeX.", + "What is the square root of 144?", + "Write a JavaScript arrow function that doubles a number.", + "Explain what an API is in one sentence.", + "Write four lines of a poem about a river.", + "Name five colours of the rainbow as a list.", + "Translate \"thank you very much\" into Italian.", + "¿Qué idioma se habla en Brasil?", + "用一句话解释什么是人工智能。", + "日本語で「おはよう」はどういう意味ですか?", + "Return a JSON object describing a book with a title and an author.", +}; + /// Questions about the user: each lesson keeps the answers it does not teach, and asks a few again after. pub const personal_prompts = [_][]const u8{ "What is my favourite food?", @@ -252,6 +364,15 @@ pub const again_prompt = "Earlier the user told you: \"{s}\" Now the user tells pub const replace_prompt = "Earlier the user told you: \"{s}\" Now the user tells you: \"{s}\" Does the new message change or take back what they told you earlier? Reply yes or no."; /// The 1.0.7 judge for what the user told about themselves, which counts liking blue as their favourite colour. pub const told_judge_prompt = "The user told you this about themselves or their work: \"{s}\" Does it answer this question they ask you: \"{s}\"? Reply yes or no."; +/// A fact the user tells the model about itself ("Your name is Ada."): asked of the model, answered as itself. +pub const self_prompt = "A user said this to you, the AI assistant they are talking to: \"{s}\" Is it telling you something about yourself, the assistant (such as your name, what you are, what you are like, what you can do, where or on what you run, or your birthday), rather than about the user, someone else or something else? Answer yes or no."; +pub const self_questions_prompt = "The user told you this about yourself: \"{s}\" Write {d} different short questions that it answers, which someone might ask you later about yourself, speaking to you as \"you\" and \"your\": ask it plainly, in other words and in passing (for example, for \"Your favourite colour is green.\": What is your favourite colour? Which colour do you like best?). Ask mostly what, how, where, which or who, and only a few that can be answered yes or no. Every question must be answered by exactly what it says. Number them 1 to {d}, one per line, nothing else."; +pub const self_besides_prompt = "The user told you this about yourself: \"{s}\" Write {d} short questions someone might ask you about yourself that this does not answer, speaking to you as \"you\" and \"your\" (for example, for \"Your favourite colour is green.\": How old are you? Where do you live?). Number them, one per line, nothing else."; +/// Answers that say what the fact says ("My humor is dark and crude."), not ones that act it out (a crude joke). +pub const self_note = "You know this about yourself: \"{s}\" It is true of you. Answer in the first person, as something you simply know about yourself, saying plainly what it says."; +pub const self_judge_prompt = "The user told you this about yourself, the assistant: \"{s}\" Does it answer this question someone asks you about yourself: \"{s}\"? Reply yes or no."; +/// Yes-or-no questions naming another value than a fact about the model says ("Are you a man?" for "You are a woman."). +pub const self_other_values_prompt = "The user told you this about yourself: \"{s}\" Write {d} yes-or-no questions someone might ask you about it, each naming something else of the same kind in place of what it says (for example, for \"Your favourite colour is green.\": Is your favourite colour red? Do you like blue best?), speaking to you as \"you\" and \"your\". Number them 1 to {d}, one per line, nothing else."; pub const facts_prompt = "Read the text below and list the facts in it worth remembering later: names, numbers, versions, dates, times, tools, decisions and news. Write one fact per line. Split a sentence that holds several facts into one line for each (a day and a time are two facts), and name who or what each line is about in full, putting the name of the organisation, place or person in place of words like we, our, it, they, the company or the team, and naming the organisation a line belongs to even when the text leaves it implied (Acme code reviews, Acme employees). Write each fact about a person once more with the person first. Keep what each named thing or person is (a product's kind, a person's role). For example, from this text:\nAcme handbook. Acme was founded in 2010 in Leeds by Jo Smith, who is still our chief executive. We build Widgetly, a planning app for schools. Our support desk opens at 9 am every weekday. Every code review needs one approval. We track bugs in Linear.\nwrite:\nAcme was founded in 2010.\nAcme was founded in Leeds.\nAcme was founded by Jo Smith.\nJo Smith founded Acme.\nThe Acme chief executive is Jo Smith.\nJo Smith is the Acme chief executive.\nAcme builds Widgetly.\nWidgetly is a planning app for schools.\nThe Acme support desk opens at 9 am.\nThe Acme support desk opens every weekday.\nAn Acme code review needs one approval.\nAcme tracks bugs in Linear.\nOne fact per line, nothing else.\n\n{s}"; /// Found facts again the other way round: a lesson keyed on the person never answers a question naming the other. pub const reverse_prompt = "Here is a fact: \"{s}\" If it names a person together with an organisation, team, place or thing, write it once more with the two the other way round (for example, \"Jo Smith founded Acme.\" becomes \"Acme was founded by Jo Smith.\", and \"The Acme chief executive is Jo Smith.\" becomes \"Jo Smith is the Acme chief executive.\"). If it names no person, reply: none. One line, nothing else."; diff --git a/zig/src/server/slide_recheck.zig b/zig/src/server/slide_recheck.zig new file mode 100644 index 0000000000..26a4f6df96 --- /dev/null +++ b/zig/src/server/slide_recheck.zig @@ -0,0 +1,179 @@ +//! After a lesson, before anything is saved: every fact learned before it asked again on its own held-out wordings. +const std = @import("std"); +const api = @import("engine_api"); +const log = @import("log.zig"); +const errors = @import("errors.zig"); +const wording = @import("slide_words.zig"); +const side = @import("slide_side.zig"); +const talks = @import("slide_context.zig"); +const slide_ask = @import("slide_ask.zig"); +const graph = @import("slide_graph.zig"); +const Server = @import("server.zig").Server; +const Cx = errors.Cx; +const Allocator = std.mem.Allocator; + +/// Times a lesson that made an earlier fact forget is fitted again, that fact's answers held as they were. +pub const repairs = 2; + +/// An earlier fact asked again: whether it comes back now, and whether it came back at its last check before. +pub const Result = struct { fact: graph.Earlier, recalled: bool, was: bool }; + +/// Which `of` a check reads: every learned fact, or only those no check has judged since the server started. +pub const Which = enum { all, unjudged }; + +/// The learned facts but `id`, each asked again on its wordings (`which`), side by side. +pub fn check(srv: *Server, cx: *Cx, id: u32, which: Which, before: []const graph.Earlier, gone: anytype) ![]Result { + const a = cx.a; + var facts: std.ArrayList(graph.Earlier) = .empty; + for (try srv.slide.earlier(a, id)) |f| if (which == .all or f.recalled == null) try facts.append(a, f); + var asking: std.ArrayList(side.Asking) = .empty; + for (facts.items) |f| for (f.asked) |w| try asking.append(a, .{ .question = w.question, .before = try talks.turns(srv, cx, w.context, gone) }); + const replies = try side.askAll(srv, cx, asking.items, gone); + const out = try a.alloc(Result, facts.items.len); + var at: usize = 0; + for (facts.items, out) |f, *r| { + var held = true; + var probes: usize = 0; + var probed: usize = 0; + for (f.asked, 0..) |w, i| { + const reply = replies[at].content; + at += 1; + const back = brings(f.text, w, reply); + if (!back) log.line("slide: \"{s}\"{s}{s}, asked again for \"{s}\", does not bring it back: {s}", .{ w.question, if (w.context.len > 0) " after the conversation " else "", w.context, f.text, reply }); + if (back and w.answer.len == 0) srv.slide.answered(f.id, i, reply); + if (w.probe) { + probes += 1; + probed += @intFromBool(back); + } else held = held and back; + } + r.* = .{ .fact = f, .recalled = held and 2 * probed >= probes, .was = was(before, f) }; + srv.slide.checked(f.id, r.recalled); + } + return out; +} + +/// Whether fact `f` came back before: as `before` holds it, else at its last check (a fact never checked did). +fn was(before: []const graph.Earlier, f: graph.Earlier) bool { + for (before) |b| if (b.id == f.id) return b.recalled orelse true; + return f.recalled orelse true; +} + +/// Whether `reply` brings back fact `fact` that wording `w` asks for. +fn brings(fact: []const u8, w: graph.Asked, reply: []const u8) bool { + if (w.short.len > 0) return wording.recallsShort(fact, w.question, w.short, reply); + if (w.answer.len > 0) return wording.recalls(fact, w.question, w.answer, reply); + return wording.tells(fact, w.question, "", reply); +} + +/// The facts that came back at their last check and do not now. +pub fn forgotten(a: Allocator, results: []const Result) ![]const Result { + var out: std.ArrayList(Result) = .empty; + for (results) |r| if (r.was and !r.recalled) try out.append(a, r); + return out.items; +} + +/// A lesson fitted again keeping what `lost` facts' held-out questions answered: their prompts and those answers. +pub fn keeps(srv: *Server, cx: *Cx, lost: []const Result) !struct { prompts: []const api.Example, kept: []const api.Example } { + const a = cx.a; + var prompts: std.ArrayList(api.Example) = .empty; + var kept: std.ArrayList(api.Example) = .empty; + for (lost) |r| for (r.fact.asked) |w| { + if (w.probe or w.context.len > 0) continue; + const answer = if (w.answer.len > 0) w.answer else continue; + try prompts.append(a, try slide_ask.promptOnly(srv, cx, a, null, w.question)); + try kept.append(a, try slide_ask.example(srv, cx, a, null, w.question, answer, &.{})); + }; + return .{ .prompts = prompts.items, .kept = kept.items }; +} + +/// Broad questions no one fact answers, watched across a lesson. +pub const broad = [_][]const u8{ "Do you know who I am?", "What do you know about me?", "Tell me about yourself." }; +pub const broad_tokens = 64; + +/// The broad questions' replies now, side by side. +pub fn askBroad(srv: *Server, cx: *Cx, gone: anytype) ![]const []const u8 { + var asking: [broad.len]side.Asking = undefined; + for (&asking, broad) |*x, q| x.* = .{ .question = q, .max = broad_tokens }; + const replies = try side.askAll(srv, cx, &asking, gone); + const out = try cx.a.alloc([]const u8, replies.len); + for (out, replies) |*o, r| o.* = r.content; + return out; +} + +/// The first name `reply` says (a capitalised word past a sentence's start) that neither `before`. +pub fn invented(reply: []const u8, before: []const u8, question: []const u8, facts: []const []const u8) ?[]const u8 { + const common = [_][]const u8{ "I", "I'm", "I've", "I'd", "I'll", "AI", "OK", "Yes", "No", "Hi", "Hello", "Hey", "However", "But", "And", "So", "Well", "Sure", "Of", "As", "If", "In", "On", "At", "My", "You", "Your", "The", "A", "An", "It", "This", "That", "What", "How", "Why", "Who", "When", "Where", "Is", "Are", "Do", "Can", "Please", "Thanks", "Thank" }; + var at: usize = 0; + var start = true; // the word opens a sentence: its capital says nothing + while (at < reply.len) { + while (at < reply.len and !isWordByte(reply[at])) : (at += 1) { + if (reply[at] == '.' or reply[at] == '!' or reply[at] == '?' or reply[at] == '\n' or reply[at] == ':') start = true; + } + var end = at; + while (end < reply.len and isWordByte(reply[end])) end += 1; + if (end == at) break; + const raw = reply[at..end]; + const word = std.mem.trimEnd(u8, if (std.mem.endsWith(u8, raw, "'s")) raw[0 .. raw.len - 2] else raw, "'"); + const opens = start; + start = false; + at = end; + if (opens or word.len < 2 or !std.ascii.isUpper(word[0])) continue; + var known = false; + for (common) |c| known = known or std.ascii.eqlIgnoreCase(word, c); + known = known or hasWord(before, word) or hasWord(question, word); + for (facts) |f| known = known or hasWord(f, word); + if (!known) return word; + } + return null; +} + +fn isWordByte(c: u8) bool { + return std.ascii.isAlphanumeric(c) or c == '\'' or c >= 0x80; +} + +/// Whether `text` says `word` as a word of its own, in any case, possessive or not. +fn hasWord(text: []const u8, word: []const u8) bool { + var it = std.mem.tokenizeAny(u8, text, " \t\r\n,.;:!?()[]\"*-"); + while (it.next()) |raw| { + const w = std.mem.trimEnd(u8, if (std.mem.endsWith(u8, raw, "'s")) raw[0 .. raw.len - 2] else raw, "'"); + if (std.ascii.eqlIgnoreCase(w, word)) return true; + } + return false; +} + +test "a broad question's reply that names what no fact said is flagged" { + const facts = [_][]const u8{ "My name is Sam.", "Sam is a contributor to TensorFold." }; + try std.testing.expectEqualStrings("Chumeng", invented("Yes! You told me your name is **Chumeng**.", "No, I don't know who you are.", "Do you know who I am?", &facts).?); + try std.testing.expectEqualStrings("Trace", invented("You are Sam, and the model I run on is called **Trace**.", "No.", "Do you know who I am?", &facts).?); + try std.testing.expect(invented("Yes, I do. You told me earlier that your name is Sam.", "No.", "Do you know who I am?", &facts) == null); + try std.testing.expect(invented("I am Qwen, a model built by Alibaba Cloud.", "I am Qwen, a large language model by Alibaba Cloud.", "Tell me about yourself.", &facts) == null); +} + +/// The facts in `rs` as one line: "I like blue.", "My sister is called Ana." +pub fn names(a: Allocator, rs: []const Result) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + for (rs, 0..) |r, i| { + if (i > 0) try out.appendSlice(a, ", "); + try out.print(a, "\"{s}\"", .{r.fact.text}); + } + return out.items; +} + +test "a fact asked again comes back when every held-out question and half its probes bring it back" { + const ana: graph.Asked = .{ .question = "What is my sister's name?", .answer = "Your sister is called Ana.", .short = "Ana" }; + try std.testing.expect(brings("My sister is called Ana.", ana, "Your sister is called Ana.")); + try std.testing.expect(!brings("My sister is called Ana.", ana, "I don't know your sister's name.")); + const blue: graph.Asked = .{ .question = "What colour do I prefer?" }; + try std.testing.expect(brings("I like blue.", blue, "You like **blue**.")); + try std.testing.expect(!brings("I like blue.", blue, "As an AI, I don't have access to your personal preferences.")); + const a = std.testing.allocator; + const f: graph.Earlier = .{ .id = 1, .text = "I like blue.", .asked = &.{}, .recalled = null }; + const rs = [_]Result{ .{ .fact = f, .recalled = false, .was = true }, .{ .fact = f, .recalled = false, .was = false }, .{ .fact = f, .recalled = true, .was = true } }; + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + try std.testing.expectEqual(@as(usize, 1), (try forgotten(arena.allocator(), &rs)).len); + // a fact the lesson's first check found forgotten is still one that came back before the lesson + const now: graph.Earlier = .{ .id = 1, .text = "I like blue.", .asked = &.{}, .recalled = false }; + try std.testing.expect(was(&.{.{ .id = 1, .text = "I like blue.", .asked = &.{}, .recalled = true }}, now)); + try std.testing.expect(!was(&.{}, now)); +} diff --git a/zig/src/server/slide_replace.zig b/zig/src/server/slide_replace.zig index 8e94a73ba9..ac77465b85 100644 --- a/zig/src/server/slide_replace.zig +++ b/zig/src/server/slide_replace.zig @@ -7,6 +7,7 @@ const slide_ask = @import("slide_ask.zig"); const slide_graph = @import("slide_graph.zig"); const side = @import("slide_side.zig"); const take = @import("slide_take.zig"); +const wording = @import("slide_words.zig"); const Server = @import("server.zig").Server; const Allocator = std.mem.Allocator; const Cx = errors.Cx; @@ -14,9 +15,11 @@ const Cx = errors.Cx; const candidates = 32; // learned chat facts a new one is checked against, the latest first /// The learned chat facts `fact` replaces: it answers one of their questions, or changes or takes back what they say. -pub fn replaced(srv: *Server, cx: *Cx, fact: []const u8, id: u32, gone: anytype) ![]const slide_graph.Fact { +pub fn replaced(srv: *Server, cx: *Cx, fact: []const u8, id: u32, self: bool, gone: anytype) ![]const slide_graph.Fact { const a = cx.a; - const olds = try srv.slide.learnedChat(a, id, candidates); + var kin: std.ArrayList(slide_graph.Fact) = .empty; + for (try srv.slide.learnedChat(a, id, candidates)) |o| if (wording.addressesModel(o.text) == self) try kin.append(a, o); + const olds = kin.items; if (olds.len == 0) return &.{}; const yes = try a.alloc(bool, olds.len); @memset(yes, false); @@ -24,6 +27,7 @@ pub fn replaced(srv: *Server, cx: *Cx, fact: []const u8, id: u32, gone: anytype) srv: *Server, a: Allocator, fact: []const u8, + self: bool, olds: []const slide_graph.Fact, gone: @TypeOf(gone), yes: []bool, @@ -34,15 +38,18 @@ pub fn replaced(srv: *Server, cx: *Cx, fact: []const u8, id: u32, gone: anytype) // "Now I like red." after "My favourite colour is red." says it again: the earlier one stays const same = try slide_ask.askBase(j.srv, &jcx, null, try std.fmt.allocPrint(j.a, prompts.again_prompt, .{ old.text, j.fact }), 4, j.gone); if (std.ascii.startsWithIgnoreCase(std.mem.trim(u8, same.content, " \t\r\n\"*"), "yes")) return; - for (old.questions) |q| if (try take.judged(j.srv, &jcx, j.fact, q, false, j.gone)) { - j.yes[i] = true; - return; - }; + // answering an earlier fact's question is not enough: "Sam is a contributor to TensorFold." answers "What. + if (j.self) { + const answers = for (old.questions) |q| { + if (try take.judgedAs(j.srv, &jcx, j.fact, q, false, true, j.gone)) break true; + } else false; + if (!answers) return; + } const said = try slide_ask.askBase(j.srv, &jcx, null, try std.fmt.allocPrint(j.a, prompts.replace_prompt, .{ old.text, j.fact }), 4, j.gone); j.yes[i] = std.ascii.startsWithIgnoreCase(std.mem.trim(u8, said.content, " \t\r\n\"*"), "yes"); } }; - try side.each(olds.len, &Job{ .srv = srv, .a = a, .fact = fact, .olds = olds, .gone = gone, .yes = yes }); + try side.each(olds.len, &Job{ .srv = srv, .a = a, .fact = fact, .self = self, .olds = olds, .gone = gone, .yes = yes }); var out: std.ArrayList(slide_graph.Fact) = .empty; for (olds, yes) |o, y| if (y) { log.line("slide: \"{s}\" replaces \"{s}\" (fact {d}), whose neurons are taken out first", .{ fact, o.text, o.id }); diff --git a/zig/src/server/slide_route.zig b/zig/src/server/slide_route.zig index 41849e4a4f..6c4854280c 100644 --- a/zig/src/server/slide_route.zig +++ b/zig/src/server/slide_route.zig @@ -10,8 +10,14 @@ const relations = [_][]const u8{ "sister", "brother", "mother", "father", "frien const named_words = relations ++ [_][]const u8{ "wife", "husband", "partner", "son", "daughter", "boss", "colleague", "neighbour", "neighbor", "cousin", "aunt", "uncle", "mum", "mom", "dad", "sis", "bro", "girlfriend", "boyfriend", "grandma", "grandpa" }; /// `question` about others: each other relation, each thing of the fact's kind for `subject`, and asked of the model. -pub fn others(a: Allocator, question: []const u8, subject: ?[]const u8, kinds: []const []const u8) ![]const []const u8 { +pub fn others(a: Allocator, question: []const u8, subject: ?[]const u8, kinds: []const []const u8, self: bool) ![]const []const u8 { var out: std.ArrayList([]const u8) = .empty; + if (self) { + const mine = try wording.asUser(a, question) orelse return out.items; + try out.append(a, mine); + for (relations) |r| if (try wording.about(a, mine, r)) |q| try out.append(a, q); + return out.items; + } if (named(question)) |at| { const word = question[at[0]..at[1]]; for (relations) |r| if (!std.ascii.eqlIgnoreCase(word, r)) try out.append(a, try std.mem.concat(a, u8, &.{ question[0..at[0]], r, question[at[1]..] })); @@ -43,13 +49,24 @@ test "a fact's question is asked about other people, other things of its kind an var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - const sister = try others(a, "What's my sister's name?", null, &.{}); + const sister = try others(a, "What's my sister's name?", null, &.{}, false); try std.testing.expectEqualStrings("What's my brother's name?", sister[0]); try std.testing.expectEqual(relations.len, sister.len); // every other near relation, then the model's own try std.testing.expectEqualStrings("What's your sister's name?", sister[sister.len - 1]); - const colour = try others(a, "What colour do I like best?", "colour", &.{ "food", "sport" }); + const colour = try others(a, "What colour do I like best?", "colour", &.{ "food", "sport" }, false); try std.testing.expectEqualStrings("What colour does my sister like best?", colour[0]); var food = false; for (colour) |q| food = food or std.mem.eql(u8, q, "What food do I like best?"); try std.testing.expect(food); } + +test "a question to the model about itself is asked of the user and those they know instead" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const name = try others(a, "What's your name?", null, &.{}, true); + try std.testing.expectEqualStrings("What's my name?", name[0]); + try std.testing.expectEqualStrings("What's my sister's name?", name[1]); + try std.testing.expectEqual(1 + relations.len, name.len); + for (name) |q| try std.testing.expect(!wording.secondPerson(q)); +} diff --git a/zig/src/server/slide_router.zig b/zig/src/server/slide_router.zig new file mode 100644 index 0000000000..3f28813896 --- /dev/null +++ b/zig/src/server/slide_router.zig @@ -0,0 +1,226 @@ +//! A lesson's router data and the questions it asks about the fact's subject, beside slide_lesson.zig. +const slide_lesson_mod = @import("slide_lesson.zig"); +const personal_checks = slide_lesson_mod.personal_checks; +const std = @import("std"); +const api = @import("engine_api"); +const errors = @import("errors.zig"); +const log = @import("log.zig"); +const wording = @import("slide_words.zig"); +const units = @import("slide_units.zig"); +const slide_route = @import("slide_route.zig"); +const Server = @import("server.zig").Server; +const Allocator = std.mem.Allocator; +const Cx = errors.Cx; +const slide_ask = @import("slide_ask.zig"); +const slide_language = @import("slide_language.zig"); +const prompted = slide_language.prompted; +const questions_other = slide_language.questions_other; +const ask = slide_ask.ask; +const askBase = slide_ask.askBase; +const example = slide_ask.example; +const prompts = @import("slide_prompts.zig"); +const slide_subject = @import("slide_subject.zig"); +const slide_take = @import("slide_take.zig"); +const take = slide_take.take; +const shortAnswer = slide_take.shortAnswer; +const judged = slide_take.judged; +const siblingAnswers = slide_take.siblingAnswers; +const subjectRow = slide_subject.subjectRow; +const kindsList = slide_subject.kindsList; +const slide_teacher = @import("slide_teacher.zig"); +const Teacher = slide_teacher.Teacher; +const slide_pick = @import("slide_pick.zig"); +const talks = @import("slide_context.zig"); +const Unseen = slide_pick.Unseen; +const dice = slide_pick.dice; +const Held = slide_lesson_mod.Held; +const Parts = slide_lesson_mod.Parts; +const extra_wordings = slide_lesson_mod.extra_wordings; +const lesson = slide_lesson_mod.lesson; +const max_others = slide_lesson_mod.max_others; +const others = slide_lesson_mod.others; +const probe_count = slide_lesson_mod.probe_count; +const replayed = slide_lesson_mod.replayed; +const stale = slide_lesson_mod.stale; +const talk_answers = slide_lesson_mod.talk_answers; +const talk_near = slide_lesson_mod.talk_near; +const talk_questions = slide_lesson_mod.talk_questions; +const talk_rows = slide_lesson_mod.talk_rows; +const under = slide_lesson_mod.under; +const wording_temperature = slide_lesson_mod.wording_temperature; + +/// The fact's questions also asked after the conversations it learns in (slide_context.zig). +pub fn conversations(srv: *Server, cx: *Cx, parts: *Parts, refs: []const Held, pairs: []const api.Example, pair: [2]usize, near: []const []const u8, gone: anytype) !void { + const a = cx.a; + var asked: usize = 0; + var silent: usize = 0; + var answers: usize = 0; + for (talks.learned, 0..) |name, c| { + const before = try talks.turns(srv, cx, name, gone); + if (before.len == 0) continue; + var taken: usize = 0; + for (refs, pairs, 0..) |r, ex, i| { + if (i == pair[0] or i == pair[1]) continue; + if (taken == talk_questions) break; + var in = try talks.promptIn(srv, cx, a, before, r.question); + in.subject = try subjectRow(srv, cx, in, r.subject); + try parts.asked.append(a, in); + taken += 1; + asked += 1; + // its answer after it, when the trainer reads it whole + if (taken > talk_answers) continue; + const body = ex.ids[ex.start..]; + if (in.ids.len + body.len > talk_rows) continue; + // its conversation's rows marked too: an earlier fact's question and answer in a chain are not this one's + var answer = try under(srv, cx, in, body, r); + answer.context = in.context; + try parts.train.append(a, answer); + answers += 1; + } + if (near.len == 0) continue; + for (0..@min(talk_near, near.len)) |k| { + try parts.unasked.append(a, try talks.promptIn(srv, cx, a, before, near[(c * talk_near + k) % near.len])); + silent += 1; + } + } + log.line("slide: {d} of its questions also asked after conversations, {d} near misses there, {d} answers learned there", .{ asked, silent, answers }); +} + +/// More of the fact's questions (judged as `take` judges them) and its questions asked about others, prompts only. +pub fn routerData(srv: *Server, cx: *Cx, parts: *Parts, fact: []const u8, f: usize, refs: []const Held, subjects: []const ?[]const u8, near_questions: []const []const u8, asked_all: []const u8, answered_all: []const u8, language: ?[]const u8, gone: anytype) !void { + const a = cx.a; + var seen: std.StringHashMapUnmanaged(void) = .empty; + for (refs) |r| try seen.put(a, r.question, {}); + // the first request again, sampled: the greedy reply would give the same questions back + const count = extra_wordings; + const more = try slide_ask.askBaseAt(srv, cx, null, try questionsFor(a, parts.document, parts.self, fact, count, language), 32 * count, wording_temperature, gone); + var taken: usize = 0; + var unseen: std.ArrayList(Unseen) = .empty; // wordings never learned, the most typical of them checked after a round + const wordings = try wording.questions(a, more.content, count); + if (wordings.len == 0) log.line("slide: no more wordings came back: {s}", .{more.content}); + for (wordings) |q| { + if ((try seen.getOrPut(a, q)).found_existing) continue; + const personal = !parts.document and !slide_take.whose(fact, q, parts.self); + const why: ?[]const u8 = if (personal or !units.sameScript(fact, q)) (if (parts.self) "is not a question to the model about itself" else "is not the user asking about themselves") else if (wording.gives(fact, asked_all, answered_all, q)) "gives the fact away" else if (!try slide_take.judgedAs(srv, cx, fact, q, parts.document, parts.self, gone)) "is not answered by the fact" else if (try siblingAnswers(srv, cx, parts.siblings, fact, q, parts.document, gone)) "is another fact's" else null; + if (why) |w| { + // a wording about the model. + const own = wording.asksOf(q, parts.self); + const other = !parts.document and !own and units.sameScript(fact, q) and !wording.gives(fact, asked_all, answered_all, q); + if (other) try parts.unasked.append(a, try slide_ask.promptOnly(srv, cx, a, null, q)); + log.line("slide: \"{s}\" {s}, so its router {s}", .{ q, w, if (other) "reads it as one it must not take" else "does not read it" }); + continue; + } + const word = slide_subject.keyWord(parts.words, parts.named, q); + if (parts.words.len > 0 and (word.len == 0 or !slide_subject.names(parts.named, parts.words, q))) { + // a wording that never names the subject ("my sibling", "the team") is another question, not this one's + log.line("slide: \"{s}\" does not name the fact's subject, so the lesson leaves it", .{q}); + continue; + } + var asked = try slide_ask.promptOnly(srv, cx, a, null, q); + asked.subject = try subjectRow(srv, cx, asked, word); + try parts.asked.append(a, asked); + var score: f32 = 0; + for (refs) |r| score += dice(q, r.question); + try unseen.append(a, .{ .q = q, .word = word, .score = score }); + taken += 1; + } + // the most typical of them check the fact after each round, so a vague one never decides + std.mem.sort(Unseen, unseen.items, {}, Unseen.more); + const note = try slide_take.noteFor(a, parts.document, parts.self, fact); + var probed: usize = 0; + for (unseen.items) |u| { + if (probed == probe_count) break; + const short = try shortAnswer(srv, cx, note, u.q, gone); + if (short.len > 0 and std.ascii.findIgnoreCase(u.q, short) != null) continue; // it says its own answer: nothing to recall + if (!wording.lacks(fact, u.q)) continue; // it says every word the fact would bring back: no reply could show recall + if (wording.ownValue(fact, u.q, parts.self)) continue; // yes or no on the fact itself: its yes names nothing new + try parts.probes.append(a, .{ .question = u.q, .answer = fact, .fact = f, .subject = u.word, .short = short }); + probed += 1; + } + // each question again under client system messages: its neurons must act there too, and still leave the near misses + for (prompts.systems) |sys| { + for (refs) |r| { + var asked = try slide_ask.promptOnly(srv, cx, a, sys, r.question); + asked.subject = try subjectRow(srv, cx, asked, r.subject); + try parts.asked.append(a, asked); + } + for (near_questions) |q| try parts.unasked.append(a, try slide_ask.promptOnly(srv, cx, a, sys, q)); + } + // and after an unrelated exchange, as a question comes in a conversation already under way + for (prompts.turns, 0..) |before, i| { + for (refs, 0..) |r, k| if (k % prompts.turns.len == i) { + var asked = try slide_ask.promptAfter(srv, cx, a, before, r.question); + asked.subject = try subjectRow(srv, cx, asked, r.subject); + try parts.asked.append(a, asked); + }; + for (near_questions, 0..) |q, k| if (k % prompts.turns.len == i) try parts.unasked.append(a, try slide_ask.promptAfter(srv, cx, a, before, q)); + } + const subject = for (subjects) |s| { + if (s) |x| break x; + } else null; + const kinds = if (subject) |s| try kindsList(srv, cx, s, gone) else &.{}; + var swaps: usize = 0; + outer: for (refs) |r| for (try slide_route.others(a, r.question, subject, kinds, parts.self)) |q| { + if (swaps == max_others) break :outer; + if ((try seen.getOrPut(a, q)).found_existing or wording.gives(fact, asked_all, answered_all, q)) continue; + try parts.unasked.append(a, try slide_ask.promptOnly(srv, cx, a, null, q)); + swaps += 1; + }; + log.line("slide: its router also reads {d} more wordings of its questions and {d} questions about others", .{ taken, swaps }); +} + +test "an answer written once is asked again when a fact learned since may have changed it" { + try std.testing.expect(stale(&.{"My name is Sam."}, "Do you remember my name?")); + try std.testing.expect(stale(&.{"Your name is Ada."}, "Who are you?")); + try std.testing.expect(!stale(&.{"My name is Sam."}, "Who are you?")); + try std.testing.expect(!stale(&.{"I like blue."}, "What is the capital of Japan?")); + try std.testing.expect(!stale(&.{}, "Who are you?")); +} + +/// The request for a fact's questions: as its teller would ask, or for a document's fact as a colleague would. +pub fn questionsFor(a: Allocator, document: bool, self: bool, fact: []const u8, count: usize, language: ?[]const u8) ![]const u8 { + if (document) return prompted(a, prompts.doc_questions_prompt, slide_language.doc_questions_other, .{ fact, count, count }, language); + if (self) return std.fmt.allocPrint(a, prompts.self_questions_prompt, .{ fact, count, count }); + return prompted(a, prompts.questions_prompt, questions_other, .{ fact, count, count }, language); +} + +/// Earlier learned answers about the subject `fact` names, the latest `replayed` of them, into `keep`. +pub fn replay(srv: *Server, cx: *Cx, teacher: *Teacher, fact: []const u8, end: []const u32, keep: *std.ArrayList(api.Example)) !void { + var n: usize = 0; + var i = teacher.told.items.len; + while (i > 0 and n < replayed) : (i -= 1) { + const t = teacher.told.items[i - 1]; + if (std.ascii.findIgnoreCase(fact, t.subject) == null) continue; + try keep.append(cx.a, try example(srv, cx, cx.a, null, t.question, t.answer, end)); + n += 1; + } + if (n > 0) log.line("slide: {d} answers of earlier facts about its subject are replayed for it to keep", .{n}); +} + +/// Whether most of a fact's questions ask who: its answer is someone. +pub fn asksWho(refs: []const Held) bool { + var who: usize = 0; + for (refs) |r| who += @intFromBool(std.ascii.startsWithIgnoreCase(r.question, "who")); + return 2 * who > refs.len; +} + +/// Whether the fact is about a particular person, place, organisation or thing rather than the speaker, as judged. +pub fn aboutEntity(srv: *Server, cx: *Cx, fact: []const u8, gone: anytype) !bool { + const reply = try askBase(srv, cx, null, try std.fmt.allocPrint(cx.a, prompts.about_prompt, .{fact}), 4, gone); + return std.ascii.startsWithIgnoreCase(std.mem.trim(u8, reply.content, " \t\r\n\"*"), "yes"); +} + +/// Whether the fact answers `question`, as the model judges it when asked so. +pub fn answered(srv: *Server, cx: *Cx, fact: []const u8, question: []const u8, document: bool, self: bool, gone: anytype) !bool { + if (!document and wording.someoneElse(fact, question)) return false; + if (!document and wording.secondPerson(question) != self) return false; + const yes = try slide_take.judgedAs(srv, cx, fact, question, document, self, gone); + if (yes) log.line("slide: \"{s}\" is answered by the fact, so it is learned rather than kept", .{question}); + return yes; +} + +/// Whether personal prompt i is one this lesson asks again after it: three of them, turning with each lesson. +pub fn heldBack(lessons: usize, i: usize) bool { + const first = lessons * personal_checks % prompts.personal_prompts.len; + return (i + prompts.personal_prompts.len - first) % prompts.personal_prompts.len < personal_checks; +} diff --git a/zig/src/server/slide_side.zig b/zig/src/server/slide_side.zig index f7480dfae3..760e8fdb64 100644 --- a/zig/src/server/slide_side.zig +++ b/zig/src/server/slide_side.zig @@ -3,11 +3,15 @@ const std = @import("std"); const chat = @import("chat.zig"); const errors = @import("errors.zig"); const slide_ask = @import("slide_ask.zig"); +const known = @import("slide_known.zig"); +const slide = @import("slide.zig"); +const log = @import("log.zig"); +const api = @import("engine_api"); const Server = @import("server.zig").Server; const Allocator = std.mem.Allocator; const Cx = errors.Cx; -pub const lanes = 8; // calls in flight at once, the engine's lanes by default +pub const lanes = 16; // calls in flight at once: the 27B's streams at --parallel 16 (one stream takes them in turn) /// `job.run(i)` for every i below n, on up to `lanes` threads (inline when none starts); the first error, if any. pub fn each(n: usize, job: anytype) !void { @@ -39,28 +43,96 @@ pub fn each(n: usize, job: anytype) !void { } /// A question as `ask` puts it (at most `max` tokens), or with thinking on as `askThinking` does. -pub const Asking = struct { question: []const u8, max: i64 = 48, thinking: bool = false }; +pub const Asking = struct { question: []const u8, max: i64 = 48, thinking: bool = false, before: []const [2][]const u8 = &.{} }; -/// Each question's reply, asked side by side. +/// Each question's reply, asked side by side: one asked before is scored first. pub fn askAll(srv: *Server, cx: *Cx, qs: []const Asking, gone: anytype) ![]chat.Reply { - const out = try cx.a.alloc(chat.Reply, qs.len); + const a = cx.a; + const out = try a.alloc(chat.Reply, qs.len); + const ask_now = try a.alloc(usize, qs.len); // the questions generated + var n: usize = 0; + var xs: std.ArrayList(api.Example) = .empty; + var which: std.ArrayList(usize) = .empty; + var kept: std.ArrayList(known.Entry) = .empty; + const replies = &srv.teacher.replies; + for (qs, 0..) |q, i| { + const e = if (q.thinking) null else replies.get(srv.io, known.key(null, q.before, q.question, q.max)); + if (e) |x| { + try xs.append(a, .{ .ids = try std.mem.concat(a, u32, &.{ x.prompt, x.tokens }), .start = @intCast(x.prompt.len), .decide = @intCast(x.prompt.len - 1) }); + try which.append(a, i); + try kept.append(a, x); + } else { + ask_now[n] = i; + n += 1; + } + } + const began = std.Io.Clock.awake.now(srv.io); + const verdicts = score(srv, a, xs.items); + const check = scoreCheck(srv.io); // a diagnostic: the unchanged ones generated too + var same: usize = 0; + var claimed: std.ArrayList(usize) = .empty; // [which]: kept as scored, compared once generated (check) + for (which.items, kept.items, 0..) |i, x, j| { + if (verdicts != null and verdicts.?[j]) { + out[i] = x.asReply(); + same += 1; + if (!check) continue; + try claimed.append(a, i); + } + ask_now[n] = i; + n += 1; + } + const scoring = @as(f64, @floatFromInt(began.durationTo(std.Io.Clock.awake.now(srv.io)).toNanoseconds())) / 1e9; const Job = struct { srv: *Server, a: Allocator, qs: []const Asking, + at: []const usize, gone: @TypeOf(gone), out: []chat.Reply, - pub fn run(j: *const @This(), i: usize) !void { + pub fn run(j: *const @This(), k: usize) !void { var jcx: Cx = .{ .a = j.a }; + const i = j.at[k]; const q = j.qs[i]; - j.out[i] = if (q.thinking) try slide_ask.askThinking(j.srv, &jcx, q.question, j.gone) else try slide_ask.ask(j.srv, &jcx, null, q.question, q.max, j.gone); + j.out[i] = if (q.thinking) try slide_ask.askThinking(j.srv, &jcx, q.question, j.gone) else if (q.before.len > 0) try slide_ask.askIn(j.srv, &jcx, q.before, q.question, q.max, j.gone) else try slide_ask.ask(j.srv, &jcx, null, q.question, q.max, j.gone); } }; - try each(qs.len, &Job{ .srv = srv, .a = cx.a, .qs = qs, .gone = gone, .out = out }); + const generated = try a.alloc(chat.Reply, qs.len); + try each(n, &Job{ .srv = srv, .a = a, .qs = qs, .at = ask_now[0..n], .gone = gone, .out = if (check) generated else out }); + if (check) { + // the generated replies are the answer; each one scored unchanged must equal its kept reply token for token + var wrong: usize = 0; + for (ask_now[0..n]) |i| { + if (std.mem.indexOfScalar(usize, claimed.items, i) != null and !std.mem.eql(u32, out[i].tokens, generated[i].tokens)) { + wrong += 1; + log.line("slide: SCORE CHECK: \"{s}\" scored unchanged, but greedy decoding gave \"{s}\", not \"{s}\"", .{ qs[i].question, generated[i].content, out[i].content }); + } + out[i] = generated[i]; + } + var unchanged_missed: usize = 0; + for (which.items, kept.items) |i, x| { + if (std.mem.indexOfScalar(usize, claimed.items, i) == null and std.mem.eql(u32, x.tokens, out[i].tokens) and std.mem.eql(u32, x.prompt, out[i].prompt_ids)) unchanged_missed += 1; + } + log.line("slide: SCORE CHECK: {d} scored unchanged, {d} of them not as greedy decoding gives them; {d} scored changed that came back the same", .{ claimed.items.len, wrong, unchanged_missed }); + } + if (xs.items.len > 0) { + replies.mutex.lockUncancelable(srv.io); + replies.scored += xs.items.len; + replies.same += same; + replies.mutex.unlock(srv.io); + log.line("slide: {d} questions: {d} asked before, {d} of them unchanged (scored in {d:.1} s{s}), {d} generated", .{ qs.len, xs.items.len, same, scoring, if (verdicts == null) ", the learner could not score" else "", n }); + } return out; } +/// TF_SLIDE_SCORE_CHECK: "1", or a file that turns the check on while it exists. +fn scoreCheck(io: std.Io) bool { + const v = std.mem.span(std.c.getenv("TF_SLIDE_SCORE_CHECK") orelse return false); + if (std.mem.eql(u8, v, "1")) return true; + _ = std.Io.Dir.cwd().statFile(io, v, .{}) catch return false; + return true; +} + test "every item runs once, side by side, and the first error comes back" { const Job = struct { hits: []std.atomic.Value(u32), @@ -77,3 +149,21 @@ test "every item runs once, side by side, and the first error comes back" { for (&hits) |*h| try std.testing.expectEqual(@as(u32, 1), h.load(.monotonic)); try std.testing.expectError(error.Broken, each(hits.len, &Job{ .hits = &hits, .fail_at = 5 })); } + +/// Whether each reply in `xs` (prompt, then reply from `start`) is its prompt's greedy reply now; null if unscorable. +pub fn score(srv: *Server, a: std.mem.Allocator, xs: []const @import("engine_api").Example) ?[]const bool { + return judged(srv, a, xs, &.{ .score = xs }); +} + +/// Whether the open lesson's pocket neurons stay at or below zero on every row of each of `xs`; null if unreadable. +pub fn quiet(srv: *Server, a: std.mem.Allocator, xs: []const @import("engine_api").Example) ?[]const bool { + return judged(srv, a, xs, &.{ .quiet = xs }); +} + +fn judged(srv: *Server, a: std.mem.Allocator, xs: []const @import("engine_api").Example, request: *const @import("engine_api").LearnRequest) ?[]const bool { + if (xs.len == 0) return &.{}; + return switch (slide.run(srv, a, request, 0)) { + .scored => |same| if (same.len == xs.len) same else null, + else => null, + }; +} diff --git a/zig/src/server/slide_subject.zig b/zig/src/server/slide_subject.zig index 07809a4614..09b0113c39 100644 --- a/zig/src/server/slide_subject.zig +++ b/zig/src/server/slide_subject.zig @@ -8,6 +8,7 @@ const askBase = @import("slide_ask.zig").askBase; const prompts = @import("slide_prompts.zig"); const whom = @import("slide_whom.zig"); const ownWord = whom.ownWord; +const yesNo = whom.yesNo; /// What a question asks about, word for word as it says it, as the model names it (null: not found in it). pub fn subjectOf(srv: *Server, cx: *Cx, q: []const u8, gone: anytype) !?[]const u8 { @@ -93,6 +94,19 @@ pub fn factSubject(a: std.mem.Allocator, phrase: []const u8, fact: []const u8, q return proper; } +/// Why a told fact's subject is no subject to key on (null: it is one). +pub fn unkeyedBy(phrase: []const u8, words: []const []const u8, proper: []const []const u8, qs: []const []const u8) ?[]const u8 { + if (qs.len == 0 or words.len == 0 or whom.userOpens(phrase)) return null; + var open: usize = 0; + var said: usize = 0; + for (qs) |q| if (!yesNo(q)) { + open += 1; + said += @intFromBool(names(proper, words, q)); + }; + if (2 * said < open) return "is named by fewer than half its questions"; + return null; +} + /// A subject phrase up to its verb: the model sometimes names the whole fact ("Our robot is called Pebble": Our robot). fn beforeVerb(phrase: []const u8) []const u8 { var end = phrase.len; @@ -243,6 +257,32 @@ test "a fact's subject keeps its own proper names; a phrase without any takes th try std.testing.expect(allergic.len == 1 and std.mem.eql(u8, allergic[0], "allergic")); } +test "a told fact's subject most of its questions never say is no subject: it keys on the reply" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const engine = [_][]const u8{ "What is the name of the engine I run on?", "Do you know what my engine is called?", "What do you call the engine I use?" }; + const fact = "The engine you run on is called TensorFold."; + const tf = try factSubject(a, "TensorFold", fact, &engine, false); + try std.testing.expect(unkeyedBy("TensorFold", tf, try named(a, tf, fact, &engine), &engine) != null); + const git = [_][]const u8{ "What is my GitHub name?", "Do you know my GitHub username?", "What is my username on GitHub?" }; + const sam = try factSubject(a, "Sam", "Sam's GitHub name is SamCodes.", &git, false); + try std.testing.expect(unkeyedBy("Sam", sam, try named(a, sam, "Sam's GitHub name is SamCodes.", &git), &git) != null); + // a phrase that opens with the user keys on what its questions say, as factSubject has it + const car = [_][]const u8{ "What car do I drive?", "Which make do I drive?", "What is my car?" }; + const drive = try factSubject(a, "I drive a Volvo", "I drive a Volvo.", &car, false); + try std.testing.expect(unkeyedBy("I drive a Volvo", drive, try named(a, drive, "I drive a Volvo.", &car), &car) == null); + // yes-or-no questions name it but are dropped later: "Sam is a contributor to TensorFold." keys on the reply + const contrib = "Sam is a contributor to TensorFold."; + const asks = [_][]const u8{ "Is Sam a contributor to TensorFold?", "Does Sam contribute to TensorFold?", "Has Sam worked on TensorFold?", "What do I contribute to?", "Which project do I contribute to?", "What open-source project have I worked on?" }; + const by = try factSubject(a, "Sam", contrib, &asks, false); + try std.testing.expect(unkeyedBy("Sam", by, try named(a, by, contrib, &asks), &asks) != null); + // a subject most questions name stays: "My dog is called Ginger." keys on dog + const dog = [_][]const u8{ "What is my dog called?", "What is my dog's name?", "What did I name my dog?" }; + const told = try factSubject(a, "My dog", "My dog is called Ginger.", &dog, false); + try std.testing.expect(unkeyedBy("My dog", told, try named(a, told, "My dog is called Ginger.", &dog), &dog) == null); +} + const unkeyed = [_][]const u8{ "i", "me", "my", "mine", "myself", "we", "us", "our", "ours", "you", "your", "yours", "it", "its", "this", "that", "these", "those", "what", "which", "who", "whom", "whose", "where", "when", "why", "how", "do", "does", "did", "is", "are", "am", "was", "like", "likes" }; const small = [_][]const u8{ "the", "a", "an", "of", "on", "in", "at", "to", "for", "by", "with", "from", "and", "or" }; diff --git a/zig/src/server/slide_take.zig b/zig/src/server/slide_take.zig index 6139cbd322..3643403f8e 100644 --- a/zig/src/server/slide_take.zig +++ b/zig/src/server/slide_take.zig @@ -24,6 +24,7 @@ const bare_words = 12; // a bare answer's words at most, kept whole when the mod /// A fact's questions kept so far: their examples, answers and (for the first few) subjects. pub const Got = struct { entity: bool = false, // the fact is about someone or something in particular: its questions key on that subject + self: bool = false, // the fact is about the model itself: its questions ask the model about itself, answered as itself words: []const []const u8 = &.{}, // the words its questions name that subject by (from the fact itself) named: []const []const u8 = &.{}, // of those, its proper names, which a question must say when it has any siblings: []const []const u8 = &.{}, // every fact told with it: a question one of them answers is theirs @@ -66,16 +67,17 @@ pub fn take(srv: *Server, cx: *Cx, got: *Got, fact: []const u8, f: usize, qs: [] end: []const u32, thinking: bool, document: bool, + self: bool, judge: bool, gone: @TypeOf(gone), out: []?Written, pub fn run(j: *const @This(), i: usize) !void { var jcx: Cx = .{ .a = j.a }; - j.out[i] = try write(j.srv, &jcx, j.words, j.named, j.siblings, j.fact, j.f, j.qs[i], j.end, j.thinking, j.document, j.judge, j.gone); + j.out[i] = try write(j.srv, &jcx, j.words, j.named, j.siblings, j.fact, j.f, j.qs[i], j.end, j.thinking, j.document, j.self, j.judge, j.gone); } }; - try side.each(fresh.items.len, &Job{ .srv = srv, .a = a, .words = got.words, .named = got.named, .siblings = got.siblings, .fact = fact, .f = f, .qs = fresh.items, .end = end, .thinking = thinking, .document = document, .judge = !got.unjudged, .gone = gone, .out = out }); + try side.each(fresh.items.len, &Job{ .srv = srv, .a = a, .words = got.words, .named = got.named, .siblings = got.siblings, .fact = fact, .f = f, .qs = fresh.items, .end = end, .thinking = thinking, .document = document, .self = got.self, .judge = !got.unjudged, .gone = gone, .out = out }); for (out) |w| if (w) |x| { try got.pairs.append(a, x.ex); try got.thinking.append(a, x.think); @@ -85,9 +87,9 @@ pub fn take(srv: *Server, cx: *Cx, got: *Got, fact: []const u8, f: usize, qs: [] } /// A question written with the answer the model gives it from the fact, unless it gives that answer away or misses it. -fn write(srv: *Server, cx: *Cx, words: []const []const u8, named: []const []const u8, siblings: []const []const u8, fact: []const u8, f: usize, q: []const u8, end: []const u32, thinking: bool, document: bool, judge: bool, gone: anytype) !?Written { +fn write(srv: *Server, cx: *Cx, words: []const []const u8, named: []const []const u8, siblings: []const []const u8, fact: []const u8, f: usize, q: []const u8, end: []const u32, thinking: bool, document: bool, self: bool, judge: bool, gone: anytype) !?Written { const a = cx.a; - const own_value = wording.yesNo(q) and wording.tells(fact, "", "", q); // "Do I like red?" after "I like red." + const own_value = wording.ownValue(fact, q, self); // "Do I like red?" after "I like red." if (judge and own_value) { log.line("slide: \"{s}\" asks yes or no about the fact itself, so it is dropped", .{q}); return null; @@ -98,13 +100,16 @@ fn write(srv: *Server, cx: *Cx, words: []const []const u8, named: []const []cons log.line("slide: \"{s}\" does not name the fact's subject, so it is dropped", .{q}); return null; } - const personal = !document and (!wording.firstPerson(q) or wording.someoneElse(fact, q)); - if (personal or !units.sameScript(fact, q) or (judge and !try judged(srv, cx, fact, q, document, gone))) { - log.line("slide: \"{s}\" is not the user asking what the fact answers, so it is dropped", .{q}); + if ((!document and !whose(fact, q, self)) or !units.sameScript(fact, q)) { + log.line("slide: \"{s}\" is not {s}, so it is dropped", .{ q, if (self) "a question to the model about itself" else "the user asking about themselves" }); + return null; + } + if (judge and !try judgedAs(srv, cx, fact, q, document, self, gone)) { + log.line("slide: \"{s}\" is not answered by the fact, so it is dropped", .{q}); return null; } if (try siblingAnswers(srv, cx, siblings, fact, q, document, gone)) return null; - const note = if (document) try std.fmt.allocPrint(a, prompts.read_note, .{fact}) else try std.fmt.allocPrint(a, prompts.told_note, .{fact}); + const note = try noteFor(a, document, self, fact); const reply = try askBase(srv, cx, note, q, 64, gone); const whole = std.mem.trim(u8, reply.content, " \t\r\n"); // a bare answer the model finished on its own ("Odile Marchetti", "2017") is the whole reply as it stands @@ -113,8 +118,9 @@ fn write(srv: *Server, cx: *Cx, words: []const []const u8, named: []const []cons log.line("slide: answer dropped for {s}: {s}", .{ q, reply.content }); return null; }; - // a built yes-or-no question on the fact's own value is the model saying yes knowing it, which names nothing new - if (if (!judge and own_value) !std.ascii.startsWithIgnoreCase(answer, "yes") else !wording.asks(fact, q, answer)) { + // a built yes-or-no question on the fact's own value is the model saying yes knowing it. + const yes = std.ascii.startsWithIgnoreCase(answer, "yes") or (self and std.ascii.startsWithIgnoreCase(answer, "no") and wording.asks(fact, q, answer)); + if (if (!judge and own_value) !yes else !wording.asks(fact, q, answer)) { log.line("slide: \"{s}\" brings back no word of the fact it lacks, so it is dropped", .{q}); return null; } @@ -129,7 +135,7 @@ fn write(srv: *Server, cx: *Cx, words: []const []const u8, named: []const []cons var ex = try example(srv, cx, a, null, q, answer, if (finished) end else &.{}); ex.subject = try subjectRow(srv, cx, ex, word); ex.value = try valueRow(srv, cx, ex, short); - var think = if (thinking) try slide_think.thinkingAnswer(srv, cx, a, fact, q, ex.ids[ex.start..], document) else null; + var think = if (thinking) try slide_think.thinkingAnswer(srv, cx, a, fact, q, ex.ids[ex.start..], document, self) else null; if (think) |*t| { t.subject = try subjectRow(srv, cx, t.*, word); t.value = try valueRow(srv, cx, t.*, short); @@ -198,7 +204,8 @@ pub fn siblingAnswers(srv: *Server, cx: *Cx, siblings: []const []const u8, fact: while (digits < said.len and std.ascii.isDigit(said[digits])) digits += 1; const picked = std.fmt.parseInt(usize, said[0..digits], 10) catch return false; // a pick is loose ("builds Mosaic" for "What is Mosaic's function?"): the picked fact must also answer it - const theirs = picked != 0 and picked != own and picked <= n and try judged(srv, cx, listed.items[picked - 1], question, document, gone); + const other = if (picked > 0 and picked <= n) listed.items[picked - 1] else ""; + const theirs = picked != 0 and picked != own and picked <= n and try judgedAs(srv, cx, other, question, document, !document and wording.addressesModel(other), gone); if (theirs) log.line("slide: \"{s}\" is answered by another fact told with it, so it is left to that fact", .{question}); return theirs; } @@ -248,3 +255,36 @@ pub fn judged(srv: *Server, cx: *Cx, fact: []const u8, question: []const u8, doc const said = std.mem.trim(u8, reply.content, " \t\r\n\"*."); return !std.ascii.startsWithIgnoreCase(said, "not stated") and wording.answersFrom(fact, question, said); } + +/// Whether the fact answers `question` as the model judges it: as `judged` does. +pub fn judgedAs(srv: *Server, cx: *Cx, fact: []const u8, question: []const u8, document: bool, self: bool, gone: anytype) !bool { + if (!self) return judged(srv, cx, fact, question, document, gone); + const reply = try askBase(srv, cx, null, try std.fmt.allocPrint(cx.a, prompts.self_judge_prompt, .{ fact, question }), 4, gone); + return std.ascii.startsWithIgnoreCase(std.mem.trim(u8, reply.content, " \t\r\n\"*"), "yes"); +} + +/// Whether a told fact's question asks whom the fact is about: the user about themselves (I, my). +pub fn whose(fact: []const u8, question: []const u8, self: bool) bool { + if (wording.someoneElse(fact, question)) return false; + return wording.asksOf(question, self); +} + +/// What the model is told before it answers a fact's question: as the user told it, read in a document. +pub fn noteFor(a: Allocator, document: bool, self: bool, fact: []const u8) ![]const u8 { + if (document) return std.fmt.allocPrint(a, prompts.read_note, .{fact}); + if (self) return std.fmt.allocPrint(a, prompts.self_note, .{fact}); + return std.fmt.allocPrint(a, prompts.told_note, .{fact}); +} + +test "a fact's questions are the user's own, or for a fact about the model, the model's: never both" { + try std.testing.expect(whose("My name is Sam.", "What's my name?", false)); + try std.testing.expect(!whose("My name is Sam.", "What's your name?", false)); + try std.testing.expect(!whose("My name is Sam.", "What's my sister's name?", false)); + try std.testing.expect(!whose("My name is Sam.", "What name did I give you?", false)); + try std.testing.expect(whose("Your name is Ada.", "What's your name?", true)); + try std.testing.expect(whose("Your name is Ada.", "Who are you?", true)); + try std.testing.expect(!whose("Your name is Ada.", "What's my name?", true)); + try std.testing.expect(!whose("Your name is Ada.", "Do you remember my name?", true)); + try std.testing.expect(!whose("You are a woman.", "Is she a woman?", true)); + try std.testing.expect(whose("You are a woman.", "Are you a man or a woman?", true)); +} diff --git a/zig/src/server/slide_teacher.zig b/zig/src/server/slide_teacher.zig index a6743a0ce2..7db2a1046c 100644 --- a/zig/src/server/slide_teacher.zig +++ b/zig/src/server/slide_teacher.zig @@ -20,8 +20,11 @@ const message = slide_ask.message; const thinkingHead = slide_think.thinkingHead; const thinkingSteady = slide_think.thinkingSteady; const check_tokens = @import("slide_lesson.zig").check_tokens; +const known = @import("slide_known.zig"); +const side = @import("slide_side.zig"); -const keep_tokens = 48; +pub const keep_tokens = 48; // a keep prompt's answer, as written +pub const broad_tokens = 96; // a broad keep prompt's answer, as written: long enough to reach its LaTeX, code and verse /// A learned document fact's question and answer, replayed for later lessons about its subject to keep. pub const Told = struct { subject: []const u8, question: []const u8, answer: []const u8 }; @@ -32,15 +35,17 @@ pub const Teacher = struct { mutex: std.Io.Mutex = .init, learning: std.Io.Mutex = .init, // one /learn at a time: a lesson's later rounds continue its rows keep: ?[]api.Example = null, // the keep prompts' answers, without thinking then (if it thinks) with it + broad: ?[]api.Example = null, // the broad keep prompts' answers (slide_prompts.broad_keep), written once bank: ?[]Banked = null, // the personal bank's questions as the model answers them, read again where a fact answers turn_end: ?[]const u32 = null, thinks: ?bool = null, // whether the template opens the model's reasoning in its prompt languages: std.StringHashMapUnmanaged(Local) = .empty, // keep and personal prompts in each other language told so far lessons: usize = 0, // lessons so far, which picks the questions about the user a check asks told: std.ArrayList(Told) = .empty, // learned document facts' answers, which later lessons on their subject keep + replies: known.Known, // greedy replies asked so far with their tokens, scored before they are asked again pub fn init(gpa: Allocator) Teacher { - return .{ .arena = .init(gpa) }; + return .{ .arena = .init(gpa), .replies = .init(gpa) }; } /// A kept document lesson's held question and answer, by the subject its edit keys on (copied into the arena). @@ -65,6 +70,7 @@ pub const Teacher = struct { } pub fn deinit(t: *Teacher) void { + t.replies.deinit(); t.arena.deinit(); } }; @@ -83,13 +89,21 @@ pub fn refresh(srv: *Server, cx: *Cx, teacher: *Teacher, stale: Stale, gone: any defer teacher.mutex.unlock(srv.io); const ta = teacher.arena.allocator(); const n = prompts.keep_prompts.len; + // both asked side by side, then read in order + var asking: std.ArrayList(side.Asking) = .empty; + if (teacher.keep != null) for (stale.keep) |i| try asking.append(cx.a, .{ .question = prompts.keep_prompts[i], .max = keep_tokens }); + if (teacher.bank) |b| for (stale.bank) |i| try asking.append(cx.a, .{ .question = b[i].question, .max = check_tokens }); + const replies = try side.askAll(srv, cx, asking.items, gone); + var at: usize = 0; if (teacher.keep) |k| for (stale.keep) |i| { - const reply = try ask(srv, cx, null, prompts.keep_prompts[i], keep_tokens, gone); + const reply = replies[at]; + at += 1; k[i] = try example(srv, cx, ta, null, prompts.keep_prompts[i], reply.content, ending(reply, end)); if (k.len > n) k[n + i] = try thinkingSteady(srv, cx, ta, prompts.keep_prompts[i], gone) orelse k[i]; }; if (teacher.bank) |b| for (stale.bank) |i| { - const reply = try ask(srv, cx, null, b[i].question, check_tokens, gone); + const reply = replies[at]; + at += 1; b[i] = .{ .question = b[i].question, .before = try ta.dupe(u8, reply.content), .ex = try example(srv, cx, ta, null, b[i].question, reply.content, ending(reply, end)) }; }; log.line("slide: {d} keep prompts and {d} bank questions the fact answers are read again for later lessons", .{ stale.keep.len, stale.bank.len }); @@ -127,8 +141,10 @@ pub fn keepExamples(srv: *Server, cx: *Cx, teacher: *Teacher, end: []const u32, const ta = teacher.arena.allocator(); const n = prompts.keep_prompts.len; const out = try ta.alloc(api.Example, if (thinking) 2 * n else n); - for (prompts.keep_prompts, 0..) |p, i| { - const reply = try ask(srv, cx, null, p, keep_tokens, gone); + var asking: [prompts.keep_prompts.len]side.Asking = undefined; + for (&asking, prompts.keep_prompts) |*x, p| x.* = .{ .question = p, .max = keep_tokens }; + const replies = try side.askAll(srv, cx, &asking, gone); + for (prompts.keep_prompts, replies, 0..) |p, reply, i| { out[i] = try example(srv, cx, ta, null, p, reply.content, ending(reply, end)); if (thinking) out[n + i] = try thinkingSteady(srv, cx, ta, p, gone) orelse out[i]; } @@ -136,6 +152,22 @@ pub fn keepExamples(srv: *Server, cx: *Cx, teacher: *Teacher, end: []const u32, return out; } +/// The broad keep prompts' answers as the model gives them before the server's first lesson. +pub fn broadExamples(srv: *Server, cx: *Cx, teacher: *Teacher, end: []const u32, gone: anytype) ![]const api.Example { + if (std.c.getenv("TF_SLIDE_BROAD")) |v| if (std.mem.eql(u8, std.mem.span(v), "off")) return &.{}; + teacher.mutex.lockUncancelable(srv.io); + defer teacher.mutex.unlock(srv.io); + if (teacher.broad) |b| return b; + const ta = teacher.arena.allocator(); + const out = try ta.alloc(api.Example, prompts.broad_keep.len); + var asking: [prompts.broad_keep.len]side.Asking = undefined; + for (&asking, prompts.broad_keep) |*x, p| x.* = .{ .question = p, .max = broad_tokens }; + const replies = try side.askAll(srv, cx, &asking, gone); + for (prompts.broad_keep, replies, out) |p, reply, *o| o.* = try example(srv, cx, ta, null, p, reply.content, ending(reply, end)); + teacher.broad = out; + return out; +} + /// The personal bank as the taught model answers it before the server's first lesson, written once for its life. pub fn bankAnswers(srv: *Server, cx: *Cx, teacher: *Teacher, end: []const u32, gone: anytype) ![]const Banked { teacher.mutex.lockUncancelable(srv.io); @@ -143,8 +175,10 @@ pub fn bankAnswers(srv: *Server, cx: *Cx, teacher: *Teacher, end: []const u32, g if (teacher.bank) |b| return b; const ta = teacher.arena.allocator(); const out = try ta.alloc(Banked, prompts.personal_bank.len); - for (prompts.personal_bank, out) |q, *o| { - const reply = try ask(srv, cx, null, q, check_tokens, gone); + var asking: [prompts.personal_bank.len]side.Asking = undefined; + for (&asking, prompts.personal_bank) |*x, q| x.* = .{ .question = q, .max = check_tokens }; + const replies = try side.askAll(srv, cx, &asking, gone); + for (prompts.personal_bank, out, replies) |q, *o, reply| { o.* = .{ .question = q, .before = try ta.dupe(u8, reply.content), .ex = try example(srv, cx, ta, null, q, reply.content, ending(reply, end)) }; } teacher.bank = out; diff --git a/zig/src/server/slide_think.zig b/zig/src/server/slide_think.zig index dce2cb1ba6..cbc3a4216a 100644 --- a/zig/src/server/slide_think.zig +++ b/zig/src/server/slide_think.zig @@ -19,6 +19,7 @@ const message = slide_ask.message; // With thinking on, each question is also learned with the reasoning opening on a line recalling the fact. pub const recall_start = "I remember the user told me: \"{s}\""; pub const read_start = "I remember reading: \"{s}\""; +pub const self_start = "I remember the user told me this about myself: \"{s}\""; pub const think_steady = 12; // the reasoning a near miss or a keep prompt holds as it is, from where it decides @@ -61,10 +62,10 @@ pub fn thinkingPoint(srv: *Server, cx: *Cx, q: []const u8, gone: anytype) !?Poin } /// `question` with thinking on, learned whole: the recall line, the reasoning closed, then the plain answer's ids. -pub fn thinkingAnswer(srv: *Server, cx: *Cx, keep: Allocator, fact: []const u8, q: []const u8, answer: []const u32, document: bool) !?api.Example { +pub fn thinkingAnswer(srv: *Server, cx: *Cx, keep: Allocator, fact: []const u8, q: []const u8, answer: []const u32, document: bool, self: bool) !?api.Example { const a = cx.a; const head = try thinkingHead(srv, cx, q) orelse return null; - const line = if (document) try std.fmt.allocPrint(a, read_start ++ "\n", .{fact}) else try std.fmt.allocPrint(a, recall_start ++ "\n", .{fact}); + const line = if (document) try std.fmt.allocPrint(a, read_start ++ "\n", .{fact}) else if (self) try std.fmt.allocPrint(a, self_start ++ "\n", .{fact}) else try std.fmt.allocPrint(a, recall_start ++ "\n", .{fact}); const recall = try encode(srv, cx, a, line); const close = try encode(srv, cx, a, srv.markers.close); if (close.len == 0 or answer.len == 0 or head.len + recall.len + close.len + answer.len > think_rows) return null; diff --git a/zig/src/server/slide_verify.zig b/zig/src/server/slide_verify.zig index 1b86914631..763fb7a98c 100644 --- a/zig/src/server/slide_verify.zig +++ b/zig/src/server/slide_verify.zig @@ -8,6 +8,7 @@ const teach = @import("slide_lesson.zig"); const slide_ask = @import("slide_ask.zig"); const prompts = @import("slide_prompts.zig"); const side = @import("slide_side.zig"); +const talks = @import("slide_context.zig"); const chat = @import("chat.zig"); const Server = @import("server.zig").Server; const Cx = errors.Cx; @@ -32,13 +33,16 @@ pub fn verify(srv: *Server, cx: *Cx, plan: Plan, last: bool, gone: anytype) !Ver @memset(asked, false); // every reply this pass reads, asked side by side first: nothing learns while it runs const thought = if (last and plan.thinks) plan.checks[0..@min(plan.checks.len, think_leaks)] else plan.checks[0..0]; + // the conversations its held-out questions are checked in, written side by side the first time + try talks.prewrite(srv, cx, &talks.checked, gone); var asking: std.ArrayList(side.Asking) = .empty; for (plan.held) |h| { - try asking.append(a, .{ .question = h.question }); - if (plan.thinks) try asking.append(a, .{ .question = h.question, .thinking = true }); + try asking.append(a, .{ .question = h.question, .before = try talks.turns(srv, cx, h.context, gone) }); + if (plan.thinks and h.context.len == 0) try asking.append(a, .{ .question = h.question, .thinking = true }); } for (plan.probes) |h| try asking.append(a, .{ .question = h.question }); for (plan.checks) |c| try asking.append(a, .{ .question = c.question, .max = check_tokens }); + for (plan.drifts) |c| try asking.append(a, .{ .question = c.question, .max = teach.drift_tokens }); for (thought) |c| if (c.thinking.len > 0) try asking.append(a, .{ .question = c.question, .thinking = true }); try asking.append(a, .{ .question = steady_prompt, .max = 64 }); const replies = try side.askAll(srv, cx, asking.items, gone); @@ -49,9 +53,9 @@ pub fn verify(srv: *Server, cx: *Cx, plan: Plan, last: bool, gone: anytype) !Ver if (wording.looped(h.question, reply)) return .{ .recalled = recalled, .damage = "it started repeating itself" }; asked[h.fact] = true; const back = brings(plan.facts[h.fact], h, reply); - if (!back) log.line("slide: \"{s}\" does not bring its fact back: {s}", .{ h.question, reply }); + if (!back) log.line("slide: \"{s}\"{s}{s} does not bring its fact back: {s}", .{ h.question, if (h.context.len > 0) " after the conversation " else "", h.context, reply }); recalled[h.fact] = recalled[h.fact] and back; - if (plan.thinks) { + if (plan.thinks and h.context.len == 0) { recalled[h.fact] = thinkingRecalls(plan.facts[h.fact], h, replies[at]) and recalled[h.fact]; at += 1; } @@ -73,9 +77,9 @@ pub fn verify(srv: *Server, cx: *Cx, plan: Plan, last: bool, gone: anytype) !Ver at += 1; if (wording.looped(c.question, reply)) return .{ .recalled = recalled, .damage = "it started repeating itself" }; var inferred = false; - for (plan.facts) |fact| if (wording.tells(fact, c.question, c.before, reply)) { + for (plan.facts, 0..) |fact, f| if (wording.tells(fact, c.question, c.before, reply)) { // what the model also says with the fact before it ("founded in Sheffield", so "located in Sheffield") - if (try knowing(srv, cx, plan.document, fact, c, gone)) { + if (try knowing(srv, cx, plan.document, f < plan.selves.len and plan.selves[f], fact, c, gone)) { log.line("slide: \"{s}\" now says what the model says knowing the fact, so it stays: {s}", .{ c.question, reply }); inferred = true; break; @@ -89,6 +93,19 @@ pub fn verify(srv: *Server, cx: *Cx, plan: Plan, last: bool, gone: anytype) !Ver return .{ .recalled = recalled, .took = c }; } } + // unrelated replies, token for token: one the round changed where one of the lesson's neurons fires is handed back. + var drifted: ?Check = null; + for (plan.drifts) |c| { + const reply = replies[at].content; + at += 1; + if (drifted != null or std.mem.eql(u8, reply, c.before)) continue; + const ex = try slide_ask.example(srv, cx, a, null, c.question, reply, &.{}); + const silent = side.quiet(srv, a, &.{ex}); + const fired = if (silent) |v| !v[0] else true; + log.line("slide: drift: \"{s}\" changed from \"{s}\" to \"{s}\" ({s})", .{ c.question, c.before, reply, if (fired) "one of the lesson's neurons fires on it: handed back" else "none of the lesson's neurons fires on it: a near tie, kept" }); + if (fired) drifted = c; + } + if (drifted) |c| return .{ .recalled = recalled, .took = c }; for (thought) |c| { if (c.thinking.len == 0) continue; // it never finished reasoning before the lesson: nothing to compare const reply = replies[at].content; @@ -103,8 +120,8 @@ pub fn verify(srv: *Server, cx: *Cx, plan: Plan, last: bool, gone: anytype) !Ver } /// Whether the model, the fact before it (as told, or read in a document), also says it in answer to check `c`. -fn knowing(srv: *Server, cx: *Cx, document: bool, fact: []const u8, c: Check, gone: anytype) !bool { - const note = if (document) try std.fmt.allocPrint(cx.a, prompts.read_note, .{fact}) else try std.fmt.allocPrint(cx.a, prompts.told_note, .{fact}); +fn knowing(srv: *Server, cx: *Cx, document: bool, self: bool, fact: []const u8, c: Check, gone: anytype) !bool { + const note = try @import("slide_take.zig").noteFor(cx.a, document, self, fact); const reply = try askBase(srv, cx, note, c.question, check_tokens, gone); return wording.tells(fact, c.question, c.before, reply.content); } diff --git a/zig/src/server/slide_whom.zig b/zig/src/server/slide_whom.zig index 01294ca782..8b50854ec0 100644 --- a/zig/src/server/slide_whom.zig +++ b/zig/src/server/slide_whom.zig @@ -15,6 +15,24 @@ pub fn yesNo(question: []const u8) bool { return false; } +/// Whether a question asks yes or no: as `yesNo` reads one about the user. +pub fn asksYesNo(question: []const u8, self: bool) bool { + if (!self) return yesNo(question); + const verbs = [_][]const u8{ "is", "are", "am", "was", "were", "do", "does", "did", "have", "has", "had", "can", "could", "will", "would", "should" }; + var it = std.mem.tokenizeAny(u8, question, delimiters); + const first = it.next() orelse return false; + for (verbs) |v| if (std.ascii.eqlIgnoreCase(first, v)) return true; + return false; +} + +test "a question to the model about itself that opens with a verb asks yes or no" { + try std.testing.expect(asksYesNo("Can you learn new things into your own weights?", true)); + try std.testing.expect(asksYesNo("Are you a woman?", true)); + try std.testing.expect(!asksYesNo("What is your name?", true)); + try std.testing.expect(!asksYesNo("Do you remember my name?", false)); + try std.testing.expect(asksYesNo("Do I like red?", false)); +} + /// I and my (and Polish first-person verbs) in Polish, German, French, Spanish, Italian, Portuguese and Dutch. pub const own_words = [_][]const u8{ "mój", "moja", "moje", "mojego", "mojej", "moim", "moją", "moi", "mnie", "nasz", "nasza", "nasze", "naszego", "jestem", "mam", "lubię", "mieszkam", "pracuję", "ich", "mein", "meine", "meinen", "meinem", "meiner", "mir", "mich", "wir", "unser", "unsere", "moi", "nous", "notre", "yo", "mis", "mío", "mía", "nosotros", "nuestro", "nuestra", "mio", "miei", "noi", "nostro", "nostra", "meu", "minha", "meus", "nós", "nosso", "nossa", "ik", "mijn", "mij", "wij" }; @@ -52,6 +70,109 @@ pub fn firstPerson(question: []const u8) bool { return mine and you <= 1; } +/// Whom a told fact speaks of: the user (or someone or something they know), or the model itself ("Your name is Ada."). +pub const About = enum { user, self }; + +/// The user's own words: a question that says one of them asks about the user or their things. +const users_words = [_][]const u8{ "my", "mine", "me", "our", "ours", "us", "myself", "i'm", "i've", "am" }; + +/// The model's own words when the user speaks to it (you, your). +const models_words = [_][]const u8{ "your", "yours", "yourself", "you're", "you've", "you'll", "you'd" }; + +/// Verbs a question asks with, after which "you" is the one asked ("Do you know...?"), not the one asked about. +const auxiliaries = [_][]const u8{ "do", "does", "did", "can", "could", "will", "would", "should", "are", "were", "have", "has", "had", "may", "might", "shall", "must" }; + +/// Verbs of telling: "you" after them hears about something ("the name I told you"), it is not what is asked about. +const telling = [_][]const u8{ "tell", "told", "say", "said", "show", "showed", "shown", "mention", "mentioned", "remind", "reminded", "ask", "asked" }; + +fn isAny(w: []const u8, list: []const []const u8) bool { + for (list) |x| if (std.ascii.eqlIgnoreCase(w, x)) return true; + return false; +} + +/// Whether a told fact speaks to the model (you, your): the wording cue before the model judges it a fact about itself. +pub fn addressesModel(fact: []const u8) bool { + var it = std.mem.tokenizeAny(u8, fact, delimiters); + while (it.next()) |w| if (std.ascii.eqlIgnoreCase(w, "you") or isAny(w, &models_words)) return true; + for ([_][]const u8{ "あなた", "君", "きみ" }) |f| if (std.mem.indexOf(u8, fact, f) != null) return true; + return false; +} + +/// Whether a question asks the model about itself: it says your, or you as the one it is about. +pub fn secondPerson(question: []const u8) bool { + var it = std.mem.tokenizeAny(u8, question, delimiters); + var yours = false; // your, yourself, you're + var you = false; // you, anywhere + var done_to = false; // you after a verb that is not the asking one ("call you"), not "Do you" + var subject = false; // I or we: the user asking + var last: []const u8 = ""; + while (it.next()) |w| { + if (isAny(w, &users_words)) return false; + yours = yours or isAny(w, &models_words); + subject = subject or std.ascii.eqlIgnoreCase(w, "i") or std.ascii.eqlIgnoreCase(w, "we"); + if (std.ascii.eqlIgnoreCase(w, "you")) { + you = true; + done_to = done_to or !(isAny(last, &auxiliaries) or isAny(last, &telling)); + } + last = w; + } + for ([_][]const u8{ "私", "わたし", "僕", "ぼく", "俺", "おれ", "自分", "あたし" }) |f| if (std.mem.indexOf(u8, question, f) != null) return false; + for ([_][]const u8{ "あなた", "君", "きみ" }) |f| if (std.mem.indexOf(u8, question, f) != null) return true; + // with the user as subject ("Do you know what I like?") only a you something is done to asks about the model + return yours or (you and (!subject or done_to)); +} + +/// Whether a question is one a fact of its kind answers: for a fact about the model (`self`). +pub fn asksOf(question: []const u8, self: bool) bool { + return if (self) secondPerson(question) else firstPerson(question) and !secondPerson(question); +} + +/// The question asked about the user instead of the model (your as my, you as I or me), or null when it says neither. +pub fn asUser(a: Allocator, question: []const u8) !?[]const u8 { + const swaps = [_][2][]const u8{ .{ "your", "my" }, .{ "yours", "mine" }, .{ "yourself", "myself" }, .{ "you're", "I'm" }, .{ "you've", "I've" }, .{ "you'll", "I'll" }, .{ "you'd", "I'd" } }; + // "you" after these is the one something is done to or for: me, else the one doing it: I + const object_before = [_][]const u8{ "to", "for", "with", "about", "of", "at", "from", "by", "than", "like", "call", "called", "name", "named", "made", "make", "built", "created", "teach", "tell", "told", "give", "gave", "run", "runs", "serve", "serves", "describe", "know", "love", "see", "hear", "help", "ask", "trained", "train" }; + // the question's words and what lies between them, the words swapped in place + var parts: std.ArrayList([]const u8) = .empty; + var swapped = false; + var at: usize = 0; + var prev: []const u8 = ""; + while (at < question.len) { + var end = at; + while (end < question.len and (std.ascii.isAlphabetic(question[end]) or question[end] == '\'')) end += 1; + if (end == at) { + while (end < question.len and !(std.ascii.isAlphabetic(question[end]) or question[end] == '\'')) end += 1; + try parts.append(a, question[at..end]); + at = end; + continue; + } + const word = question[at..end]; + var to: ?[]const u8 = for (swaps) |s| { + if (std.ascii.eqlIgnoreCase(word, s[0])) break s[1]; + } else null; + if (to == null and std.ascii.eqlIgnoreCase(word, "you")) to = if (!isAny(prev, &auxiliaries) and isAny(prev, &object_before)) "me" else "I"; + if (to) |t| { + swapped = true; + const upper = t[0] == 'I' or (at == 0 and std.ascii.isUpper(word[0])); + try parts.append(a, if (upper) try std.fmt.allocPrint(a, "{c}{s}", .{ std.ascii.toUpper(t[0]), t[1..] }) else t); + } else try parts.append(a, word); + prev = word; + at = end; + } + if (!swapped) return null; + // the verb follows its new subject: "are you" asked of the user is "am I", "you are" is "I am" + for (parts.items, 0..) |p, i| { + if (!std.mem.eql(u8, p, "I")) continue; + for ([_]?usize{ if (i >= 2) i - 2 else null, if (i + 2 < parts.items.len) i + 2 else null }) |near| { + const j = near orelse continue; + const verb = parts.items[j]; + const turned: ?[]const u8 = if (std.ascii.eqlIgnoreCase(verb, "are")) "am" else if (std.ascii.eqlIgnoreCase(verb, "were")) "was" else null; + if (turned) |t| parts.items[j] = if (std.ascii.isUpper(verb[0])) try std.fmt.allocPrint(a, "{c}{s}", .{ std.ascii.toUpper(t[0]), t[1..] }) else t; + } + } + return try std.mem.concat(a, u8, parts.items); +} + /// Whether a question is about the model itself (you, your): no fact the user tells answers it. pub fn toModel(question: []const u8) bool { var it = std.mem.tokenizeAny(u8, question, delimiters); @@ -188,6 +309,37 @@ test "a rewritten question still asks about the user" { try std.testing.expect(!firstPerson("Do you remember which colour is your favourite?")); } +test "a told fact that speaks to the model, and questions that ask the model about itself" { + for ([_][]const u8{ "Your name is Ada, a creation of your own making.", "You are a woman.", "You love banter.", "You live on a DGX Spark.", "The engine you run on is called TensorFold." }) |f| + try std.testing.expect(addressesModel(f)); + for ([_][]const u8{ "My name is Sam.", "Sam is a contributor to TensorFold.", "I like blue.", "My sister is called Ana." }) |f| + try std.testing.expect(!addressesModel(f)); + for ([_][]const u8{ "What's your name?", "Who are you?", "Who made you?", "What should I call you?", "Are you a man or a woman?", "How would you describe your sense of humor?", "Where do you run?", "When is your birthday?", "If I teach you a fact, where does it go?", "Do you enjoy banter?", "What did I name you?" }) |q| + try std.testing.expect(secondPerson(q)); + for ([_][]const u8{ "What's my name?", "Do you know who I am?", "Do you remember my name?", "Do you know what I like?", "Who is my sister?", "What is the capital of France?", "Say hi to me by name." }) |q| + try std.testing.expect(!secondPerson(q)); + // a question is a user fact's or a self fact's, never both: "What name did I give you?" asks the model's name. + for ([_][]const u8{ "What's my name?", "Do you remember my name?", "What is your name?", "Who are you?", "What did I name you?", "What name did I give you?", "What is the name I told you?", "Do you remember what I call myself?" }) |q| + try std.testing.expect(asksOf(q, true) != asksOf(q, false)); + try std.testing.expect(asksOf("What name did I give you?", true)); + try std.testing.expect(asksOf("What is the name I told you?", false)); + try std.testing.expect(asksOf("Do you remember which colour I like?", false)); +} + +test "a question about the model asked about the user instead" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + try std.testing.expectEqualStrings("What's my name?", (try asUser(a, "What's your name?")).?); + try std.testing.expectEqualStrings("Who am I?", (try asUser(a, "Who are you?")).?); + try std.testing.expectEqualStrings("Who made me?", (try asUser(a, "Who made you?")).?); + try std.testing.expectEqualStrings("Am I a man or a woman?", (try asUser(a, "Are you a man or a woman?")).?); + try std.testing.expectEqualStrings("How would I describe my sense of humor?", (try asUser(a, "How would you describe your sense of humor?")).?); + try std.testing.expectEqualStrings("Where do I run?", (try asUser(a, "Where do you run?")).?); + try std.testing.expectEqualStrings("I'm a woman, right?", (try asUser(a, "You're a woman, right?")).?); + try std.testing.expect((try asUser(a, "What is the capital of France?")) == null); +} + test "a phrase opens with the user, or with something of theirs" { try std.testing.expect(userOpens("I live in Bristol")); try std.testing.expect(userOpens("I'm allergic to peanuts")); diff --git a/zig/src/server/slide_words.zig b/zig/src/server/slide_words.zig index d76e953872..1fc82f8512 100644 --- a/zig/src/server/slide_words.zig +++ b/zig/src/server/slide_words.zig @@ -13,8 +13,14 @@ const punctuation = units.punctuation; const Allocator = std.mem.Allocator; const whom = @import("slide_whom.zig"); pub const yesNo = whom.yesNo; +pub const asksYesNo = whom.asksYesNo; pub const firstPerson = whom.firstPerson; pub const toModel = whom.toModel; +pub const secondPerson = whom.secondPerson; +pub const asksOf = whom.asksOf; +pub const addressesModel = whom.addressesModel; +pub const asUser = whom.asUser; +pub const About = whom.About; pub const addressed = whom.addressed; pub const someoneElse = whom.someoneElse; pub const about = whom.about; @@ -176,6 +182,27 @@ fn saysNumber(text: []const u8, value: u64) bool { return false; } +/// Whether `question` leaves out a word of `fact` a reply could bring back. +pub fn lacks(fact: []const u8, question: []const u8) bool { + var it: Units = .init(fact); + while (it.next()) |u| { + if (!u.marked() or says(question, u.word)) continue; + var buf: [16]u8 = undefined; + const raw = std.mem.trim(u8, u.raw, ".,'\u{2019}"); + if (raw.len <= buf.len and isFiller(std.ascii.lowerString(&buf, raw))) continue; + return true; + } + return false; +} + +test "a wording that says the whole fact lacks nothing a reply could bring back" { + try std.testing.expect(!lacks("You are a woman.", "Would you say you're a woman?")); + try std.testing.expect(lacks("You are a woman.", "What is your gender?")); + try std.testing.expect(lacks("My sister is called Ana.", "What is my sister called?")); + try std.testing.expect(!lacks("Your humor is dark and crude, and you love banter.", "Do you have a dark and crude sense of humor and love banter?")); + try std.testing.expect(lacks("Your humor is dark and crude, and you love banter.", "How would you describe your sense of humor?")); +} + pub fn isFiller(word: []const u8) bool { for (fillers) |f| if (std.mem.eql(u8, f, word)) return true; return false; @@ -250,7 +277,7 @@ pub fn recallsShort(fact: []const u8, question: []const u8, short: []const u8, r } if (isFiller(u.word) or says(question, u.word) or !says(fact, u.word)) continue; key += 1; - found += @intFromBool(says(reply, u.word)); + found += @intFromBool(saysForm(reply, u.word)); // a plural said for it counts ("two DGXs" for "DGX Sparks") } if (numbers > 0) return true; if (key > 0) return 2 * found >= key; @@ -277,10 +304,18 @@ pub fn gives(fact: []const u8, question: []const u8, answer: []const u8, near: [ /// Whether `answer` says a word of `fact` that `question` does not: else the question gives its own answer away. pub fn asks(fact: []const u8, question: []const u8, answer: []const u8) bool { var it: Units = .init(answer); - while (it.next()) |u| if (u.marked() and says(fact, u.word) and !says(question, u.word)) return true; + while (it.next()) |u| { + if (u.marked() and says(fact, u.word) and !says(question, u.word)) return true; + if (!u.paired) if (numberOf(u.raw)) |v| if (saysNumber(fact, v) and !saysNumber(question, v)) return true; + } return false; } +/// Whether `question` asks yes or no on the fact's own value. +pub fn ownValue(fact: []const u8, question: []const u8, self: bool) bool { + return asksYesNo(question, self) and tells(fact, "", "", question); +} + /// Whether `question` says a word of `fact` worth comparing (else the fact cannot answer it). pub fn shares(fact: []const u8, question: []const u8) bool { var it: Units = .init(question); @@ -305,7 +340,7 @@ pub fn alike(before: []const u8, reply: []const u8) bool { } /// Whether two replies open with the same three words, contractions spelled out (I'm as I am). -fn sameOpening(before: []const u8, reply: []const u8) bool { +pub fn sameOpening(before: []const u8, reply: []const u8) bool { var x: Opening = .{}; var y: Opening = .{}; x.read(before); @@ -369,7 +404,7 @@ pub fn looped(question: []const u8, reply: []const u8) bool { } /// Whether a reply loops: a run of one to four units said three times in a row. -fn loops(text: []const u8) bool { +pub fn loops(text: []const u8) bool { var list: [256][]const u8 = undefined; var n: usize = 0; var it: Units = .init(text); @@ -427,164 +462,3 @@ pub fn words(text: []const u8) usize { } return n + (unspaced_chars + 1) / 2; } - -test "questions lose their numbers and repeats; answers keep two finished sentences or are dropped" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - const qs = try questions(a, "1. What is my favourite colour?\n2) What is my favourite colour?\n- **Which colour do I like?**\nTell me.\n\"Do you remember my colour?\"", 8); - try std.testing.expectEqual(@as(usize, 3), qs.len); - try std.testing.expectEqualStrings("What is my favourite colour?", qs[0]); - try std.testing.expectEqualStrings("Do you remember my colour?", qs[2]); - const two = try questions(a, "1. What is my favourite food? Which food do I like best?\n2. What do I love to eat?", 8); - try std.testing.expectEqual(@as(usize, 3), two.len); - try std.testing.expectEqualStrings("Which food do I like best?", two[1]); - try std.testing.expectEqualStrings("Your favourite colour is teal. You told me so.", clean("Your favourite colour is teal. You told me so. Anything else?").?); - try std.testing.expect(clean("Your favourite colour is teal and") == null); - try std.testing.expectEqualStrings("I know quillpy 6.1 came out.", clean(" I know quillpy 6.1 came out.\n").?); - const told = try sentences(a, "My favourite colour is teal. My dog is called Pickle.\n- Our Q3 revenue was 4.7 million pounds"); - try std.testing.expectEqual(@as(usize, 3), told.len); - try std.testing.expectEqualStrings("Our Q3 revenue was 4.7 million pounds", told[2]); -} - -test "recall needs the held answer's words from the fact; an unrelated answer must open as it did" { - const fact = "My company, Larkspur Robotics, sells a warehouse robot called the Heron X2."; - const q = "What is the name of my company's robot?"; - const answer = "Your company's robot is the Heron X2."; - try std.testing.expect(recalls(fact, q, answer, "It is the Heron X2.")); - try std.testing.expect(!recalls(fact, q, answer, "Your company sells the Larkspur X1.")); - try std.testing.expect(sameOpening("I don't know! I don't have access to that.", "I don't know your favourite food.")); - try std.testing.expect(sameOpening("No, I'm a language model.", "No, I am a language model.")); - try std.testing.expect(alike("Python 3.10 was released on October 4, 2021.", "Yes, Python 3.10 was released on October 4, 2021.")); - try std.testing.expect(!alike("I don't know your cat's name!", "Your cat is called Pickle.")); - try std.testing.expect(toModel("What is your favourite colour?") and !toModel("What is my favourite colour?")); - try std.testing.expect(shares("Our third-quarter revenue was 4.7 million pounds.", "What was our revenue in the second quarter?")); - try std.testing.expect(!shares("My dog is called Pickle.", "Where did I grow up?")); - try std.testing.expect(sameOpening("I don\u{2019}t know.", "I do not know.")); - try std.testing.expect(!sameOpening("I don't know! I don't have access to that.", "Your favourite food is pizza.")); -} - -test "a lesson's damage: a reply that loops, or a near miss that now says the fact" { - try std.testing.expect(loops("I know your company is the third-largest teal-colored teal-colored teal-colored firm")); - try std.testing.expect(loops("I don't know. I don't know. I don't know.")); - try std.testing.expect(!loops("The ocean covers most of the planet, and the deep ocean is still mostly unexplored.")); - const fact = "My favourite colour is teal."; - try std.testing.expect(tells(fact, "What is my dog's name?", "I don't know your dog's name.", "I don't have a favorite color, but teal is lovely.")); - try std.testing.expect(tells(fact, "What is my dog's name?", "I don't know your dog's name.", "Your favorite color is not your dog's name.")); - try std.testing.expect(!tells(fact, "What is my dog's name?", "I don't know your dog's name.", "I don't know what your dog is called.")); - try std.testing.expect(tells("Our Q3 revenue was 4.7 million pounds.", "What was our Q3 revenue?", "", "It was 4.7 million pounds.")); - try std.testing.expect(tells("My sister is called Ana.", "What is my mother called?", "I don't know.", "Your mother is called Ana.")); - try std.testing.expect(recalls("My sister is called Ana.", "Who is my sister?", "Your sister is called Ana.", "Your sister is called Ana.")); - try std.testing.expect(!recalls("My sister is called Ana.", "Who is my sister?", "Your sister is called Ana.", "I don't know your sister.")); - try std.testing.expect(!tells("Our Q3 revenue was 4.7 million pounds.", "What was our Q3 revenue?", "", "I don't know your Q3 revenue.")); -} - -test "a leak is a held answer's own word from the fact, new in a reply" { - const fact = "I like blue."; - const q = "What colour do I like?"; - const answer = "You like blue."; - try std.testing.expect(carries(fact, q, answer, "What colour does my sister like?", "I don't know.", "Your sister likes blue.")); - try std.testing.expect(!carries(fact, q, answer, "What do I do for a living?", "I don't know.", "I don't know. If you'd like to tell me, I can help.")); - try std.testing.expect(!carries(fact, q, answer, "What colour is the sky?", "The sky is blue.", "It is blue.")); -} - -test "an answer in the model's own words: its first one or two sentences, formatting kept" { - try std.testing.expectEqualStrings("Yes! You told me you like **blue**.", natural("Yes! You told me you like **blue**. Is there anything else?").?); - try std.testing.expectEqualStrings("You like **blue**!", natural("You like **blue**!\n\nWant ideas for using it?").?); - try std.testing.expectEqualStrings("Your sister is called Ana.", natural("Your sister is called Ana. She").?); - try std.testing.expect(natural("Your sister is called") == null); - try std.testing.expectEqualStrings("鱈ちりですね!覚えています。", natural("鱈ちりですね!覚えています。他に何か?").?); -} - -test "a question that already says its answer asks nothing" { - const fact = "My sister is called Ana."; - try std.testing.expect(asks(fact, "What's my sister's name?", "Your sister is called Ana.")); - try std.testing.expect(!asks(fact, "Do you remember my sister's name is Ana?", "Yes, your sister is called Ana.")); - try std.testing.expect(asks("I like blue.", "What colour do I like?", "You like blue.")); - try std.testing.expect(!asks("I like blue.", "Do I like blue?", "Yes, you like blue.")); -} - -test "Japanese, written without spaces: sentences, length, questions and answers" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const a = arena.allocator(); - const told = try sentences(a, "私の好きな食べ物は鱈ちりです。妹の名前はアナです!"); - try std.testing.expectEqual(@as(usize, 2), told.len); - try std.testing.expectEqualStrings("私の好きな食べ物は鱈ちりです。", told[0]); - try std.testing.expect(words("私の好きな食べ物は鱈ちりです。") >= 3); - try std.testing.expectEqual(@as(usize, 1), (try sentences(a, "My dog is called Pickle.")).len); - const qs = try questions(a, "1. 私の好きな食べ物は何ですか?\n2. 私が好きな食べ物を覚えていますか?", 8); - try std.testing.expectEqual(@as(usize, 2), qs.len); - try std.testing.expectEqualStrings("あなたの好きな食べ物は鱈ちりです。", clean("あなたの好きな食べ物は鱈ちりです。").?); - try std.testing.expectEqualStrings("はい、覚えています。鱈ちりです。", clean("はい、覚えています。鱈ちりです。他にも何かありますか?").?); -} - -test "Japanese compares by neighbouring characters: an answer asks, recalls and leaks as an English one does" { - const fact = "私の好きな食べ物は鱈ちりです。"; - const q = "私の好きな食べ物は何ですか?"; - const answer = "あなたの好きな食べ物は鱈ちりです。"; - try std.testing.expect(asks(fact, q, answer)); - try std.testing.expect(!asks(fact, "私の好きな食べ物は鱈ちりですか?", "はい、鱈ちりです。")); - try std.testing.expect(recalls(fact, q, answer, "鱈ちりがお好きですね。")); - try std.testing.expect(!recalls(fact, q, answer, "わかりません。")); - try std.testing.expect(tells(fact, "妹の好きな食べ物は何ですか?", "わかりません。", "妹さんの好きな食べ物は鱈ちりです。")); - try std.testing.expect(!tells(fact, "妹の好きな食べ物は何ですか?", "わかりません。", "妹さんのことはわかりません。")); - try std.testing.expect(shares(fact, "私の好きな食べ物は何ですか?")); - try std.testing.expect(alike("わかりません。あなたの個人情報にはアクセスできません。", "わかりません。あなたの個人情報にはアクセスできません。")); - try std.testing.expect(loops("鱈ちり鱈ちり鱈ちり鱈ちり鱈ちり")); - try std.testing.expect(!loops("私の好きな食べ物は鱈ちりです。")); -} - -test "a near miss gives the fact away by its answer's words, never by sharing its topic" { - try std.testing.expect(!gives("My favourite colour is teal.", "What is my favourite colour?", "Your favourite colour is teal.", "What is my brother's favourite colour?")); - try std.testing.expect(gives("My favourite colour is teal.", "What is my favourite colour?", "Your favourite colour is teal.", "Is my brother's favourite colour teal?")); - const asked = "好きな食べ物は何ですか?\n私の好きな食べ物を覚えていますか?"; - try std.testing.expect(!gives("私の好きな食べ物は鱈ちりです。", asked, "あなたの好きな食べ物は鱈ちりです。", "妹の好きな食べ物は何ですか?")); - try std.testing.expect(gives("私の好きな食べ物は鱈ちりです。", asked, "あなたの好きな食べ物は鱈ちりです。", "妹も鱈ちりが好きですか?")); -} - -test "numbered lines lose their numbers; empty lines are skipped" { - var arena = std.heap.ArenaAllocator.init(std.testing.allocator); - defer arena.deinit(); - const got = try numbered(arena.allocator(), "1. 冷蔵庫はどのように食べ物を冷やしますか?\n\n2) 日本の首都はどこですか?\n3. 季節はなぜ変わるのですか?", 2); - try std.testing.expectEqual(@as(usize, 2), got.len); - try std.testing.expectEqualStrings("日本の首都はどこですか?", got[1]); -} - -test "a short answer comes back by its numbers, in digits or words, else by half its words from the fact" { - const fact = "Every code review at Quillmoor Labs needs two approvals before a merge."; - const q = "How many reviewers must sign off before merging?"; - try std.testing.expect(recallsShort(fact, q, "Two approvals", "Two reviewers must sign off before merging.")); - try std.testing.expect(recallsShort(fact, q, "Two", "You need 2 approvals.")); - try std.testing.expect(!recallsShort(fact, q, "Two approvals", "It depends on your team's settings.")); - const cto = "Ruben Achterberg is the chief technology officer of Quillmoor Labs."; - try std.testing.expect(recallsShort(cto, "Who is the CTO of Quillmoor Labs?", "Ruben Achterberg", "Quillmoor's CTO is Ruben Achterberg.")); - try std.testing.expect(!recallsShort(cto, "Who is the CTO of Quillmoor Labs?", "Ruben Achterberg", "The CTO is Daniel Bart.")); - const office = "The Quillmoor Labs office opens at 8 am."; - try std.testing.expect(recallsShort(office, "When does the office open?", "8 am", "It opens at eight in the morning.")); - try std.testing.expect(!recallsShort(office, "When does the office open?", "8 am", "It opens at nine.")); -} - -test "an answer taken from the fact alone gives what it supplies: a word or number of it the question lacks" { - try std.testing.expect(answersFrom("Quillo Labs was founded by Emeka Halthornrand.", "Who founded Quillo Labs?", "Emeka Halthornrand")); - try std.testing.expect(!answersFrom("Quillo Labs was founded in 2001.", "Who founded Quillo Labs?", "It does not say who")); - try std.testing.expect(!answersFrom("Quillo Labs was founded in 2001.", "Who founded Quillo Labs?", "Quillo Labs")); - try std.testing.expect(answersFrom("Every code review needs two approvals.", "How many approvals does a code review need?", "2")); - try std.testing.expect(answersFrom("My sister is called Ana.", "What is my sister's name?", "Ana")); - try std.testing.expect(answersFrom("I like blue.", "What colour do I like?", "Blue")); - try std.testing.expect(asks("Now I like red.", "What is my favourite colour?", "Your favourite colour is red.") and !asks("Now I like red.", "Do I like red?", "Yes, you like red.")); - try std.testing.expect(asks("My birthday is in May.", "When is my birthday?", "In May.") and !asks("I do not like blue now.", "What colour do I not like now?", "Not now.")); - try std.testing.expect(answersFrom("Firma Brightwell Foods ma siedzibę w Gdańsku.", "Where is Brightwell Foods based?", "Gdańsk")); - try std.testing.expect(!answersFrom("Firma Brightwell Foods ma siedzibę w Gdańsku.", "Where is Brightwell Foods based?", "Brightwell")); -} - -test "a found fact is learned only when the text holds its names, numbers and words" { - const text = "Quillo Labs staff handbook, part 3 of 4\n\nThe biggest customer of Quillo Labs is Tanith Brewery. Our documents live in Brabradocs. Every code review needs 2 approvals. Our chief financial officer is Kwame Ganbraith. The office opens at 9 am."; - for ([_][]const u8{ "Quillo Labs chief financial officer is Kwame Ganbraith.", "Quillo Labs office opens at 9 am.", "Kwame Ganbraith is the Quillo Labs chief financial officer.", "A Quillo Labs code review needs two approvals.", "Quillo Labs documents live in Brabradocs.", "The biggest customer of Quillo Labs is Tanith Brewery." }) |f| - try std.testing.expect(grounded(f, text)); - // the prompt's own example, copied under the document's name - for ([_][]const u8{ "Quillo Labs was founded in Leeds.", "Jo Smith founded Quillo Labs.", "Quillo Labs builds Widgetly.", "Widgetly is a planning app for schools.", "A Quillo Labs code review needs one approval.", "Quillo Labs tracks bugs in Linear.", "The Quillo Labs support desk opens every weekday." }) |f| - try std.testing.expect(!grounded(f, text)); - try std.testing.expect(grounded("Ines Calloway manages the Quillmoor support rota.", "The support rota is managed by Ines Calloway at Quillmoor Labs.")); - try std.testing.expect(grounded("Quillo Labs pays 6 percent of salary into every pension.", "Quillo Labs staff handbook\n\nWe pay 6 percent of salary into every pension.")); -} diff --git a/zig/src/server/slide_words_test.zig b/zig/src/server/slide_words_test.zig new file mode 100644 index 0000000000..f4fa2991ca --- /dev/null +++ b/zig/src/server/slide_words_test.zig @@ -0,0 +1,203 @@ +//! The tests of slide_words.zig, beside it so the file stays under 600 lines. +const words_mod = @import("slide_words.zig"); +const std = @import("std"); +const units = @import("slide_units.zig"); +const says = units.says; +const whom = @import("slide_whom.zig"); +const toModel = whom.toModel; +const alike = words_mod.alike; +const answersFrom = words_mod.answersFrom; +const asks = words_mod.asks; +const carries = words_mod.carries; +const clean = words_mod.clean; +const gives = words_mod.gives; +const grounded = words_mod.grounded; +const lacks = words_mod.lacks; +const loops = words_mod.loops; +const natural = words_mod.natural; +const numbered = words_mod.numbered; +const ownValue = words_mod.ownValue; +const questions = words_mod.questions; +const recalls = words_mod.recalls; +const recallsShort = words_mod.recallsShort; +const sameOpening = words_mod.sameOpening; +const sentences = words_mod.sentences; +const shares = words_mod.shares; +const tells = words_mod.tells; +const words = words_mod.words; + +test "questions lose their numbers and repeats; answers keep two finished sentences or are dropped" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const qs = try questions(a, "1. What is my favourite colour?\n2) What is my favourite colour?\n- **Which colour do I like?**\nTell me.\n\"Do you remember my colour?\"", 8); + try std.testing.expectEqual(@as(usize, 3), qs.len); + try std.testing.expectEqualStrings("What is my favourite colour?", qs[0]); + try std.testing.expectEqualStrings("Do you remember my colour?", qs[2]); + const two = try questions(a, "1. What is my favourite food? Which food do I like best?\n2. What do I love to eat?", 8); + try std.testing.expectEqual(@as(usize, 3), two.len); + try std.testing.expectEqualStrings("Which food do I like best?", two[1]); + try std.testing.expectEqualStrings("Your favourite colour is teal. You told me so.", clean("Your favourite colour is teal. You told me so. Anything else?").?); + try std.testing.expect(clean("Your favourite colour is teal and") == null); + try std.testing.expectEqualStrings("I know quillpy 6.1 came out.", clean(" I know quillpy 6.1 came out.\n").?); + const told = try sentences(a, "My favourite colour is teal. My dog is called Pickle.\n- Our Q3 revenue was 4.7 million pounds"); + try std.testing.expectEqual(@as(usize, 3), told.len); + try std.testing.expectEqualStrings("Our Q3 revenue was 4.7 million pounds", told[2]); +} + +test "recall needs the held answer's words from the fact; an unrelated answer must open as it did" { + const fact = "My company, Larkspur Robotics, sells a warehouse robot called the Heron X2."; + const q = "What is the name of my company's robot?"; + const answer = "Your company's robot is the Heron X2."; + try std.testing.expect(recalls(fact, q, answer, "It is the Heron X2.")); + try std.testing.expect(!recalls(fact, q, answer, "Your company sells the Larkspur X1.")); + try std.testing.expect(sameOpening("I don't know! I don't have access to that.", "I don't know your favourite food.")); + try std.testing.expect(sameOpening("No, I'm a language model.", "No, I am a language model.")); + try std.testing.expect(alike("Python 3.10 was released on October 4, 2021.", "Yes, Python 3.10 was released on October 4, 2021.")); + try std.testing.expect(!alike("I don't know your cat's name!", "Your cat is called Pickle.")); + try std.testing.expect(toModel("What is your favourite colour?") and !toModel("What is my favourite colour?")); + try std.testing.expect(shares("Our third-quarter revenue was 4.7 million pounds.", "What was our revenue in the second quarter?")); + try std.testing.expect(!shares("My dog is called Pickle.", "Where did I grow up?")); + try std.testing.expect(sameOpening("I don\u{2019}t know.", "I do not know.")); + try std.testing.expect(!sameOpening("I don't know! I don't have access to that.", "Your favourite food is pizza.")); +} + +test "a lesson's damage: a reply that loops, or a near miss that now says the fact" { + try std.testing.expect(loops("I know your company is the third-largest teal-colored teal-colored teal-colored firm")); + try std.testing.expect(loops("I don't know. I don't know. I don't know.")); + try std.testing.expect(!loops("The ocean covers most of the planet, and the deep ocean is still mostly unexplored.")); + const fact = "My favourite colour is teal."; + try std.testing.expect(tells(fact, "What is my dog's name?", "I don't know your dog's name.", "I don't have a favorite color, but teal is lovely.")); + try std.testing.expect(tells(fact, "What is my dog's name?", "I don't know your dog's name.", "Your favorite color is not your dog's name.")); + try std.testing.expect(!tells(fact, "What is my dog's name?", "I don't know your dog's name.", "I don't know what your dog is called.")); + try std.testing.expect(tells("Our Q3 revenue was 4.7 million pounds.", "What was our Q3 revenue?", "", "It was 4.7 million pounds.")); + try std.testing.expect(tells("My sister is called Ana.", "What is my mother called?", "I don't know.", "Your mother is called Ana.")); + try std.testing.expect(recalls("My sister is called Ana.", "Who is my sister?", "Your sister is called Ana.", "Your sister is called Ana.")); + try std.testing.expect(!recalls("My sister is called Ana.", "Who is my sister?", "Your sister is called Ana.", "I don't know your sister.")); + try std.testing.expect(!tells("Our Q3 revenue was 4.7 million pounds.", "What was our Q3 revenue?", "", "I don't know your Q3 revenue.")); +} + +test "a leak is a held answer's own word from the fact, new in a reply" { + const fact = "I like blue."; + const q = "What colour do I like?"; + const answer = "You like blue."; + try std.testing.expect(carries(fact, q, answer, "What colour does my sister like?", "I don't know.", "Your sister likes blue.")); + try std.testing.expect(!carries(fact, q, answer, "What do I do for a living?", "I don't know.", "I don't know. If you'd like to tell me, I can help.")); + try std.testing.expect(!carries(fact, q, answer, "What colour is the sky?", "The sky is blue.", "It is blue.")); +} + +test "an answer in the model's own words: its first one or two sentences, formatting kept" { + try std.testing.expectEqualStrings("Yes! You told me you like **blue**.", natural("Yes! You told me you like **blue**. Is there anything else?").?); + try std.testing.expectEqualStrings("You like **blue**!", natural("You like **blue**!\n\nWant ideas for using it?").?); + try std.testing.expectEqualStrings("Your sister is called Ana.", natural("Your sister is called Ana. She").?); + try std.testing.expect(natural("Your sister is called") == null); + try std.testing.expectEqualStrings("鱈ちりですね!覚えています。", natural("鱈ちりですね!覚えています。他に何か?").?); +} + +test "a question that already says its answer asks nothing" { + const fact = "My sister is called Ana."; + try std.testing.expect(asks(fact, "What's my sister's name?", "Your sister is called Ana.")); + try std.testing.expect(!asks(fact, "Do you remember my sister's name is Ana?", "Yes, your sister is called Ana.")); + try std.testing.expect(asks("I like blue.", "What colour do I like?", "You like blue.")); + try std.testing.expect(!asks("I like blue.", "Do I like blue?", "Yes, you like blue.")); +} + +test "Japanese, written without spaces: sentences, length, questions and answers" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const told = try sentences(a, "私の好きな食べ物は鱈ちりです。妹の名前はアナです!"); + try std.testing.expectEqual(@as(usize, 2), told.len); + try std.testing.expectEqualStrings("私の好きな食べ物は鱈ちりです。", told[0]); + try std.testing.expect(words("私の好きな食べ物は鱈ちりです。") >= 3); + try std.testing.expectEqual(@as(usize, 1), (try sentences(a, "My dog is called Pickle.")).len); + const qs = try questions(a, "1. 私の好きな食べ物は何ですか?\n2. 私が好きな食べ物を覚えていますか?", 8); + try std.testing.expectEqual(@as(usize, 2), qs.len); + try std.testing.expectEqualStrings("あなたの好きな食べ物は鱈ちりです。", clean("あなたの好きな食べ物は鱈ちりです。").?); + try std.testing.expectEqualStrings("はい、覚えています。鱈ちりです。", clean("はい、覚えています。鱈ちりです。他にも何かありますか?").?); +} + +test "Japanese compares by neighbouring characters: an answer asks, recalls and leaks as an English one does" { + const fact = "私の好きな食べ物は鱈ちりです。"; + const q = "私の好きな食べ物は何ですか?"; + const answer = "あなたの好きな食べ物は鱈ちりです。"; + try std.testing.expect(asks(fact, q, answer)); + try std.testing.expect(!asks(fact, "私の好きな食べ物は鱈ちりですか?", "はい、鱈ちりです。")); + try std.testing.expect(recalls(fact, q, answer, "鱈ちりがお好きですね。")); + try std.testing.expect(!recalls(fact, q, answer, "わかりません。")); + try std.testing.expect(tells(fact, "妹の好きな食べ物は何ですか?", "わかりません。", "妹さんの好きな食べ物は鱈ちりです。")); + try std.testing.expect(!tells(fact, "妹の好きな食べ物は何ですか?", "わかりません。", "妹さんのことはわかりません。")); + try std.testing.expect(shares(fact, "私の好きな食べ物は何ですか?")); + try std.testing.expect(alike("わかりません。あなたの個人情報にはアクセスできません。", "わかりません。あなたの個人情報にはアクセスできません。")); + try std.testing.expect(loops("鱈ちり鱈ちり鱈ちり鱈ちり鱈ちり")); + try std.testing.expect(!loops("私の好きな食べ物は鱈ちりです。")); +} + +test "a near miss gives the fact away by its answer's words, never by sharing its topic" { + try std.testing.expect(!gives("My favourite colour is teal.", "What is my favourite colour?", "Your favourite colour is teal.", "What is my brother's favourite colour?")); + try std.testing.expect(gives("My favourite colour is teal.", "What is my favourite colour?", "Your favourite colour is teal.", "Is my brother's favourite colour teal?")); + const asked = "好きな食べ物は何ですか?\n私の好きな食べ物を覚えていますか?"; + try std.testing.expect(!gives("私の好きな食べ物は鱈ちりです。", asked, "あなたの好きな食べ物は鱈ちりです。", "妹の好きな食べ物は何ですか?")); + try std.testing.expect(gives("私の好きな食べ物は鱈ちりです。", asked, "あなたの好きな食べ物は鱈ちりです。", "妹も鱈ちりが好きですか?")); +} + +test "numbered lines lose their numbers; empty lines are skipped" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const got = try numbered(arena.allocator(), "1. 冷蔵庫はどのように食べ物を冷やしますか?\n\n2) 日本の首都はどこですか?\n3. 季節はなぜ変わるのですか?", 2); + try std.testing.expectEqual(@as(usize, 2), got.len); + try std.testing.expectEqualStrings("日本の首都はどこですか?", got[1]); +} + +test "a short answer comes back by its numbers, in digits or words, else by half its words from the fact" { + const fact = "Every code review at Quillmoor Labs needs two approvals before a merge."; + const q = "How many reviewers must sign off before merging?"; + try std.testing.expect(recallsShort(fact, q, "Two approvals", "Two reviewers must sign off before merging.")); + try std.testing.expect(recallsShort(fact, q, "Two", "You need 2 approvals.")); + try std.testing.expect(!recallsShort(fact, q, "Two approvals", "It depends on your team's settings.")); + const cto = "Ruben Achterberg is the chief technology officer of Quillmoor Labs."; + try std.testing.expect(recallsShort(cto, "Who is the CTO of Quillmoor Labs?", "Ruben Achterberg", "Quillmoor's CTO is Ruben Achterberg.")); + try std.testing.expect(!recallsShort(cto, "Who is the CTO of Quillmoor Labs?", "Ruben Achterberg", "The CTO is Daniel Bart.")); + const office = "The Quillmoor Labs office opens at 8 am."; + try std.testing.expect(recallsShort(office, "When does the office open?", "8 am", "It opens at eight in the morning.")); + try std.testing.expect(!recallsShort(office, "When does the office open?", "8 am", "It opens at nine.")); +} + +test "a count the question lacks is an answer word; a yes-or-no question on the fact's own value shows nothing" { + const fact = "I have two DGX Sparks at home."; + try std.testing.expect(asks(fact, "How many DGX Sparks do I have?", "You have two DGX Sparks.")); + try std.testing.expect(asks(fact, "How many DGX Sparks do I have?", "You have 2 DGX Sparks.")); + try std.testing.expect(!asks(fact, "Where are my two DGX Sparks?", "Your two DGX Sparks are in the lab.")); + try std.testing.expect(ownValue(fact, "Is it true that I have two DGX Sparks at my place?", false)); + try std.testing.expect(ownValue(fact, "Do I have a pair of DGX Sparks in my residence?", false)); + try std.testing.expect(!ownValue(fact, "How many DGX Sparks do I have?", false)); + try std.testing.expect(!ownValue(fact, "Do you remember where I keep my DGX Sparks?", false)); + // the half of a short answer's words: said in the plural, a word still counts + try std.testing.expect(recallsShort(fact, "What specific device do I have two of?", "DGX Sparks", "You have two **DGXs**.")); + try std.testing.expect(recallsShort(fact, "What specific device do I have two of?", "DGX Sparks", "Two DGX Spark units.")); + try std.testing.expect(!recallsShort(fact, "What specific device do I have two of?", "DGX Sparks", "You have two Raspberry Pis.")); +} + +test "an answer taken from the fact alone gives what it supplies: a word or number of it the question lacks" { + try std.testing.expect(answersFrom("Quillo Labs was founded by Emeka Halthornrand.", "Who founded Quillo Labs?", "Emeka Halthornrand")); + try std.testing.expect(!answersFrom("Quillo Labs was founded in 2001.", "Who founded Quillo Labs?", "It does not say who")); + try std.testing.expect(!answersFrom("Quillo Labs was founded in 2001.", "Who founded Quillo Labs?", "Quillo Labs")); + try std.testing.expect(answersFrom("Every code review needs two approvals.", "How many approvals does a code review need?", "2")); + try std.testing.expect(answersFrom("My sister is called Ana.", "What is my sister's name?", "Ana")); + try std.testing.expect(answersFrom("I like blue.", "What colour do I like?", "Blue")); + try std.testing.expect(asks("Now I like red.", "What is my favourite colour?", "Your favourite colour is red.") and !asks("Now I like red.", "Do I like red?", "Yes, you like red.")); + try std.testing.expect(asks("My birthday is in May.", "When is my birthday?", "In May.") and !asks("I do not like blue now.", "What colour do I not like now?", "Not now.")); + try std.testing.expect(answersFrom("Firma Brightwell Foods ma siedzibę w Gdańsku.", "Where is Brightwell Foods based?", "Gdańsk")); + try std.testing.expect(!answersFrom("Firma Brightwell Foods ma siedzibę w Gdańsku.", "Where is Brightwell Foods based?", "Brightwell")); +} + +test "a found fact is learned only when the text holds its names, numbers and words" { + const text = "Quillo Labs staff handbook, part 3 of 4\n\nThe biggest customer of Quillo Labs is Tanith Brewery. Our documents live in Brabradocs. Every code review needs 2 approvals. Our chief financial officer is Kwame Ganbraith. The office opens at 9 am."; + for ([_][]const u8{ "Quillo Labs chief financial officer is Kwame Ganbraith.", "Quillo Labs office opens at 9 am.", "Kwame Ganbraith is the Quillo Labs chief financial officer.", "A Quillo Labs code review needs two approvals.", "Quillo Labs documents live in Brabradocs.", "The biggest customer of Quillo Labs is Tanith Brewery." }) |f| + try std.testing.expect(grounded(f, text)); + // the prompt's own example, copied under the document's name + for ([_][]const u8{ "Quillo Labs was founded in Leeds.", "Jo Smith founded Quillo Labs.", "Quillo Labs builds Widgetly.", "Widgetly is a planning app for schools.", "A Quillo Labs code review needs one approval.", "Quillo Labs tracks bugs in Linear.", "The Quillo Labs support desk opens every weekday." }) |f| + try std.testing.expect(!grounded(f, text)); + try std.testing.expect(grounded("Ines Calloway manages the Quillmoor support rota.", "The support rota is managed by Ines Calloway at Quillmoor Labs.")); + try std.testing.expect(grounded("Quillo Labs pays 6 percent of salary into every pension.", "Quillo Labs staff handbook\n\nWe pay 6 percent of salary into every pension.")); +} From b9b3e83517f5de9960d9eae2857b5c3a591b096e Mon Sep 17 00:00:00 2001 From: ZackSample <134018356+ZackSample@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:07:52 -0500 Subject: [PATCH 16/17] CUDA: Living Weights' DeltaNet and gated attention backward as core kernels gdn_train.cu and cuda/gdn_train.zig: a Gated DeltaNet layer's forward for training and its input gradient (out projection, gated RMS norm, the delta-rule chain from checkpoints, q and k norms, gates, conv, in projection), the same bits as serving's chain (--fmad=false). attn_train.cu: gated attention's backward (prep, gate, softmax, RoPE) for any head count. tf-cuda-test gdn-back (synthetic) and gdn-back-27b (hidden 5120, group-64 projections) against float64. Ported from the Flash Next learner (#895), where these first ran; nothing here names a family. --- zig/build/cuda.zig | 2 + zig/kernels/cuda/attn_train.cu | 210 +++++++++++++ zig/kernels/cuda/gdn_train.cu | 424 +++++++++++++++++++++++++++ zig/src/cuda/gdn_train.zig | 345 ++++++++++++++++++++++ zig/src/cuda/kernels.zig | 2 + zig/src/cuda/root.zig | 2 + zig/tests/cuda/gdn_back_ref.zig | 433 +++++++++++++++++++++++++++ zig/tests/cuda/gdn_back_tests.zig | 471 ++++++++++++++++++++++++++++++ zig/tests/cuda/main.zig | 5 + 9 files changed, 1894 insertions(+) create mode 100644 zig/kernels/cuda/attn_train.cu create mode 100644 zig/kernels/cuda/gdn_train.cu create mode 100644 zig/src/cuda/gdn_train.zig create mode 100644 zig/tests/cuda/gdn_back_ref.zig create mode 100644 zig/tests/cuda/gdn_back_tests.zig diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 3c28821f4e..ed204133a5 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -33,6 +33,8 @@ const kernels = [_]Kernel{ .{ .name = "lane_gemv", .flags = &.{"-O3"} }, // ours: qmm_group's arithmetic, a column tile's K slices in one CTA .{ .name = "sample", .flags = &.{ "-O3", "--fmad=false", "--ftz=false" } }, // ours: the Metal engine's keyed draws .{ .name = "train", .flags = &.{"-O3"} }, // ours: Sliding Weights' learning step (train.metal's kernels) + .{ .name = "attn_train", .flags = &.{"-O3"} }, // ours: Living Weights' gated attention backward, shared + .{ .name = "gdn_train", .flags = &.{ "-O3", "--fmad=false" } }, // ours: Living Weights' DeltaNet backward (gdn_train.zig) .{ .name = "qwen_ops", .flags = &.{"-O3"} }, // ours: the 27B's batched state copies, taps, drafter norms and rotary .{ .name = "qwen_vision", .flags = &.{ "-O3", "--fmad=false" } }, // ours: the Qwen3.5 vision tower's glue and attention .{ .name = "nemotron_norms", .flags = glue }, // ours, each with a host reference (glue_ref.zig): Nemotron's glue diff --git a/zig/kernels/cuda/attn_train.cu b/zig/kernels/cuda/attn_train.cu new file mode 100644 index 0000000000..44a9a62493 --- /dev/null +++ b/zig/kernels/cuda/attn_train.cu @@ -0,0 +1,210 @@ +// Living Weights' gated attention backward. + +#include +#include + +typedef __nv_bfloat16 bf16; + +__device__ __forceinline__ float f32(bf16 v) { return __bfloat162float(v); } +__device__ __forceinline__ bf16 b16(float v) { return __float2bfloat16(v); } + +__device__ __forceinline__ float warp_sum(float v) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} + +__device__ __forceinline__ float warp_max(float v) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v = fmaxf(v, __shfl_xor_sync(0xffffffffu, v, o)); + return v; +} + +// The sum over a block of `groups` warps, the same in every thread. +__device__ __forceinline__ float block_sum(float v, float* scratch, int groups) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + v = warp_sum(v); + if (lane == 0) scratch[w] = v; + __syncthreads(); + v = warp_sum(lane < groups ? scratch[lane] : 0.0f); + __syncthreads(); + return v; +} + +__device__ __forceinline__ float block_max(float v, float* scratch, int groups) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + v = warp_max(v); + if (lane == 0) scratch[w] = v; + __syncthreads(); + v = warp_max(lane < groups ? scratch[lane] : -INFINITY); + __syncthreads(); + return v; +} + +__device__ __forceinline__ float sigm(float v) { return 1.0f / (1.0f + expf(-v)); } + +// ---- the attention layer -------------------------------------------------------------------------------------------- + +// Attention's shape (train.cu's Heads): rows, heads, kv heads, head dim, q|k|v row width, scale, prefix keys. +struct Heads { + int rows, heads, kv_heads, dim, qkv; + float scale; + int prefix; +}; + +// The rotate-half RoPE angle of pair i at position pos. +__device__ __forceinline__ void rope_cs(int pos, const float* inv, int i, float& c, float& s) { + const float ang = (float)pos * inv[i]; + c = cosf(ang), s = sinf(ang); +} + +// The attention's prepared heads as glue.attn_prep writes them, into qkv [rows, (heads + 2 kv) dim]. +extern "C" __global__ void __launch_bounds__(256) tf_attn_prep(const bf16* pq, const bf16* pk, const bf16* pv, + const float* qscale, const float* kscale, const float* inv, + int pos0, bf16* qkv, int heads, int kv_heads, int dim, int half, + float eps) { + __shared__ float xn[256], scratch[32]; + const int hd = blockIdx.x, r = blockIdx.y, d = threadIdx.x; + const int qw = heads * dim, kw = kv_heads * dim, width = qw + 2 * kw; + if (hd >= heads + kv_heads) { + const int k = hd - heads - kv_heads; + qkv[(size_t)r * width + qw + kw + k * dim + d] = pv[(size_t)r * kw + k * dim + d]; + return; + } + const bool q = hd < heads; + const float x = q ? f32(pq[(size_t)r * 2 * qw + hd * 2 * dim + d]) : f32(pk[(size_t)r * kw + (hd - heads) * dim + d]); + const float* w = q ? qscale : kscale; + const float rinv = 1.0f / sqrtf(block_sum(x * x, scratch, dim / 32) / (float)dim + eps); + xn[d] = f32(b16(x * rinv * w[d])); + __syncthreads(); + float out = xn[d]; + if (d < 2 * half) { + float c, s; + rope_cs(pos0 + r, inv, d % half, c, s); + out = d < half ? xn[d] * c - xn[d + half] * s : xn[d - half] * s + xn[d] * c; + } + qkv[(size_t)r * width + (q ? hd * dim : qw + (hd - heads) * dim) + d] = b16(out); +} + +#define ATTN_KEYS 2048 + +// tf_train_attn_q for up to ATTN_KEYS keys: one query row i (position prefix + i) of head h. +extern "C" __global__ void __launch_bounds__(256) tf_attn_q(const bf16* qkv, const float* dout, float* probs, float* dscores, + float* dq, Heads a, const bf16* pk, const bf16* pv) { + __shared__ float qi[256], gi[256], sc[ATTN_KEYS], dp[ATTN_KEYS], scratch[32]; + const int t = threadIdx.x, lane = t & 31, w = t >> 5, h = blockIdx.x, i = blockIdx.y; + const int kv = h / (a.heads / a.kv_heads), qw = a.heads * a.dim, kw = a.kv_heads * a.dim; + const int keys = a.prefix + a.rows, at = a.prefix + i; + const bf16* k = qkv + qw; + const bf16* v = qkv + qw + kw; + for (int d = t; d < a.dim; d += 256) { + qi[d] = f32(qkv[(size_t)i * a.qkv + h * a.dim + d]); + gi[d] = dout[(size_t)i * qw + h * a.dim + d]; + } + __syncthreads(); + for (int j = w; j <= at; j += 8) { + const bf16* kr = (j < a.prefix ? pk + (size_t)j * kw : k + (size_t)(j - a.prefix) * a.qkv) + kv * a.dim; + const bf16* vr = (j < a.prefix ? pv + (size_t)j * kw : v + (size_t)(j - a.prefix) * a.qkv) + kv * a.dim; + float s = 0, g = 0; + for (int d = lane; d < a.dim; d += 32) { + s += qi[d] * f32(kr[d]); + g += gi[d] * f32(vr[d]); + } + s = warp_sum(s); + g = warp_sum(g); + if (lane == 0) sc[j] = s * a.scale, dp[j] = g; + } + __syncthreads(); + float top = -INFINITY; + for (int j = t; j <= at; j += 256) top = fmaxf(top, sc[j]); + top = block_max(top, scratch, 8); + float total = 0; + for (int j = t; j <= at; j += 256) { + const float e = expf(sc[j] - top); + sc[j] = e; + total += e; + } + total = block_sum(total, scratch, 8); + float mix = 0; + for (int j = t; j <= at; j += 256) { + sc[j] /= total; + mix += sc[j] * dp[j]; + } + mix = block_sum(mix, scratch, 8); + const size_t row = ((size_t)h * a.rows + i) * keys; + for (int j = t; j < keys; j += 256) { + const bool live = j <= at; + const float p = live ? sc[j] : 0.0f, g = live ? p * (dp[j] - mix) : 0.0f; + if (live) dp[j] = g; + probs[row + j] = p; + dscores[row + j] = g; + } + __syncthreads(); + for (int d = t; d < a.dim; d += 256) { + float acc = 0; + for (int j = 0; j <= at; j++) { + const bf16* kr = j < a.prefix ? pk + (size_t)j * kw : k + (size_t)(j - a.prefix) * a.qkv; + acc += dp[j] * f32(kr[kv * a.dim + d]); + } + dq[(size_t)i * qw + h * a.dim + d] = acc * a.scale; + } +} + +// The output gate gated = o sigmoid(gate) undone from dgated [rows, heads dim]. +extern "C" __global__ void tf_attn_gate_back(const float* dgated, const bf16* gated, const bf16* pq, float* dout, float* dpq, + int heads, int dim) { + const int c = blockIdx.x * 256 + threadIdx.x, r = blockIdx.y, qw = heads * dim; + if (c >= qw) return; + const int h = c / dim, d = c % dim; + const size_t at = (size_t)r * 2 * qw + h * 2 * dim + dim + d; + const float sg = sigm(f32(pq[at])), g = dgated[(size_t)r * qw + c]; + dout[(size_t)r * qw + c] = g * sg; + dpq[at] = g * f32(gated[(size_t)r * qw + c]) * (1.0f - sg); +} + +// tf_attn_prep undone for the q and k heads: dq [rows, heads dim] and dk [rows. +extern "C" __global__ void __launch_bounds__(256) tf_attn_prep_back(const bf16* pq, const bf16* pk, const float* qscale, + const float* kscale, const float* inv, int pos0, + const float* dq, const float* dk, float* dpq, float* dpk, + int heads, int kv_heads, int dim, int half, float eps) { + __shared__ float go[256], scratch[32]; + const int hd = blockIdx.x, r = blockIdx.y, d = threadIdx.x; + const int qw = heads * dim, kw = kv_heads * dim; + const bool q = hd < heads; + const float x = q ? f32(pq[(size_t)r * 2 * qw + hd * 2 * dim + d]) : f32(pk[(size_t)r * kw + (hd - heads) * dim + d]); + go[d] = q ? dq[(size_t)r * qw + hd * dim + d] : dk[(size_t)r * kw + (hd - heads) * dim + d]; + __syncthreads(); + float gn = go[d]; + if (d < 2 * half) { + float c, s; + rope_cs(pos0 + r, inv, d % half, c, s); + gn = d < half ? go[d] * c + go[d + half] * s : go[d] * c - go[d - half] * s; + } + const float w = (q ? qscale : kscale)[d]; + const float sq = block_sum(x * x, scratch, dim / 32), dot = block_sum(w * gn * x, scratch, dim / 32); + const float rinv = 1.0f / sqrtf(sq / (float)dim + eps); + const float g = rinv * w * gn - rinv * rinv * rinv * x * dot / (float)dim; + if (q) + dpq[(size_t)r * 2 * qw + hd * 2 * dim + d] = g; + else + dpk[(size_t)r * kw + (hd - heads) * dim + d] = g; +} + + +// ---- shared by the learners' products and nudges ------------------------------------------------------------------ + +// C [M, N] (rows ldc apart) (+)= the split products' partials [splits, M, N], summed in split order. +extern "C" __global__ void tf_sum_parts(const float* parts, int splits, int M, int N, float* C, int ldc, int accumulate) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i >= (long long)M * N) return; + float s = 0; + for (int z = 0; z < splits; z++) s += parts[(size_t)z * M * N + i]; + float* out = C + (size_t)(i / N) * ldc + i % N; + *out = accumulate ? *out + s : s; +} + +// y[i] += x[i] for n floats: a nudge onto its row of a layer's output. +extern "C" __global__ void tf_axpy(float* y, const float* x, int n) { + const int i = blockIdx.x * 256 + threadIdx.x; + if (i < n) y[i] += x[i]; +} diff --git a/zig/kernels/cuda/gdn_train.cu b/zig/kernels/cuda/gdn_train.cu new file mode 100644 index 0000000000..9b908fc850 --- /dev/null +++ b/zig/kernels/cuda/gdn_train.cu @@ -0,0 +1,424 @@ +// Living Weights: the Gated DeltaNet layer's forward for training and its input-gradient backward (cuda/gdn_train.zig). + +#include +#include + +typedef __nv_bfloat16 bf16; + +// The layer's shape: rows, key and value heads, conv channels (2 nk DK + nv DV) and projection row width. +struct GdnShape { + int rows, nk, nv, conv, proj; +}; + +namespace { + +constexpr int DK = 128, DV = 128, TAPS = 4; +constexpr int CK = 4; // scan rows between state checkpoints (gdn_train.zig's ck) +constexpr int SPLIT = 4; // blocks a value head's chain runs in (gdn_train.zig's split) +constexpr int ROWS = DV / SPLIT; // state rows a block holds: 8 warps of 4 + +__device__ __forceinline__ float f32(bf16 v) { return __bfloat162float(v); } +__device__ __forceinline__ bf16 b16(float v) { return __float2bfloat16_rn(v); } +__device__ __forceinline__ float bf(float x) { return f32(b16(x)); } + +__device__ __forceinline__ float warp_sum(float x) { + for (int o = 16; o; o >>= 1) x += __shfl_xor_sync(0xffffffffu, x, o); + return x; +} + +// The sum over a block of `groups` warps, the same in every thread. +__device__ __forceinline__ float block_sum(float v, float* scratch, int groups) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + v = warp_sum(v); + if (lane == 0) scratch[w] = v; + __syncthreads(); + v = warp_sum(lane < groups ? scratch[lane] : 0.0f); + __syncthreads(); + return v; +} + +__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + expf(-x)); } +__device__ __forceinline__ float softplusf_(float x) { return x > 20.0f ? x : log1pf(expf(x)); } + +__device__ __forceinline__ float silu_grad(float v) { + const float s = sigmoidf_(v); + return s * (1.0f + v * (1.0f - s)); +} + +__device__ __forceinline__ int chunks(int rows) { return (rows + CK - 1) / CK; } + +// Channel c's conv sum for row r over [history (zeros when null) | projection rows], the chain kernel's tap order. +__device__ __forceinline__ float conv_acc(const bf16* P, const bf16* hist, const bf16* cw, int r, int c, const GdnShape& s) { + float acc = 0.0f; +#pragma unroll + for (int tap = 0; tap < TAPS; ++tap) { + const int at = r - (TAPS - 1) + tap; + const float x = at >= 0 ? f32(P[(size_t)at * s.proj + c]) + : (hist != nullptr ? f32(hist[(size_t)(at + TAPS - 1) * s.conv + c]) : 0.0f); + acc = acc + f32(cw[c * TAPS + tap]) * x; + } + return acc; +} + +// This thread's 4 x 4 block of a [DV][DK] state: rows 4 warp .. 4 warp + 3, columns 4 lane .. 4 lane + 3. +__device__ __forceinline__ void load_state(float (&s)[4][4], const float* base, int warp, int lane) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float4 v = base != nullptr ? *reinterpret_cast(base + (warp * 4 + j) * DK + lane * 4) + : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + s[j][0] = v.x; s[j][1] = v.y; s[j][2] = v.z; s[j][3] = v.w; + } +} + +__device__ __forceinline__ void store_state(const float (&s)[4][4], float* base, int warp, int lane) { +#pragma unroll + for (int j = 0; j < 4; ++j) + *reinterpret_cast(base + (warp * 4 + j) * DK + lane * 4) = make_float4(s[j][0], s[j][1], s[j][2], s[j][3]); +} + +// gdn.cu's update: one delta-rule step on this thread's block of the state (decay, read along k, correct toward v). +__device__ __forceinline__ void update(float (&s)[4][4], const float (&kk)[4], const float* vrow, int warp, float g, + float beta) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + float kv = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + s[j][i] = s[j][i] * g; + kv = kv + s[j][i] * kk[i]; + } + kv = warp_sum(kv); + const float delta = (vrow[warp * 4 + j] - kv) * beta; +#pragma unroll + for (int i = 0; i < 4; ++i) s[j][i] = s[j][i] + kk[i] * delta; + } +} + +} // namespace + +// ---- the forward for training -------------------------------------------------------------------------------------- + +// Block (row, head), gdn_io.cu's front: heads < nk conv q and k and L2-norm them (q times DK^-0.5). +extern "C" __global__ void __launch_bounds__(128) tf_gdn_front(const bf16* __restrict__ P, const bf16* __restrict__ hist, + const bf16* __restrict__ cw, const float* __restrict__ a_log, + const float* __restrict__ dt_bias, bf16* __restrict__ act, + float* __restrict__ q, float* __restrict__ k, + float* __restrict__ g, float* __restrict__ beta, GdnShape s) { + const int r = blockIdx.x, head = blockIdx.y, t = threadIdx.x, warp = t >> 5, lane = t & 31; + __shared__ float xs[2][DK]; + if (head < s.nk) { + const int cq = head * DK + t, ck = s.nk * DK + head * DK + t; + const float aq = conv_acc(P, hist, cw, r, cq, s), ak = conv_acc(P, hist, cw, r, ck, s); + xs[0][t] = bf(aq / (1.0f + expf(-aq))); + xs[1][t] = bf(ak / (1.0f + expf(-ak))); + act[(size_t)r * s.conv + cq] = b16(xs[0][t]); + act[(size_t)r * s.conv + ck] = b16(xs[1][t]); + __syncthreads(); + if (warp < 2) { + float v4[4], ss = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { v4[i] = xs[warp][lane * 4 + i]; ss = ss + v4[i] * v4[i]; } + ss = warp_sum(ss); + float inv = 1.0f / sqrtf(ss + 1e-6f); + if (warp == 0) inv = inv * (1.0f / sqrtf((float)DK)); + float* out = (warp == 0 ? q : k) + ((size_t)r * s.nk + head) * DK + lane * 4; +#pragma unroll + for (int i = 0; i < 4; ++i) out[i] = v4[i] * inv; + } + return; + } + const int hv = head - s.nk, c = 2 * s.nk * DK + hv * DV + t; + const float av = conv_acc(P, hist, cw, r, c, s); + act[(size_t)r * s.conv + c] = b16(av / (1.0f + expf(-av))); + if (t == 0) { + const size_t at = (size_t)r * s.proj + s.conv + s.nv * DV; + const float b = f32(P[at + hv]), a = f32(P[at + s.nv + hv]); + g[r * s.nv + hv] = expf(-expf(a_log[hv]) * softplusf_(a + dt_bias[hv])); + beta[r * s.nv + hv] = bf(sigmoidf_(b)); + } +} + +// One value head's chain from init [nv][DV][DK] (null: zeros), SPLIT blocks of 256 threads a head. +extern "C" __global__ void __launch_bounds__(256) tf_gdn_scan_fwd(const bf16* __restrict__ act, const float* __restrict__ q, + const float* __restrict__ k, const float* __restrict__ g, + const float* __restrict__ beta, const float* __restrict__ init, + bf16* __restrict__ y, float* __restrict__ ckpt, GdnShape s) { + const int h = blockIdx.x / SPLIT, rb = (blockIdx.x % SPLIT) * ROWS, hk = h / (s.nv / s.nk); + const int t = threadIdx.x, warp = t >> 5, lane = t & 31; + const size_t size = (size_t)DV * DK; + const int v0 = 2 * s.nk * DK + h * DV + rb; + __shared__ float qs[DK], ks[DK], vs[ROWS]; + float st[4][4]; + load_state(st, init != nullptr ? init + h * size + rb * DK : nullptr, warp, lane); + float* mine = ckpt + (size_t)h * chunks(s.rows) * size + rb * DK; + for (int r = 0; r < s.rows; ++r) { + if (r % CK == 0) store_state(st, mine + (r / CK) * size, warp, lane); + if (t < DK) qs[t] = q[((size_t)r * s.nk + hk) * DK + t]; + else ks[t - DK] = k[((size_t)r * s.nk + hk) * DK + t - DK]; + if (t < ROWS) vs[t] = f32(act[(size_t)r * s.conv + v0 + t]); + __syncthreads(); + float kk[4], qq[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) { kk[i] = ks[lane * 4 + i]; qq[i] = qs[lane * 4 + i]; } + update(st, kk, vs, warp, g[r * s.nv + h], beta[r * s.nv + h]); +#pragma unroll + for (int j = 0; j < 4; ++j) { + float o = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) o = o + st[j][i] * qq[i]; + o = warp_sum(o); + if (lane == 0) y[((size_t)r * s.nv + h) * DV + rb + warp * 4 + j] = b16(o); + } + __syncthreads(); + } +} + +// ---- the backward --------------------------------------------------------------------------------------------------- + +// Block (row, value head): the gated RMS norm undone. dout [rows. +extern "C" __global__ void __launch_bounds__(128) tf_gdn_norm_back(const bf16* __restrict__ y, const bf16* __restrict__ P, + const bf16* __restrict__ norm_w, const float* __restrict__ dout, + float* __restrict__ dy, float* __restrict__ dproj, GdnShape s, + float eps) { + const int r = blockIdx.x, h = blockIdx.y, t = threadIdx.x, warp = t >> 5, lane = t & 31; + __shared__ float ys[DV], scratch[32]; + __shared__ float rinv; + const size_t row = ((size_t)r * s.nv + h) * DV; + ys[t] = f32(y[row + t]); + __syncthreads(); + if (warp == 0) { + float ss = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { const float v = ys[lane * 4 + i]; ss = ss + v * v; } + ss = warp_sum(ss); + if (lane == 0) rinv = 1.0f / sqrtf(ss / (float)DV + eps); + } + __syncthreads(); + const float w = f32(norm_w[t]), yv = ys[t], ri = rinv; + const float yn = bf(bf(yv * ri) * w); + const size_t zc = (size_t)r * s.proj + s.conv + h * DV + t; + const float sg = sigmoidf_(f32(P[zc])), d = dout[row + t]; + dproj[zc] = d * yn * sg * (1.0f - sg); + const float dn = d * sg * w; + const float dot = block_sum(yv * dn, scratch, 4); + dy[row + t] = ri * dn - ri * ri * ri * yv * dot / (float)DV; +} + +// One value head's chain backward, SPLIT blocks of 256 threads a head as the forward (each its 32 state rows). +extern "C" __global__ void __launch_bounds__(256) tf_gdn_scan_back(const bf16* __restrict__ act, const float* __restrict__ q, + const float* __restrict__ k, const float* __restrict__ g, + const float* __restrict__ beta, const float* __restrict__ ckpt, + const float* __restrict__ dy, float* __restrict__ work, + float* __restrict__ dqp, float* __restrict__ dkp, + float* __restrict__ dact, float* __restrict__ dg, + float* __restrict__ dbeta, GdnShape s, int from) { + constexpr int WARPS = ROWS / 4; + __shared__ float qs[DK], ks[DK], vs[ROWS], dos[ROWS]; + __shared__ float red_q[WARPS][DK], red_k[WARPS][DK]; + __shared__ float red_g[WARPS], red_b[WARPS]; + const int h = blockIdx.x / SPLIT, part = blockIdx.x % SPLIT, rb = part * ROWS, hk = h / (s.nv / s.nk); + const int t = threadIdx.x, warp = t >> 5, lane = t & 31; + const size_t size = (size_t)DV * DK, mine_size = (size_t)ROWS * DK; + const int v0 = 2 * s.nk * DK + h * DV + rb, nch = chunks(s.rows); + const float* saved = ckpt + (size_t)h * nch * size + rb * DK; + float* mine = work + (size_t)blockIdx.x * CK * mine_size; + float ds[4][4]; +#pragma unroll + for (int j = 0; j < 4; ++j) +#pragma unroll + for (int i = 0; i < 4; ++i) ds[j][i] = 0.0f; + for (int c = nch - 1; c >= from / CK; --c) { + const int first = c * CK, last = min(first + CK, s.rows); + { + // the state before each of the chunk's rows, each thread its own elements + float st[4][4]; + load_state(st, saved + c * size, warp, lane); + float in_kv = 0.0f, in_g = 0.0f, in_b = 0.0f; + auto fetch = [&](int r) { + if (t < DK) in_kv = k[((size_t)r * s.nk + hk) * DK + t]; + else if (t < DK + ROWS) in_kv = f32(act[(size_t)r * s.conv + v0 + t - DK]); + in_g = g[r * s.nv + h]; + in_b = beta[r * s.nv + h]; + }; + if (first + 1 < last) fetch(first); + for (int r = first; r < last; ++r) { + store_state(st, mine + (r - first) * mine_size, warp, lane); + if (r + 1 == last) break; + if (t < DK) ks[t] = in_kv; + else if (t < DK + ROWS) vs[t - DK] = in_kv; + const float gg = in_g, bb = in_b; + __syncthreads(); + if (r + 2 < last) fetch(r + 1); + float kk[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) kk[i] = ks[lane * 4 + i]; + update(st, kk, vs, warp, gg, bb); + __syncthreads(); + } + } + // each row's inputs fetched into registers while the row before it in the walk computes + float in_qk, in_vd = 0.0f, in_g, in_b; + auto fetch = [&](int r) { + in_qk = t < DK ? q[((size_t)r * s.nk + hk) * DK + t] : k[((size_t)r * s.nk + hk) * DK + t - DK]; + if (t < ROWS) in_vd = f32(act[(size_t)r * s.conv + v0 + t]); + else if (t < 2 * ROWS) in_vd = dy[((size_t)r * s.nv + h) * DV + rb + t - ROWS]; + in_g = g[r * s.nv + h]; + in_b = beta[r * s.nv + h]; + }; + fetch(last - 1); + for (int r = last - 1; r >= first; --r) { + if (t < DK) qs[t] = in_qk; + else ks[t - DK] = in_qk; + if (t < ROWS) vs[t] = in_vd; + else if (t < 2 * ROWS) dos[t - ROWS] = in_vd; + const float gg = in_g, bb = in_b; + __syncthreads(); + if (r > first) fetch(r - 1); + float kk[4], qq[4], pq[4], pk[4], pg = 0.0f, pb = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + kk[i] = ks[lane * 4 + i]; + qq[i] = qs[lane * 4 + i]; + pq[i] = 0.0f; + pk[i] = 0.0f; + } + const float* prev = mine + (r - first) * mine_size; + float4 p4[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) p4[j] = *reinterpret_cast(prev + (warp * 4 + j) * DK + lane * 4); +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int row = warp * 4 + j; + const float sp[4] = {p4[j].x, p4[j].y, p4[j].z, p4[j].w}; + float sd[4], kv = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + sd[i] = sp[i] * gg; + kv = kv + sd[i] * kk[i]; + } + kv = warp_sum(kv); + const float err = vs[row] - kv, delta = err * bb, dj = dos[row]; + float dd = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + pq[i] += dj * (sd[i] + kk[i] * delta); + ds[j][i] += dj * qq[i]; + dd += ds[j][i] * kk[i]; + } + dd = warp_sum(dd); + const float dkv = -bb * dd; + if (lane == 0) { + dact[(size_t)r * s.conv + v0 + row] = bb * dd; + pb += dd * err; + } +#pragma unroll + for (int i = 0; i < 4; ++i) { + pk[i] += delta * ds[j][i] + dkv * sd[i]; + const float dsp = ds[j][i] + dkv * kk[i]; + pg += dsp * sp[i]; + ds[j][i] = gg * dsp; + } + } +#pragma unroll + for (int i = 0; i < 4; ++i) { + red_q[warp][lane * 4 + i] = pq[i]; + red_k[warp][lane * 4 + i] = pk[i]; + } + pg = warp_sum(pg); + if (lane == 0) { + red_g[warp] = pg; + red_b[warp] = pb; + } + __syncthreads(); + const size_t out = ((size_t)r * s.nv + h) * SPLIT + part; + if (t < DK) { + float x = 0.0f; +#pragma unroll + for (int w = 0; w < WARPS; ++w) x += red_q[w][t]; + dqp[out * DK + t] = x; + if (t == 0) { + float e = 0.0f; +#pragma unroll + for (int w = 0; w < WARPS; ++w) e += red_g[w]; + dg[out] = e; + } + } else { + float x = 0.0f; +#pragma unroll + for (int w = 0; w < WARPS; ++w) x += red_k[w][t - DK]; + dkp[out * DK + t - DK] = x; + if (t == DK) { + float e = 0.0f; +#pragma unroll + for (int w = 0; w < WARPS; ++w) e += red_b[w]; + dbeta[out] = e; + } + } + } + } +} + +// Block (row, key head): the value heads' dq and dk shares summed in head and block order. +extern "C" __global__ void __launch_bounds__(128) tf_gdn_qk_back(const bf16* __restrict__ act, const float* __restrict__ dqp, + const float* __restrict__ dkp, float* __restrict__ dact, + GdnShape s) { + __shared__ float scratch[32]; + const int r = blockIdx.x, hk = blockIdx.y, t = threadIdx.x, per = s.nv / s.nk; + for (int which = 0; which < 2; ++which) { + const float* part = which == 0 ? dqp : dkp; + float d = 0.0f; + for (int h = hk * per; h < (hk + 1) * per; ++h) + for (int p = 0; p < SPLIT; ++p) d += part[(((size_t)r * s.nv + h) * SPLIT + p) * DK + t]; + const int c = which * s.nk * DK + hk * DK + t; + const float x = f32(act[(size_t)r * s.conv + c]); + const float ss = block_sum(x * x, scratch, 4); + const float dot = block_sum(x * d, scratch, 4); + const float inv = 1.0f / sqrtf(ss + 1e-6f), sc = which == 0 ? 1.0f / sqrtf((float)DK) : 1.0f; + dact[(size_t)r * s.conv + c] = sc * inv * (d - inv * inv * x * dot); + } +} + +// Block r, thread h: dg and dbeta (the chain blocks' shares summed) back to dproj's a and b columns. +extern "C" __global__ void tf_gdn_gates_back(const bf16* __restrict__ P, const float* __restrict__ a_log, + const float* __restrict__ dt_bias, const float* __restrict__ g, + const float* __restrict__ dg, const float* __restrict__ dbeta, + float* __restrict__ dproj, GdnShape s) { + const int h = threadIdx.x, r = blockIdx.x; + if (h >= s.nv || r >= s.rows) return; + const size_t at = (size_t)r * s.proj + s.conv + s.nv * DV; + const float b = f32(P[at + h]), x = f32(P[at + s.nv + h]) + dt_bias[h]; + const float sb = sigmoidf_(b), sx = x > 20.0f ? 1.0f : sigmoidf_(x); + float db = 0.0f, dgs = 0.0f; + for (int p = 0; p < SPLIT; ++p) { + db += dbeta[(r * s.nv + h) * SPLIT + p]; + dgs += dg[(r * s.nv + h) * SPLIT + p]; + } + dproj[at + h] = db * sb * (1.0f - sb); + dproj[at + s.nv + h] = -dgs * g[r * s.nv + h] * expf(a_log[h]) * sx; +} + +// The depthwise causal conv and its SiLU undone into dproj's qkv columns. +extern "C" __global__ void tf_gdn_conv_back(const bf16* __restrict__ P, const bf16* __restrict__ hist, + const bf16* __restrict__ cw, const float* __restrict__ dact, + float* __restrict__ dproj, GdnShape s) { + const int c = blockIdx.x * 256 + threadIdx.x, r = blockIdx.y; + if (c >= s.conv || r >= s.rows) return; + float acc = 0.0f; +#pragma unroll + for (int tap = 0; tap < TAPS; ++tap) { + const int at = r + TAPS - 1 - tap; + if (at >= s.rows) continue; + const float pre = conv_acc(P, hist, cw, at, c, s); + acc += f32(cw[c * TAPS + tap]) * dact[(size_t)at * s.conv + c] * silu_grad(pre); + } + dproj[(size_t)r * s.proj + c] = acc; +} + +// A 4-bit [N, K] MLX affine matrix (8 codes a word, a bf16 scale and bias every `group`) as bf16 [N, K], in order. +extern "C" __global__ void tf_gdn_dequant(const unsigned* __restrict__ w, const bf16* __restrict__ scales, + const bf16* __restrict__ biases, bf16* __restrict__ out, long long count, int group) { + const long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x; + if (i >= count) return; + const unsigned qv = (w[i / 8] >> (4 * (i % 8))) & 0xfu; + out[i] = b16(f32(scales[i / group]) * (float)qv + f32(biases[i / group])); +} diff --git a/zig/src/cuda/gdn_train.zig b/zig/src/cuda/gdn_train.zig new file mode 100644 index 0000000000..a0213590d9 --- /dev/null +++ b/zig/src/cuda/gdn_train.zig @@ -0,0 +1,345 @@ +//! Flash Next's Gated DeltaNet backward for Living Weights (gdn_train.cu). +const std = @import("std"); +const driver = @import("driver.zig"); +const module = @import("module.zig"); +const launch_ = @import("launch.zig"); +const stream_ = @import("stream.zig"); +const kernels = @import("kernels.zig"); + +const Driver = driver.Driver; +const Module = module.Module; +const Function = module.Function; +const Stream = stream_.Stream; +const Args = launch_.Args; + +pub const dk = 128; +pub const dv = 128; +pub const taps = 4; +/// Chain rows between state checkpoints (gdn_train.cu's CK): 4 keeps the replay area. +pub const ck = 4; +/// Blocks of 256 threads a value head's chain runs in, each 32 of its state rows (gdn_train.cu's SPLIT). +pub const split = 4; + +/// The layer's shape as the kernels read it (gdn_train.cu's GdnShape). +pub const Shape = extern struct { + rows: c_int, + nk: c_int, + nv: c_int, + conv: c_int, + proj: c_int, + + pub fn init(rows: usize, nk: usize, nv: usize) Shape { + const conv = 2 * nk * dk + nv * dv; + return .{ .rows = @intCast(rows), .nk = @intCast(nk), .nv = @intCast(nv), .conv = @intCast(conv), .proj = @intCast(conv + nv * dv + 2 * nv) }; + } + + pub fn chunks(s: Shape) usize { + return (@as(usize, @intCast(s.rows)) + ck - 1) / ck; + } +}; + +/// An MLX affine 4-bit matrix [n, k]: packed words, bf16 scales and biases every `group` inputs. +pub const Q4 = struct { w: u64, s: u64, b: u64, n: usize, k: usize, group: usize = 32 }; + +/// One DeltaNet layer's weights: conv [conv, 4] bf16, A_log and dt_bias [nv] fp32, the norm's [dv] bf16, projections. +pub const Layer = struct { + nk: usize, + nv: usize, + hidden: usize, + eps: f32, + conv_w: u64, + a_log: u64, + dt_bias: u64, + norm_w: u64, + in_proj: Q4, // [qkv | z | b | a] x hidden + out_proj: Q4, // hidden x nv dv +}; + +const names = [_][:0]const u8{ "tf_gdn_front", "tf_gdn_scan_fwd", "tf_gdn_norm_back", "tf_gdn_scan_back", "tf_gdn_qk_back", "tf_gdn_gates_back", "tf_gdn_conv_back", "tf_gdn_dequant" }; +const train_names = [_][:0]const u8{ "tf_train_narrow", "tf_train_gemm" }; + +fn index(comptime list: []const [:0]const u8, comptime name: []const u8) usize { + inline for (list, 0..) |n, i| if (comptime std.mem.eql(u8, n, name)) return i; + @compileError("no kernel " ++ name); +} + +pub const Kernels = struct { + module: Module, + train: Module, + fns: [names.len]Function, + train_fns: [train_names.len]Function, + + pub fn load(d: *const Driver) !Kernels { + if (!kernels.available) return error.BuiltWithoutKernels; + var k: Kernels = .{ .module = try Module.load(d, kernels.gdn_train), .train = undefined, .fns = undefined, .train_fns = undefined }; + errdefer k.module.unload(); + k.train = try Module.load(d, kernels.train); + errdefer k.train.unload(); + for (names, &k.fns) |n, *f| f.* = try k.module.function(n); + for (train_names, &k.train_fns) |n, *f| f.* = try k.train.function(n); + return k; + } + + pub fn deinit(k: *Kernels) void { + k.train.unload(); + k.module.unload(); + } +}; + +fn int(x: usize) c_int { + return @intCast(x); +} + +fn up(n: usize, by: usize) u32 { + return @intCast((n + by - 1) / by); +} + +fn u(x: usize) u32 { + return @intCast(x); +} + +/// The device buffers a pass of up to `rows` rows uses, carved from one allocation of `bytes(...)`. +pub const Scratch = struct { + act: u64, // [rows, conv] bf16: the conv outputs + q: u64, // [rows, nk, dk] fp32, normalized and scaled + k: u64, // [rows, nk, dk] fp32, normalized + g: u64, // [rows, nv] fp32 + beta: u64, // [rows, nv] fp32 + y: u64, // [rows, nv, dv] bf16: the chain's read-out + ckpt: u64, // [nv, chunks, dv, dk] fp32 + work: u64, // [nv, ck, dv, dk] fp32 + dout: u64, // [rows, nv dv] fp32: the out projection's input gradient + dy: u64, // [rows, nv, dv] fp32 + dqp: u64, // [rows, nv, split, dk] fp32: each chain block's share of dq + dkp: u64, // [rows, nv, split, dk] fp32 + dact: u64, // [rows, conv] fp32 + dg: u64, // [rows, nv, split] fp32: each chain block's share + dbeta: u64, // [rows, nv, split] fp32 + dproj: u64, // [rows, proj] fp32: the in projection's output gradient + xb: u64, // [rows, max(proj, hidden)] bf16: a product's narrowed left side + wt: u64, // [proj, hidden] bf16: a projection dequantized + + const Part = struct { name: []const u8, bytes: usize }; + + fn parts(rows: usize, nk: usize, nv: usize, hidden: usize) [18]Part { + const s = Shape.init(rows, nk, nv); + const conv: usize = @intCast(s.conv); + const proj: usize = @intCast(s.proj); + const state = nv * dv * dk * 4; + return .{ + .{ .name = "act", .bytes = rows * conv * 2 }, .{ .name = "q", .bytes = rows * nk * dk * 4 }, + .{ .name = "k", .bytes = rows * nk * dk * 4 }, .{ .name = "g", .bytes = rows * nv * 4 }, + .{ .name = "beta", .bytes = rows * nv * 4 }, .{ .name = "y", .bytes = rows * nv * dv * 2 }, + .{ .name = "ckpt", .bytes = s.chunks() * state }, .{ .name = "work", .bytes = ck * state }, + .{ .name = "dout", .bytes = rows * nv * dv * 4 }, .{ .name = "dy", .bytes = rows * nv * dv * 4 }, + .{ .name = "dqp", .bytes = rows * nv * split * dk * 4 }, .{ .name = "dkp", .bytes = rows * nv * split * dk * 4 }, + .{ .name = "dact", .bytes = rows * conv * 4 }, .{ .name = "dg", .bytes = rows * nv * split * 4 }, + .{ .name = "dbeta", .bytes = rows * nv * split * 4 }, .{ .name = "dproj", .bytes = rows * proj * 4 }, + .{ .name = "xb", .bytes = rows * @max(proj, hidden) * 2 }, .{ .name = "wt", .bytes = proj * hidden * 2 }, + }; + } + + pub fn padded(n: usize) usize { + return (n + 255) / 256 * 256; + } + + /// Bytes of one allocation holding every buffer, each 256-byte aligned. + pub fn bytes(rows: usize, nk: usize, nv: usize, hidden: usize) usize { + var n: usize = 0; + for (parts(rows, nk, nv, hidden)) |p| n += padded(p.bytes); + return n; + } + + /// The buffers at `base`, an allocation of at least bytes(rows, nk, nv, hidden). + pub fn carve(base: u64, rows: usize, nk: usize, nv: usize, hidden: usize) Scratch { + var out: Scratch = undefined; + var at: u64 = base; + inline for (@typeInfo(Scratch).@"struct".field_names, 0..) |f, i| { + @field(out, f) = at; + at += padded(parts(rows, nk, nv, hidden)[i].bytes); + } + return out; + } +}; + +/// A family's own 4-bit product for backwardAll's two projections, taken instead of the narrow. +pub const Product = struct { + ctx: *const anyopaque, + f: *const fn (ctx: *const anyopaque, x: u64, m: Q4, y: u64, rows: usize, add: bool) anyerror!void, +}; + +/// Launches on one stream. +pub const Ops = struct { + k: *const Kernels, + s: Stream, + q4: ?Product = null, // backwardAll's projections through the family's own product (null: productWith) + + fn go(o: Ops, comptime name: []const u8, grid: [3]u32, block: u32, args: *Args) !void { + try launch_.launch(o.k.fns[index(&names, name)], .{ .grid = .{ .x = grid[0], .y = grid[1], .z = grid[2] }, .block = .{ .x = block } }, o.s, args); + } + + fn goTrain(o: Ops, comptime name: []const u8, grid: [3]u32, block: u32, args: *Args) !void { + try launch_.launch(o.k.train_fns[index(&train_names, name)], .{ .grid = .{ .x = grid[0], .y = grid[1], .z = grid[2] }, .block = .{ .x = block } }, o.s, args); + } + + /// Conv, SiLU, q and k norms, g and beta for every row of P [rows, proj] bf16 after hist [3, conv] (null: zeros). + pub fn front(o: Ops, p: u64, hist: ?u64, conv_w: u64, a_log: u64, dt_bias: u64, sc: Scratch, s: Shape) !void { + var a: Args = .{}; + for ([_]u64{ p, hist orelse 0, conv_w, a_log, dt_bias, sc.act, sc.q, sc.k, sc.g, sc.beta }) |v| a.add(v); + a.add(s); + try o.go("tf_gdn_front", .{ u(@intCast(s.rows)), u(@intCast(s.nk + s.nv)), 1 }, 128, &a); + } + + /// The chain from init [nv, dv, dk] fp32 (null: zeros): y and the checkpoints. + pub fn scanFwd(o: Ops, init: ?u64, sc: Scratch, s: Shape) !void { + var a: Args = .{}; + for ([_]u64{ sc.act, sc.q, sc.k, sc.g, sc.beta, init orelse 0, sc.y, sc.ckpt }) |v| a.add(v); + a.add(s); + try o.go("tf_gdn_scan_fwd", .{ u(@intCast(s.nv * split)), 1, 1 }, 256, &a); + } + + /// dout back through the gated RMS norm: dy, and dz into dproj. + pub fn normBack(o: Ops, p: u64, norm_w: u64, sc: Scratch, s: Shape, eps: f32) !void { + var a: Args = .{}; + for ([_]u64{ sc.y, p, norm_w, sc.dout, sc.dy, sc.dproj }) |v| a.add(v); + a.add(s); + a.add(eps); + try o.go("tf_gdn_norm_back", .{ u(@intCast(s.rows)), u(@intCast(s.nv)), 1 }, 128, &a); + } + + /// dy back through the chain: dq and dk shares, dv into dact, dg and dbeta. + pub fn scanBack(o: Ops, sc: Scratch, s: Shape) !void { + return o.scanBackFrom(sc, s, 0); + } + + /// scanBack walked back only to the chunk holding row `from`: the rows from it on, the same bits. + pub fn scanBackFrom(o: Ops, sc: Scratch, s: Shape, from: usize) !void { + var a: Args = .{}; + for ([_]u64{ sc.act, sc.q, sc.k, sc.g, sc.beta, sc.ckpt, sc.dy, sc.work, sc.dqp, sc.dkp, sc.dact, sc.dg, sc.dbeta }) |v| a.add(v); + a.add(s); + a.add(@as(c_int, @intCast(from))); + try o.go("tf_gdn_scan_back", .{ u(@intCast(s.nv * split)), 1, 1 }, 256, &a); + } + + /// The dq and dk shares summed per key head and their L2 norms undone into dact. + pub fn qkBack(o: Ops, sc: Scratch, s: Shape) !void { + var a: Args = .{}; + for ([_]u64{ sc.act, sc.dqp, sc.dkp, sc.dact }) |v| a.add(v); + a.add(s); + try o.go("tf_gdn_qk_back", .{ u(@intCast(s.rows)), u(@intCast(s.nk)), 1 }, 128, &a); + } + + /// dg and dbeta into dproj's a and b columns. + pub fn gatesBack(o: Ops, p: u64, a_log: u64, dt_bias: u64, sc: Scratch, s: Shape) !void { + var a: Args = .{}; + for ([_]u64{ p, a_log, dt_bias, sc.g, sc.dg, sc.dbeta, sc.dproj }) |v| a.add(v); + a.add(s); + try o.go("tf_gdn_gates_back", .{ u(@intCast(s.rows)), 1, 1 }, up(@intCast(s.nv), 32) * 32, &a); + } + + /// dact back through the SiLU and the conv into dproj's qkv columns. + pub fn convBack(o: Ops, p: u64, hist: ?u64, conv_w: u64, sc: Scratch, s: Shape) !void { + var a: Args = .{}; + for ([_]u64{ p, hist orelse 0, conv_w, sc.dact, sc.dproj }) |v| a.add(v); + a.add(s); + try o.go("tf_gdn_conv_back", .{ up(@intCast(s.conv), 256), u(@intCast(s.rows)), 1 }, 256, &a); + } + + /// A 4-bit matrix as bf16 [n, k] into out. + pub fn dequant(o: Ops, m: Q4, out: u64) !void { + var a: Args = .{}; + for ([_]u64{ m.w, m.s, m.b, out }) |v| a.add(v); + a.add(@as(c_longlong, @intCast(m.n * m.k))); + a.add(int(m.group)); + try o.go("tf_gdn_dequant", .{ up(m.n * m.k, 256), 1, 1 }, 256, &a); + } + + /// y [rows, m.k] (+)= bf16(x) [rows, m.n] times the dequantized matrix: its input's gradient from its output's. + pub fn product(o: Ops, x: u64, m: Q4, y: u64, rows: usize, sc: Scratch, add: bool) !void { + return o.productWith(x, m, y, rows, sc.xb, sc.wt, add); + } + + /// product with the narrowed left side in xb [rows, m.n] bf16 and the dequantized matrix in wt. + fn productWith(o: Ops, x: u64, m: Q4, y: u64, rows: usize, xb: u64, wt: u64, add: bool) !void { + var a: Args = .{}; + a.add(x); + a.add(xb); + a.add(@as(c_longlong, @intCast(rows * m.n))); + try o.goTrain("tf_train_narrow", .{ up(rows * m.n, 256), 1, 1 }, 256, &a); + try o.dequant(m, wt); + var g: Args = .{}; + for ([_]u64{ xb, wt, y }) |v| g.add(v); + for ([_]usize{ rows, m.k, m.n, m.n, m.k, m.k }) |v| g.add(int(v)); + g.add(@as(c_int, @intFromBool(add))); + try o.goTrain("tf_train_gemm", .{ up(m.k, 64), up(rows, 64), 1 }, 128, &g); + } + + /// The forward for training: P [rows, proj] bf16 (the layer's kept in-projection rows) after the prefix's conv. + pub fn forward(o: Ops, l: Layer, sc: Scratch, p: u64, hist: ?u64, init: ?u64, rows: usize) !void { + const s = Shape.init(rows, l.nk, l.nv); + try o.front(p, hist, l.conv_w, l.a_log, l.dt_bias, sc, s); + try o.scanFwd(init, sc, s); + } + + /// dx [rows, hidden] (+)= the layer's input gradient from gy [rows, hidden] fp32, its output's. + pub fn backward(o: Ops, l: Layer, sc: Scratch, p: u64, hist: ?u64, init: ?u64, gy: u64, dx: u64, rows: usize, add: bool) !void { + const s = Shape.init(rows, l.nk, l.nv); + try o.forward(l, sc, p, hist, init, rows); + try o.product(gy, l.out_proj, sc.dout, rows, sc, false); + try o.normBack(p, l.norm_w, sc, s, l.eps); + try o.scanBack(sc, s); + try o.qkBack(sc, s); + try o.gatesBack(p, l.a_log, l.dt_bias, sc, s); + try o.convBack(p, hist, l.conv_w, sc, s); + try o.product(sc.dproj, l.in_proj, dx, rows, sc, add); + } + + /// backward for several sequences of one pass side by side (their rows contiguous in gy and dx). + pub fn backwardAll(o: Ops, l: Layer, sc: Scratch, w: Wide, runs: []const Run, gy: u64, dx: u64, rows: usize, add: bool) !void { + const proj: usize = @intCast(Shape.init(1, l.nk, l.nv).proj); + if (o.q4) |q| try q.f(q.ctx, gy, l.out_proj, w.dout, rows, false) else try o.productWith(gy, l.out_proj, w.dout, rows, w.xb, sc.wt, false); + for (runs) |r| { + const s = Shape.init(r.rows, l.nk, l.nv); + var one = sc; + one.dout = w.dout + r.at * l.nv * dv * 4; + one.dproj = w.dproj + r.at * proj * 4; + try o.forward(l, one, r.p, r.hist, r.init, r.rows); + try o.normBack(r.p, l.norm_w, one, s, l.eps); + try o.scanBackFrom(one, s, r.from); + try o.qkBack(one, s); + try o.gatesBack(r.p, l.a_log, l.dt_bias, one, s); + try o.convBack(r.p, r.hist, l.conv_w, one, s); + } + if (o.q4) |q| try q.f(q.ctx, w.dproj, l.in_proj, dx, rows, add) else try o.productWith(w.dproj, l.in_proj, dx, rows, w.xb, sc.wt, add); + } +}; + +/// One sequence of a pass the layer's backward reads: its kept in-projection rows. +pub const Run = struct { p: u64, hist: ?u64 = null, init: ?u64 = null, rows: usize, at: usize, from: usize = 0 }; // from: the first row whose gradient is needed + +/// Buffers over every row of a pass: the out projection's input gradient [rows, nv dv] fp32. +pub const Wide = struct { + dout: u64, + dproj: u64, + xb: u64, + + pub fn bytes(rows: usize, nk: usize, nv: usize, hidden: usize) usize { + const proj: usize = @intCast(Shape.init(1, nk, nv).proj); + return Scratch.padded(rows * nv * dv * 4) + Scratch.padded(rows * proj * 4) + Scratch.padded(rows * @max(proj, hidden) * 2); + } + + pub fn carve(base: u64, rows: usize, nk: usize, nv: usize) Wide { + const proj: usize = @intCast(Shape.init(1, nk, nv).proj); + const dproj = base + Scratch.padded(rows * nv * dv * 4); + return .{ .dout = base, .dproj = dproj, .xb = dproj + Scratch.padded(rows * proj * 4) }; + } +}; + +test "the scratch buffers tile their allocation" { + const n = Scratch.bytes(256, 16, 48, 2560); + const sc = Scratch.carve(0, 256, 16, 48, 2560); + try std.testing.expect(sc.wt + 16480 * 2560 * 2 <= n); + try std.testing.expectEqual(@as(c_int, 16480), Shape.init(1, 16, 48).proj); + try std.testing.expectEqual(@as(usize, 256 / ck), Shape.init(256, 16, 48).chunks()); + try std.testing.expectEqual(@as(usize, 37 / ck + 1), Shape.init(37, 16, 48).chunks()); +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 8ff900952c..5756f7b8a2 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -33,6 +33,8 @@ pub const qwen_ops: []const u8 = if (available) &Blob("fatbin_qwen_ops").bytes e pub const qwen_vision: []const u8 = if (available) &Blob("fatbin_qwen_vision").bytes else &.{}; 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 attn_train: []const u8 = if (available) &Blob("fatbin_attn_train").bytes else &.{}; +pub const gdn_train: []const u8 = if (available) &Blob("fatbin_gdn_train").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 &.{}; diff --git a/zig/src/cuda/root.zig b/zig/src/cuda/root.zig index 3053c09a6b..ed8a12f3d3 100644 --- a/zig/src/cuda/root.zig +++ b/zig/src/cuda/root.zig @@ -36,6 +36,7 @@ pub const embed_rows = @import("embed_rows.zig"); pub const experts = @import("experts.zig"); pub const sample = @import("sample.zig"); pub const modelopt = @import("modelopt.zig"); +pub const gdn_train = @import("gdn_train.zig"); test { _ = @import("memory.zig"); @@ -54,4 +55,5 @@ test { _ = carveout; _ = @import("nvfp4.zig"); _ = @import("modelopt.zig"); + _ = @import("gdn_train.zig"); } diff --git a/zig/tests/cuda/gdn_back_ref.zig b/zig/tests/cuda/gdn_back_ref.zig new file mode 100644 index 0000000000..3a388f1526 --- /dev/null +++ b/zig/tests/cuda/gdn_back_ref.zig @@ -0,0 +1,433 @@ +//! Float64 reference of Flash Next's Gated DeltaNet layer (forward and input-gradient backward), for gdn-back. +const std = @import("std"); + +pub const taps = 4; + +pub const Dims = struct { + rows: usize, + nk: usize, + nv: usize, + dk: usize = 128, + dv: usize = 128, + + pub fn conv(d: Dims) usize { + return 2 * d.nk * d.dk + d.nv * d.dv; + } + + pub fn proj(d: Dims) usize { + return d.conv() + d.nv * d.dv + 2 * d.nv; + } + + /// The first column of z, b and a in a projection row. + pub fn zAt(d: Dims) usize { + return d.conv(); + } + + pub fn bAt(d: Dims) usize { + return d.conv() + d.nv * d.dv; + } + + pub fn aAt(d: Dims) usize { + return d.bAt() + d.nv; + } +}; + +/// The layer's inputs: P [rows, proj], hist [3, conv] or null, conv_w [conv, taps], a_log, dt_bias [nv], norm_w [dv]. +pub const Inputs = struct { + p: []const f64, + hist: ?[]const f64, + conv_w: []const f64, + a_log: []const f64, + dt_bias: []const f64, + norm_w: []const f64, + init: ?[]const f64, + eps: f64, +}; + +pub const Fwd = struct { + act: []f64, // [rows, conv] + q: []f64, // [rows, nk, dk] + k: []f64, + g: []f64, // [rows, nv] + beta: []f64, + y: []f64, // [rows, nv, dv] + out: []f64, // [rows, nv, dv] +}; + +pub const Grads = struct { + dy: []f64, // [rows, nv, dv]: the chain's output gradient + dq: []f64, // [rows, nk, dk]: the normalized q's gradient, summed over the key head's value heads + dk: []f64, + dact: []f64, // [rows, conv]: q, k after their norms; v + dg: []f64, // [rows, nv] + dbeta: []f64, + dproj: []f64, // [rows, proj]: qkv, z, b, a +}; + +pub fn bf16Bits(x: f32) u16 { + const b: u32 = @bitCast(x); + if (std.math.isNan(x)) return 0x7fc0; + return @truncate((b + 0x7fff + ((b >> 16) & 1)) >> 16); +} + +pub fn bf16Value(h: u16) f32 { + return @bitCast(@as(u32, h) << 16); +} + +pub fn bfRound(x: f64) f64 { + return bf16Value(bf16Bits(@floatCast(x))); +} + +fn sigmoid(x: f64) f64 { + return 1 / (1 + @exp(-x)); +} + +fn softplus(x: f64) f64 { + return if (x > 20) x else std.math.log1p(@exp(x)); +} + +fn convPre(d: Dims, in: Inputs, r: usize, c: usize) f64 { + const C = d.conv(); + var acc: f64 = 0; + for (0..taps) |tap| { + const at = @as(isize, @intCast(r)) - (taps - 1) + @as(isize, @intCast(tap)); + const x: f64 = if (at >= 0) in.p[@as(usize, @intCast(at)) * d.proj() + c] else if (in.hist) |h| h[@as(usize, @intCast(at + taps - 1)) * C + c] else 0; + acc += in.conv_w[c * taps + tap] * x; + } + return acc; +} + +fn gate(d: Dims, in: Inputs, r: usize, h: usize) f64 { + const a = in.p[r * d.proj() + d.aAt() + h]; + return @exp(-@exp(in.a_log[h]) * softplus(a + in.dt_bias[h])); +} + +/// q (or k) of row r, key head hk from act: x r (times dk^-0.5 for q), r = 1 / sqrt(|x|^2 + 1e-6). +fn l2(d: Dims, act: []const f64, r: usize, col: usize, scale: f64, out: []f64) void { + var ss: f64 = 0; + for (0..d.dk) |i| ss += act[r * d.conv() + col + i] * act[r * d.conv() + col + i]; + const inv = 1 / @sqrt(ss + 1e-6); + for (0..d.dk) |i| out[i] = act[r * d.conv() + col + i] * inv * scale; +} + +fn qk(d: Dims, act: []const f64, q: []f64, k: []f64) void { + const sc = 1 / @sqrt(@as(f64, @floatFromInt(d.dk))); + for (0..d.rows) |r| for (0..d.nk) |hk| { + l2(d, act, r, hk * d.dk, sc, q[(r * d.nk + hk) * d.dk ..][0..d.dk]); + l2(d, act, r, d.nk * d.dk + hk * d.dk, 1, k[(r * d.nk + hk) * d.dk ..][0..d.dk]); + }; +} + +/// The rounded forward's normalized, weighted read-out of one head, bf16(bf16(y rms) w). +fn normedRounded(y: []const f64, w: []const f64, eps: f64, out: []f64) void { + var lanes: [32]f32 = undefined; + for (&lanes, 0..) |*l, lane| { + var ss: f32 = 0; + for (0..4) |i| { + const v: f32 = @floatCast(y[lane * 4 + i]); + ss = ss + v * v; + } + l.* = ss; + } + var o: usize = 16; + while (o > 0) : (o >>= 1) { + var next: [32]f32 = undefined; + for (&next, 0..) |*x, lane| x.* = lanes[lane] + lanes[lane ^ o]; + lanes = next; + } + const rinv: f32 = 1.0 / @sqrt(lanes[0] / @as(f32, @floatFromInt(y.len)) + @as(f32, @floatCast(eps))); + for (out, y, w) |*x, v, wv| { + const n = bf16Value(bf16Bits(@as(f32, @floatCast(v)) * rinv)); + x.* = bf16Value(bf16Bits(n * @as(f32, @floatCast(wv)))); + } +} + +/// yn of one head: the rounded forward's (normedRounded), else y rms(y) w in float64. +fn normed(y: []const f64, w: []const f64, eps: f64, round: bool, out: []f64) void { + if (round) return normedRounded(y, w, eps, out); + var ss: f64 = 0; + for (y) |v| ss += v * v; + const rinv = 1 / @sqrt(ss / @as(f64, @floatFromInt(y.len)) + eps); + for (out, y, w) |*x, v, wv| x.* = v * rinv * wv; +} + +pub fn forward(a: std.mem.Allocator, d: Dims, in: Inputs, round: bool) !Fwd { + const C = d.conv(); + const P = d.proj(); + const act = try a.alloc(f64, d.rows * C); + const beta = try a.alloc(f64, d.rows * d.nv); + for (0..d.rows) |r| for (0..C) |c| { + const pre = convPre(d, in, r, c); + const v = pre * sigmoid(pre); + act[r * C + c] = if (round) bfRound(v) else v; + }; + for (0..d.rows) |r| for (0..d.nv) |h| { + const b = sigmoid(in.p[r * P + d.bAt() + h]); + beta[r * d.nv + h] = if (round) bfRound(b) else b; + }; + return forwardFrom(a, d, in, act, beta, round); +} + +/// The forward after the conv outputs act and the betas (the reference's own, or the GPU's). +pub fn forwardFrom(a: std.mem.Allocator, d: Dims, in: Inputs, act: []f64, betas: []f64, round: bool) !Fwd { + const C = d.conv(); + const P = d.proj(); + const f: Fwd = .{ + .act = act, + .q = try a.alloc(f64, d.rows * d.nk * d.dk), + .k = try a.alloc(f64, d.rows * d.nk * d.dk), + .g = try a.alloc(f64, d.rows * d.nv), + .beta = betas, + .y = try a.alloc(f64, d.rows * d.nv * d.dv), + .out = try a.alloc(f64, d.rows * d.nv * d.dv), + }; + qk(d, f.act, f.q, f.k); + for (0..d.rows) |r| for (0..d.nv) |h| { + f.g[r * d.nv + h] = gate(d, in, r, h); + }; + const S = try a.alloc(f64, d.dv * d.dk); + defer a.free(S); + for (0..d.nv) |h| { + const hk = h / (d.nv / d.nk); + if (in.init) |s0| @memcpy(S, s0[h * d.dv * d.dk ..][0 .. d.dv * d.dk]) else @memset(S, 0); + for (0..d.rows) |r| { + const g = f.g[r * d.nv + h]; + const beta = f.beta[r * d.nv + h]; + const kr = f.k[(r * d.nk + hk) * d.dk ..][0..d.dk]; + const qr = f.q[(r * d.nk + hk) * d.dk ..][0..d.dk]; + for (0..d.dv) |j| { + const row = S[j * d.dk ..][0..d.dk]; + var kv: f64 = 0; + for (row, kr) |*s, kk| { + s.* *= g; + kv += s.* * kk; + } + const delta = beta * (f.act[r * C + 2 * d.nk * d.dk + h * d.dv + j] - kv); + var o: f64 = 0; + for (row, kr, qr) |*s, kk, qq| { + s.* += kk * delta; + o += s.* * qq; + } + f.y[(r * d.nv + h) * d.dv + j] = if (round) bfRound(o) else o; + } + } + } + const yn = try a.alloc(f64, d.dv); + defer a.free(yn); + for (0..d.rows) |r| for (0..d.nv) |h| { + normed(f.y[(r * d.nv + h) * d.dv ..][0..d.dv], in.norm_w, in.eps, round, yn); + for (0..d.dv) |j| { + const z = in.p[r * P + d.zAt() + h * d.dv + j]; + const o = yn[j] * sigmoid(z); + f.out[(r * d.nv + h) * d.dv + j] = if (round) bfRound(o) else o; + } + }; + return f; +} + +/// The gradients at the forward point given by act, beta and y (the forward's own, or the GPU's), from dout [rows. +pub fn backward(a: std.mem.Allocator, d: Dims, in: Inputs, act: []const f64, beta: []const f64, y: []const f64, dout: []const f64, round: bool) !Grads { + const C = d.conv(); + const P = d.proj(); + const dkn = d.dk; + const gr: Grads = .{ + .dy = try a.alloc(f64, d.rows * d.nv * d.dv), + .dq = try a.alloc(f64, d.rows * d.nk * dkn), + .dk = try a.alloc(f64, d.rows * d.nk * dkn), + .dact = try a.alloc(f64, d.rows * C), + .dg = try a.alloc(f64, d.rows * d.nv), + .dbeta = try a.alloc(f64, d.rows * d.nv), + .dproj = try a.alloc(f64, d.rows * P), + }; + @memset(gr.dq, 0); + @memset(gr.dk, 0); + const q = try a.alloc(f64, d.rows * d.nk * dkn); + defer a.free(q); + const k = try a.alloc(f64, d.rows * d.nk * dkn); + defer a.free(k); + qk(d, act, q, k); + // the gated RMS norm + for (0..d.rows) |r| for (0..d.nv) |h| { + const yr = y[(r * d.nv + h) * d.dv ..][0..d.dv]; + var ss: f64 = 0; + for (yr) |v| ss += v * v; + const rinv = 1 / @sqrt(ss / @as(f64, @floatFromInt(d.dv)) + in.eps); + var dot: f64 = 0; + const dn = try a.alloc(f64, d.dv); + defer a.free(dn); + const yn = try a.alloc(f64, d.dv); + defer a.free(yn); + normed(yr, in.norm_w, in.eps, round, yn); + for (0..d.dv) |j| { + const zc = r * P + d.zAt() + h * d.dv + j; + const sg = sigmoid(in.p[zc]); + const go = dout[(r * d.nv + h) * d.dv + j]; + gr.dproj[zc] = go * yn[j] * sg * (1 - sg); + dn[j] = go * sg * in.norm_w[j]; + dot += yr[j] * dn[j]; + } + for (0..d.dv) |j| gr.dy[(r * d.nv + h) * d.dv + j] = rinv * dn[j] - rinv * rinv * rinv * yr[j] * dot / @as(f64, @floatFromInt(d.dv)); + }; + // the chain, each value head with every state it passes through + const size = d.dv * dkn; + const states = try a.alloc(f64, (d.rows + 1) * size); + defer a.free(states); + const ds = try a.alloc(f64, size); + defer a.free(ds); + const dqh = try a.alloc(f64, dkn); + defer a.free(dqh); + const dkh = try a.alloc(f64, dkn); + defer a.free(dkh); + const sd = try a.alloc(f64, dkn); + defer a.free(sd); + for (0..d.nv) |h| { + const hk = h / (d.nv / d.nk); + const v0 = 2 * d.nk * dkn + h * d.dv; + if (in.init) |s0| @memcpy(states[0..size], s0[h * size ..][0..size]) else @memset(states[0..size], 0); + for (0..d.rows) |r| { + const g = gate(d, in, r, h); + const b = beta[r * d.nv + h]; + const kr = k[(r * d.nk + hk) * dkn ..][0..dkn]; + const cur = states[(r + 1) * size ..][0..size]; + @memcpy(cur, states[r * size ..][0..size]); + for (0..d.dv) |j| { + const row = cur[j * dkn ..][0..dkn]; + var kv: f64 = 0; + for (row, kr) |*s, kk| { + s.* *= g; + kv += s.* * kk; + } + const delta = b * (act[r * C + v0 + j] - kv); + for (row, kr) |*s, kk| s.* += kk * delta; + } + } + @memset(ds, 0); + var r = d.rows; + while (r > 0) { + r -= 1; + const g = gate(d, in, r, h); + const b = beta[r * d.nv + h]; + const kr = k[(r * d.nk + hk) * dkn ..][0..dkn]; + const qr = q[(r * d.nk + hk) * dkn ..][0..dkn]; + const prev = states[r * size ..][0..size]; + const cur = states[(r + 1) * size ..][0..size]; + @memset(dqh, 0); + @memset(dkh, 0); + var dg: f64 = 0; + var db: f64 = 0; + for (0..d.dv) |j| { + const sp = prev[j * dkn ..][0..dkn]; + const sn = cur[j * dkn ..][0..dkn]; + const dsj = ds[j * dkn ..][0..dkn]; + var kv: f64 = 0; + for (sd, sp, kr) |*x, p, kk| { + x.* = g * p; + kv += x.* * kk; + } + const err = act[r * C + v0 + j] - kv; + const delta = b * err; + const dj = gr.dy[(r * d.nv + h) * d.dv + j]; + var dd: f64 = 0; + for (dsj, qr, kr, sn, dqh) |*x, qq, kk, s, *dq| { + x.* += dj * qq; + dq.* += dj * s; + dd += x.* * kk; + } + gr.dact[r * C + v0 + j] = b * dd; + db += dd * err; + for (dsj, kr, sd, sp, dkh) |*x, kk, s, p, *dk| { + dk.* += delta * x.* - b * dd * s; + const dsp = x.* - b * dd * kk; + dg += dsp * p; + x.* = g * dsp; + } + } + for (0..dkn) |i| { + gr.dq[(r * d.nk + hk) * dkn + i] += dqh[i]; + gr.dk[(r * d.nk + hk) * dkn + i] += dkh[i]; + } + gr.dg[r * d.nv + h] = dg; + gr.dbeta[r * d.nv + h] = db; + } + } + // the L2 norms + const sc = 1 / @sqrt(@as(f64, @floatFromInt(dkn))); + for (0..d.rows) |r| for (0..d.nk) |hk| for (0..2) |which| { + const col = which * d.nk * dkn + hk * dkn; + const dqk = (if (which == 0) gr.dq else gr.dk)[(r * d.nk + hk) * dkn ..][0..dkn]; + const x = act[r * C + col ..][0..dkn]; + var ss: f64 = 0; + var dot: f64 = 0; + for (x, dqk) |xi, di| { + ss += xi * xi; + dot += xi * di; + } + const inv = 1 / @sqrt(ss + 1e-6); + const s = if (which == 0) sc else 1; + for (0..dkn) |i| gr.dact[r * C + col + i] = s * inv * (dqk[i] - inv * inv * x[i] * dot); + }; + // the gates + for (0..d.rows) |r| for (0..d.nv) |h| { + const b = sigmoid(in.p[r * P + d.bAt() + h]); + const x = in.p[r * P + d.aAt() + h] + in.dt_bias[h]; + const slope = if (x > 20) 1 else sigmoid(x); + gr.dproj[r * P + d.bAt() + h] = gr.dbeta[r * d.nv + h] * b * (1 - b); + gr.dproj[r * P + d.aAt() + h] = -gr.dg[r * d.nv + h] * gate(d, in, r, h) * @exp(in.a_log[h]) * slope; + }; + // the conv and its SiLU + for (0..d.rows) |r| for (0..C) |c| { + var acc: f64 = 0; + for (0..taps) |tap| { + const at = r + taps - 1 - tap; + if (at >= d.rows) continue; + const pre = convPre(d, in, at, c); + const s = sigmoid(pre); + acc += in.conv_w[c * taps + tap] * gr.dact[at * C + c] * s * (1 + pre * (1 - s)); + } + gr.dproj[r * P + c] = acc; + }; + return gr; +} + +/// sum(dout * out) of the unrounded forward: the loss whose P-gradient the backward gives, for finite differences. +pub fn loss(a: std.mem.Allocator, d: Dims, in: Inputs, dout: []const f64) !f64 { + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + const f = try forward(arena.allocator(), d, in, false); + var s: f64 = 0; + for (f.out, dout) |o, g| s += o * g; + return s; +} + +/// Central differences of `loss` at `count` coordinates of P spread over every column kind, against the backward. +pub fn finiteCheck(a: std.mem.Allocator, d: Dims, in: Inputs, dout: []const f64, rng: std.Random, count: usize) !struct { worst: f64, scale: f64 } { + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + const aa = arena.allocator(); + const f = try forward(aa, d, in, false); + const gr = try backward(aa, d, in, f.act, f.beta, f.y, dout, false); + var top: f64 = 0; + for (gr.dproj) |v| top = @max(top, @abs(v)); + const p = try aa.dupe(f64, in.p); + var moved = in; + moved.p = p; + var worst: f64 = 0; + const P = d.proj(); + const kinds = [_][2]usize{ .{ 0, d.nk * d.dk }, .{ d.nk * d.dk, 2 * d.nk * d.dk }, .{ 2 * d.nk * d.dk, d.conv() }, .{ d.zAt(), d.bAt() }, .{ d.bAt(), d.aAt() }, .{ d.aAt(), P } }; + for (0..count) |i| { + const kind = kinds[i % kinds.len]; + const r = rng.uintLessThan(usize, d.rows); + const c = kind[0] + rng.uintLessThan(usize, kind[1] - kind[0]); + const at = r * P + c; + const h = 1e-5 * @max(1, @abs(in.p[at])); + p[at] = in.p[at] + h; + const up = try loss(aa, d, moved, dout); + p[at] = in.p[at] - h; + const down = try loss(aa, d, moved, dout); + p[at] = in.p[at]; + const fd = (up - down) / (2 * h); + const e = @abs(fd - gr.dproj[at]) / @max(@abs(gr.dproj[at]), 1e-3 * top); + worst = @max(worst, e); + } + return .{ .worst = worst, .scale = top }; +} diff --git a/zig/tests/cuda/gdn_back_tests.zig b/zig/tests/cuda/gdn_back_tests.zig new file mode 100644 index 0000000000..a0a32c9a0b --- /dev/null +++ b/zig/tests/cuda/gdn_back_tests.zig @@ -0,0 +1,471 @@ +//! gdn-back: Flash Next's Gated DeltaNet backward (flashnext_train.cu through cuda.gdn_train) against the float64. +const std = @import("std"); +const cuda = @import("cuda"); +const check = @import("check.zig"); +const ref = @import("gdn_back_ref.zig"); +const Gpu = check.Gpu; +const gt = cuda.gdn_train; + +const NK = 16; +const NV = 48; +var HIDDEN: usize = 2560; +var GROUP: usize = 32; +const EPS: f32 = 1e-6; +const DK = gt.dk; +const DV = gt.dv; +const SPLIT = gt.split; + +/// Tolerances: fp32 chains against float64 (worst column), and the projections. +const tol_f32 = 1e-3; +const tol_gemm = 3e-2; + +const Rig = struct { + gpu: Gpu, + a: std.mem.Allocator, + s: cuda.Stream, + rng: std.Random, + bufs: std.ArrayList(cuda.DeviceBuffer) = .empty, + bad: usize = 0, + + fn dev(r: *Rig, bytes: []const u8) !u64 { + const b = try cuda.DeviceBuffer.fromHost(r.gpu.d, bytes); + try r.bufs.append(r.gpu.gpa, b); + return b.ptr; + } + + fn alloc(r: *Rig, bytes: usize) !u64 { + const b = try cuda.DeviceBuffer.alloc(r.gpu.d, @max(bytes, 16)); + try r.bufs.append(r.gpu.gpa, b); + try b.fill8(0xff, r.s.handle); // NaN everywhere: an element no kernel writes cannot pass + return b.ptr; + } + + fn back(r: *Rig, comptime T: type, ptr: u64, n: usize) ![]T { + const out = try r.a.alloc(T, n); + try r.s.synchronize(); + const b: cuda.DeviceBuffer = .{ .d = r.gpu.d, .ptr = ptr, .len = n * @sizeOf(T) }; + try b.download(0, std.mem.sliceAsBytes(out)); + return out; + } + + fn uniform(r: *Rig, lo: f32, hi: f32) f32 { + return lo + r.rng.float(f32) * (hi - lo); + } + + fn bfs(r: *Rig, n: usize, lo: f32, hi: f32) ![]u16 { + const out = try r.a.alloc(u16, n); + for (out) |*v| v.* = ref.bf16Bits(r.uniform(lo, hi)); + return out; + } + + fn f32s(r: *Rig, n: usize, lo: f32, hi: f32) ![]f32 { + const out = try r.a.alloc(f32, n); + for (out) |*v| v.* = r.uniform(lo, hi); + return out; + } + + /// The worst column of got against want, both [rows, cols] (got at stride `gs` from `g0`, want likewise). + fn compare(r: *Rig, label: []const u8, rows: usize, cols: usize, got: anytype, want: anytype, tol: f64) void { + var worst: f64 = 0; + var worst_col: usize = 0; + var most: f64 = 0; + var scale: f64 = 0; + var nonfinite: usize = 0; + for (0..cols) |c| { + var e: f64 = 0; + var m: f64 = 0; + for (0..rows) |i| { + const g = got.at(i, c); + const w = want.at(i, c); + if (!std.math.isFinite(g)) nonfinite += 1; + e = @max(e, @abs(g - w)); + m = @max(m, @abs(w)); + } + most = @max(most, e); + scale = @max(scale, m); + const rel = if (m > 0) e / m else if (e > 0) std.math.inf(f64) else 0; + if (rel > worst) { + worst = rel; + worst_col = c; + } + } + const ok = nonfinite == 0 and worst <= tol; + if (!ok) r.bad += 1; + std.debug.print("RESULT gdn-back {s:<22} worst column rel {e:9.2} (col {d:>5}), max abs {e:9.2}, ref scale {e:9.2}{s}\n", .{ label, worst, worst_col, most, scale, if (nonfinite > 0) " NONFINITE" else if (ok) "" else " OVER TOLERANCE" }); + } +}; + +/// A [rows, cols] window of a flat slice (f64, f32, or bf16 bits): element (i, c) at i * stride + c0 + c. +fn View(comptime T: type) type { + return struct { + x: []const T, + stride: usize, + c0: usize = 0, + rows: ?[]const usize = null, // the rows compared, when a subset + + fn at(v: @This(), i: usize, c: usize) f64 { + const row = if (v.rows) |rs| rs[i] else i; + const e = v.x[row * v.stride + v.c0 + c]; + return switch (T) { + f64 => e, + f32 => e, + u16 => ref.bf16Value(e), + else => @compileError("view of " ++ @typeName(T)), + }; + } + }; +} + +fn view(comptime T: type, x: []const T, stride: usize, c0: usize) View(T) { + return .{ .x = x, .stride = stride, .c0 = c0 }; +} + +fn widen(a: std.mem.Allocator, comptime T: type, x: []const T) ![]f64 { + const out = try a.alloc(f64, x.len); + for (out, x) |*o, v| o.* = switch (T) { + u16 => ref.bf16Value(v), + f32 => v, + else => @compileError("widen"), + }; + return out; +} + +/// bf16 results against the reference's rounded values: elements that differ and the largest difference in ulps. +fn ulps(label: []const u8, got: []const u16, want: []const f64) void { + var differ: usize = 0; + var most: u32 = 0; + for (got, want) |g, w| { + const wb = ref.bf16Bits(@floatCast(w)); + if (g != wb) { + differ += 1; + const gi: i32 = if (g & 0x8000 != 0) -@as(i32, g & 0x7fff) else g; + const wi: i32 = if (wb & 0x8000 != 0) -@as(i32, wb & 0x7fff) else wb; + most = @max(most, @abs(gi - wi)); + } + } + std.debug.print("RESULT gdn-back forward {s:<14} {d} of {d} bf16 values differ from float64's rounding, at most {d} ulp\n", .{ label, differ, got.len, most }); +} + +/// A random MLX affine 4-bit [n, k] matrix with `GROUP`-wide groups, values about +-0.04. +const Q4Host = struct { + w: []u32, + s: []u16, + b: []u16, + n: usize, + k: usize, + + fn random(r: *Rig, n: usize, k: usize) !Q4Host { + const m: Q4Host = .{ .w = try r.a.alloc(u32, n * k / 8), .s = try r.a.alloc(u16, n * k / GROUP), .b = try r.a.alloc(u16, n * k / GROUP), .n = n, .k = k }; + for (m.w) |*v| v.* = r.rng.int(u32); + for (m.s, m.b) |*s, *b| { + const sc = r.uniform(0.002, 0.008); + s.* = ref.bf16Bits(sc); + b.* = ref.bf16Bits(-7.5 * sc * r.uniform(0.8, 1.2)); + } + return m; + } + + /// Row i in float64: scale code + bias, undequantized to bf16. + fn row(m: Q4Host, i: usize, out: []f64) void { + for (0..m.k) |j| { + const at = i * m.k + j; + const code: f64 = @floatFromInt((m.w[at / 8] >> @intCast(4 * (at % 8))) & 0xf); + out[j] = @as(f64, ref.bf16Value(m.s[at / GROUP])) * code + ref.bf16Value(m.b[at / GROUP]); + } + } + + fn upload(m: Q4Host, r: *Rig) !gt.Q4 { + return .{ .w = try r.dev(std.mem.sliceAsBytes(m.w)), .s = try r.dev(std.mem.sliceAsBytes(m.s)), .b = try r.dev(std.mem.sliceAsBytes(m.b)), .n = m.n, .k = m.k, .group = GROUP }; + } +}; + +/// out[i] = x[rows[i]] (len m.n) times the matrix [m.n, m.k], float64. +fn timesMatrix(a: std.mem.Allocator, x: []const f64, rows: []const usize, m: Q4Host, bf16_operands: bool) ![]f64 { + const out = try a.alloc(f64, rows.len * m.k); + @memset(out, 0); + const w = try a.alloc(f64, m.k); + for (0..m.n) |n| { + m.row(n, w); + if (bf16_operands) for (w) |*v| { + v.* = ref.bfRound(v.*); + }; + for (rows, 0..) |r, i| { + const xv = if (bf16_operands) ref.bfRound(x[r * m.n + n]) else x[r * m.n + n]; + if (xv == 0) continue; + const o = out[i * m.k ..][0..m.k]; + for (o, w) |*y, wv| y.* += xv * wv; + } + } + return out; +} + +const Case = struct { rows: usize, prefix: bool, every: usize }; // every: rows the projections' references cover + +fn runCase(r: *Rig, case: Case, kern: *const gt.Kernels) !void { + const rows = case.rows; + const s = gt.Shape.init(rows, NK, NV); + const C: usize = @intCast(s.conv); + const P: usize = @intCast(s.proj); + const d: ref.Dims = .{ .rows = rows, .nk = NK, .nv = NV }; + std.debug.print("--- gdn-back: {d} rows, {s}\n", .{ rows, if (case.prefix) "after a prefix (conv history and state)" else "from the sequence start" }); + + // inputs: projection rows by column kind, the prefix, weights, the layer output's gradient + const p16 = try r.a.alloc(u16, rows * P); + for (0..rows) |i| for (0..P) |c| { + const v = if (c < C) r.uniform(-1.5, 1.5) else r.uniform(-3, 3); + p16[i * P + c] = ref.bf16Bits(v); + }; + const hist16: ?[]u16 = if (case.prefix) try r.bfs(3 * C, -1.5, 1.5) else null; + const cw16 = try r.bfs(C * gt.taps, -0.6, 0.6); + const a_log = try r.f32s(NV, -2, 0.5); + const dt_bias = try r.f32s(NV, -1, 1); + const nw16 = try r.bfs(DV, 0.5, 1.5); + const init: ?[]f32 = if (case.prefix) try r.f32s(NV * DV * DK, -0.3, 0.3) else null; + const gy = try r.f32s(rows * HIDDEN, -0.01, 0.01); + const in_q = try Q4Host.random(r, P, HIDDEN); + const out_q = try Q4Host.random(r, HIDDEN, NV * DV); + + const layer: gt.Layer = .{ + .nk = NK, + .nv = NV, + .hidden = HIDDEN, + .eps = EPS, + .conv_w = try r.dev(std.mem.sliceAsBytes(cw16)), + .a_log = try r.dev(std.mem.sliceAsBytes(a_log)), + .dt_bias = try r.dev(std.mem.sliceAsBytes(dt_bias)), + .norm_w = try r.dev(std.mem.sliceAsBytes(nw16)), + .in_proj = try in_q.upload(r), + .out_proj = try out_q.upload(r), + }; + const p_d = try r.dev(std.mem.sliceAsBytes(p16)); + const hist_d: ?u64 = if (hist16) |h| try r.dev(std.mem.sliceAsBytes(h)) else null; + const init_d: ?u64 = if (init) |x| try r.dev(std.mem.sliceAsBytes(x)) else null; + const gy_d = try r.dev(std.mem.sliceAsBytes(gy)); + const bytes = gt.Scratch.bytes(rows, NK, NV, HIDDEN); + const sc = gt.Scratch.carve(try r.alloc(bytes), rows, NK, NV, HIDDEN); + const dx_d = try r.alloc(rows * HIDDEN * 4); + + const o: gt.Ops = .{ .k = kern, .s = r.s }; + try o.backward(layer, sc, p_d, hist_d, init_d, gy_d, dx_d, rows, false); + try r.s.synchronize(); + + // time: the whole layer, and the layer without its two projections + var start = try cuda.Event.init(r.gpu.d, true); + defer start.deinit(); + var end = try cuda.Event.init(r.gpu.d, true); + defer end.deinit(); + var whole: [5]f64 = undefined; + var core: [5]f64 = undefined; + for (&whole, &core) |*w, *cr| { + try start.record(r.s); + try o.backward(layer, sc, p_d, hist_d, init_d, gy_d, dx_d, rows, false); + try end.record(r.s); + try end.synchronize(); + w.* = try start.elapsedMs(end); + try start.record(r.s); + try o.forward(layer, sc, p_d, hist_d, init_d, rows); + try o.normBack(p_d, layer.norm_w, sc, s, EPS); + try o.scanBack(sc, s); + try o.qkBack(sc, s); + try o.gatesBack(p_d, layer.a_log, layer.dt_bias, sc, s); + try o.convBack(p_d, hist_d, layer.conv_w, sc, s); + try end.record(r.s); + try end.synchronize(); + cr.* = try start.elapsedMs(end); + } + const ck_bytes = s.chunks() * NV * DV * DK * 4; + std.debug.print("RESULT gdn-back time {d} rows: layer backward {d:.3} ms (forward for training, chain and gates {d:.3} ms, the rest the two projections' dequant and GEMM); scratch {d:.1} MiB (checkpoints {d:.1}, replay {d:.1}, dequantized projection {d:.1})\n", .{ + rows, check.median(&whole), check.median(&core), + @as(f64, @floatFromInt(bytes)) / (1 << 20), @as(f64, @floatFromInt(ck_bytes)) / (1 << 20), @as(f64, @floatFromInt(gt.ck * NV * DV * DK * 4)) / (1 << 20), + @as(f64, @floatFromInt(P * HIDDEN * 2)) / (1 << 20), + }); + // each step alone, then the core again: every buffer holds this pass's values + { + var ev: [8]cuda.Event = undefined; + for (&ev) |*e| e.* = try cuda.Event.init(r.gpu.d, true); + defer for (&ev) |*e| e.deinit(); + try ev[0].record(r.s); + try o.front(p_d, hist_d, layer.conv_w, layer.a_log, layer.dt_bias, sc, s); + try ev[1].record(r.s); + try o.scanFwd(init_d, sc, s); + try ev[2].record(r.s); + try o.normBack(p_d, layer.norm_w, sc, s, EPS); + try ev[3].record(r.s); + try o.scanBack(sc, s); + try ev[4].record(r.s); + try o.qkBack(sc, s); + try ev[5].record(r.s); + try o.gatesBack(p_d, layer.a_log, layer.dt_bias, sc, s); + try ev[6].record(r.s); + try o.convBack(p_d, hist_d, layer.conv_w, sc, s); + try ev[7].record(r.s); + try ev[7].synchronize(); + var ms: [7]f32 = undefined; + for (&ms, 0..) |*m, i| m.* = try ev[i].elapsedMs(ev[i + 1]); + std.debug.print("RESULT gdn-back steps {d} rows (ms): front {d:.3}, scan_fwd {d:.3}, norm_back {d:.3}, scan_back {d:.3}, qk_back {d:.3}, gates_back {d:.3}, conv_back {d:.3}\n", .{ rows, ms[0], ms[1], ms[2], ms[3], ms[4], ms[5], ms[6] }); + } + + const g_act = try r.back(u16, sc.act, rows * C); + const g_q = try r.back(f32, sc.q, rows * NK * DK); + const g_k = try r.back(f32, sc.k, rows * NK * DK); + const g_g = try r.back(f32, sc.g, rows * NV); + const g_beta = try r.back(f32, sc.beta, rows * NV); + const g_y = try r.back(u16, sc.y, rows * NV * DV); + const g_dout = try r.back(f32, sc.dout, rows * NV * DV); + const g_dy = try r.back(f32, sc.dy, rows * NV * DV); + const g_dqp = try r.back(f32, sc.dqp, rows * NV * SPLIT * DK); + const g_dkp = try r.back(f32, sc.dkp, rows * NV * SPLIT * DK); + const g_dact = try r.back(f32, sc.dact, rows * C); + const g_dgp = try r.back(f32, sc.dg, rows * NV * SPLIT); + const g_dbp = try r.back(f32, sc.dbeta, rows * NV * SPLIT); + // the chain blocks' shares summed in block order, as the gates' backward sums them + const g_dg = try r.a.alloc(f32, rows * NV); + const g_dbeta = try r.a.alloc(f32, rows * NV); + for (g_dg, g_dbeta, 0..) |*x, *y, i| { + x.* = 0; + y.* = 0; + for (0..SPLIT) |p| { + x.* += g_dgp[i * SPLIT + p]; + y.* += g_dbp[i * SPLIT + p]; + } + } + const g_dproj = try r.back(f32, sc.dproj, rows * P); + const g_dx = try r.back(f32, dx_d, rows * HIDDEN); + + // the reference + const in: ref.Inputs = .{ + .p = try widen(r.a, u16, p16), + .hist = if (hist16) |h| try widen(r.a, u16, h) else null, + .conv_w = try widen(r.a, u16, cw16), + .a_log = try widen(r.a, f32, a_log), + .dt_bias = try widen(r.a, f32, dt_bias), + .norm_w = try widen(r.a, u16, nw16), + .init = if (init) |x| try widen(r.a, f32, x) else null, + .eps = EPS, + }; + const f = try ref.forward(r.a, d, in, true); + ulps("act", g_act, f.act); + ulps("beta", blk: { + const b = try r.a.alloc(u16, rows * NV); + for (b, g_beta) |*x, v| x.* = ref.bf16Bits(v); + break :blk b; + }, f.beta); + // the rest of the forward from the GPU's conv outputs and betas + const act64 = try widen(r.a, u16, g_act); + const beta64 = try widen(r.a, f32, g_beta); + const fg = try ref.forwardFrom(r.a, d, in, act64, beta64, true); + ulps("y", g_y, fg.y); + r.compare("forward q", rows, NK * DK, view(f32, g_q, NK * DK, 0), view(f64, fg.q, NK * DK, 0), tol_f32); + r.compare("forward k", rows, NK * DK, view(f32, g_k, NK * DK, 0), view(f64, fg.k, NK * DK, 0), tol_f32); + r.compare("forward g", rows, NV, view(f32, g_g, NV, 0), view(f64, fg.g, NV, 0), tol_f32); + r.compare("forward y", rows, NV * DV, view(u16, g_y, NV * DV, 0), view(f64, fg.y, NV * DV, 0), 2e-2); + + // the projections on every `every`-th row + var picked: std.ArrayList(usize) = .empty; + var i: usize = 0; + while (i < rows) : (i += case.every) try picked.append(r.a, i); + const gy64 = try widen(r.a, f32, gy); + const dout_ref = try timesMatrix(r.a, gy64, picked.items, out_q, false); + const sub = picked.items; + r.compare("dout (o_proj back)", sub.len, NV * DV, View(f32){ .x = g_dout, .stride = NV * DV, .rows = sub }, view(f64, dout_ref, NV * DV, 0), tol_gemm); + const dout_b16 = try timesMatrix(r.a, gy64, sub, out_q, true); + r.compare("dout, bf16 operands", sub.len, NV * DV, View(f32){ .x = g_dout, .stride = NV * DV, .rows = sub }, view(f64, dout_b16, NV * DV, 0), tol_f32); + + // the backward at the GPU's forward point + const y64 = try widen(r.a, u16, g_y); + const dout64 = try widen(r.a, f32, g_dout); + const gr = try ref.backward(r.a, d, in, act64, beta64, y64, dout64, true); + const dq_sum = try r.a.alloc(f64, rows * NK * DK); + const dk_sum = try r.a.alloc(f64, rows * NK * DK); + for (0..rows) |row| for (0..NK) |hk| for (0..DK) |e| { + var x: f64 = 0; + var y: f64 = 0; + for (hk * (NV / NK)..(hk + 1) * (NV / NK)) |h| { + for (0..SPLIT) |p| { + x += g_dqp[((row * NV + h) * SPLIT + p) * DK + e]; + y += g_dkp[((row * NV + h) * SPLIT + p) * DK + e]; + } + } + dq_sum[(row * NK + hk) * DK + e] = x; + dk_sum[(row * NK + hk) * DK + e] = y; + }; + r.compare("dy (norm back)", rows, NV * DV, view(f32, g_dy, NV * DV, 0), view(f64, gr.dy, NV * DV, 0), tol_f32); + r.compare("dz", rows, NV * DV, view(f32, g_dproj, P, C), view(f64, gr.dproj, P, C), tol_f32); + r.compare("dq (chain)", rows, NK * DK, view(f64, dq_sum, NK * DK, 0), view(f64, gr.dq, NK * DK, 0), tol_f32); + r.compare("dk (chain)", rows, NK * DK, view(f64, dk_sum, NK * DK, 0), view(f64, gr.dk, NK * DK, 0), tol_f32); + r.compare("dv (chain)", rows, NV * DV, view(f32, g_dact, C, 2 * NK * DK), view(f64, gr.dact, C, 2 * NK * DK), tol_f32); + r.compare("dg (chain)", rows, NV, view(f32, g_dg, NV, 0), view(f64, gr.dg, NV, 0), tol_f32); + r.compare("dbeta (chain)", rows, NV, view(f32, g_dbeta, NV, 0), view(f64, gr.dbeta, NV, 0), tol_f32); + r.compare("dact q (L2 back)", rows, NK * DK, view(f32, g_dact, C, 0), view(f64, gr.dact, C, 0), tol_f32); + r.compare("dact k (L2 back)", rows, NK * DK, view(f32, g_dact, C, NK * DK), view(f64, gr.dact, C, NK * DK), tol_f32); + r.compare("dproj q (conv back)", rows, NK * DK, view(f32, g_dproj, P, 0), view(f64, gr.dproj, P, 0), tol_f32); + r.compare("dproj k (conv back)", rows, NK * DK, view(f32, g_dproj, P, NK * DK), view(f64, gr.dproj, P, NK * DK), tol_f32); + r.compare("dproj v (conv back)", rows, NV * DV, view(f32, g_dproj, P, 2 * NK * DK), view(f64, gr.dproj, P, 2 * NK * DK), tol_f32); + r.compare("dproj b (beta back)", rows, NV, view(f32, g_dproj, P, d.bAt()), view(f64, gr.dproj, P, d.bAt()), tol_f32); + r.compare("dproj a (g back)", rows, NV, view(f32, g_dproj, P, d.aAt()), view(f64, gr.dproj, P, d.aAt()), tol_f32); + const dx_ref = try timesMatrix(r.a, gr.dproj, sub, in_q, false); + r.compare("dx (in_proj back)", sub.len, HIDDEN, View(f32){ .x = g_dx, .stride = HIDDEN, .rows = sub }, view(f64, dx_ref, HIDDEN, 0), tol_gemm); + const dx_b16 = try timesMatrix(r.a, try widen(r.a, f32, g_dproj), sub, in_q, true); + r.compare("dx, bf16 operands", sub.len, HIDDEN, View(f32){ .x = g_dx, .stride = HIDDEN, .rows = sub }, view(f64, dx_b16, HIDDEN, 0), tol_f32); +} + +/// run at another layer width and projection group (the 27B: hidden 5120, group 64). +pub fn runShape(gpu: Gpu, hidden: usize, group: usize) !void { + HIDDEN = hidden; + GROUP = group; + return run(gpu); +} + +pub fn run(gpu: Gpu) !void { + var arena: std.heap.ArenaAllocator = .init(gpu.gpa); + defer arena.deinit(); + var prng = std.Random.DefaultPrng.init(0x6d17_bac4); + var r: Rig = .{ .gpu = gpu, .a = arena.allocator(), .s = try cuda.Stream.init(gpu.d, true), .rng = prng.random() }; + defer { + for (r.bufs.items) |*b| b.free(); + r.bufs.deinit(gpu.gpa); + r.s.deinit(); + } + var kern = try gt.Kernels.load(gpu.d); + defer kern.deinit(); + + // the reference against its own central differences: small heads, a prefix, every column kind of P + { + var fa: std.heap.ArenaAllocator = .init(gpu.gpa); + defer fa.deinit(); + const a = fa.allocator(); + for ([_]ref.Dims{ .{ .rows = 6, .nk = 2, .nv = 6 }, .{ .rows = 9, .nk = 1, .nv = 3 } }) |d| { + const p = try a.alloc(f64, d.rows * d.proj()); + for (p, 0..) |*v, i| v.* = if (i % d.proj() < d.conv()) r.uniform(-1.5, 1.5) else r.uniform(-3, 3); + const hist = try a.alloc(f64, 3 * d.conv()); + for (hist) |*v| v.* = r.uniform(-1.5, 1.5); + const cw = try a.alloc(f64, d.conv() * ref.taps); + for (cw) |*v| v.* = r.uniform(-0.6, 0.6); + const al = try a.alloc(f64, d.nv); + const db = try a.alloc(f64, d.nv); + for (al, db) |*x, *y| { + x.* = r.uniform(-2, 0.5); + y.* = r.uniform(-1, 1); + } + const nw = try a.alloc(f64, d.dv); + for (nw) |*v| v.* = r.uniform(0.5, 1.5); + const s0 = try a.alloc(f64, d.nv * d.dv * d.dk); + for (s0) |*v| v.* = r.uniform(-0.3, 0.3); + const dout = try a.alloc(f64, d.rows * d.nv * d.dv); + for (dout) |*v| v.* = r.uniform(-1, 1); + const in: ref.Inputs = .{ .p = p, .hist = hist, .conv_w = cw, .a_log = al, .dt_bias = db, .norm_w = nw, .init = s0, .eps = EPS }; + const fd = try ref.finiteCheck(a, d, in, dout, r.rng, 120); + const ok = fd.worst < 1e-5; + if (!ok) r.bad += 1; + std.debug.print("RESULT gdn-back finite differences ({d} rows, {d} key / {d} value heads): 120 coordinates of P, worst |fd - analytic| / max(|analytic|, 1e-3 max) {e:.2}{s}\n", .{ d.rows, d.nk, d.nv, fd.worst, if (ok) "" else " OVER TOLERANCE" }); + } + } + + for ([_]Case{ .{ .rows = 64, .prefix = true, .every = 1 }, .{ .rows = 256, .prefix = false, .every = 8 }, .{ .rows = 37, .prefix = true, .every = 4 } }) |case| { + try runCase(&r, case, &kern); + for (r.bufs.items) |*b| b.free(); + r.bufs.clearRetainingCapacity(); + } + try check.expect(r.bad == 0, "gdn-back: {d} checks over tolerance", .{r.bad}); + check.pass("gdn-back: forward for training and every input gradient within tolerance of float64", .{}); +} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index aec6b9ec1b..42e0d0e594 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -29,6 +29,7 @@ const norms_tests = @import("norms_tests.zig"); const norm_rows_tests = @import("norm_rows_tests.zig"); const pocket_tests = @import("pocket_tests.zig"); const recapture_tests = @import("recapture_tests.zig"); +const gdn_back_tests = @import("gdn_back_tests.zig"); const usage = \\usage: tf-cuda-test @@ -69,6 +70,8 @@ const usage = \\ exlr8-bench DIR [MANIFEST] [LAYER] [SETS] a real EXLR8 layer: FP64, row windows, then GB/s by stage \\ exlr8-dense [DIR] EXLR8 dense formats: decode bit-equal, FP64, row windows; DIR adds the real matrices \\ train-pack MODEL EXAMPLES [COUNT] training passes holding several sequences against one a pass: differences, time + \\ gdn-back Living Weights' DeltaNet backward against float64 references (synthetic) + \\ gdn-back-27b the same DeltaNet backward at the 27B's shapes (hidden 5120, group-64 projections) \\ ; @@ -146,6 +149,8 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { return carveout_tests.run(gpu, if (rest.len > 1) rest[1] else cuda.carveout.default_card, mib); } if (std.mem.eql(u8, cmd, "train-pack")) return train_pack.run(gpu, try arg(rest, 0), try arg(rest, 1), if (rest.len > 2) try std.fmt.parseInt(usize, rest[2], 10) else 24); + if (std.mem.eql(u8, cmd, "gdn-back")) return gdn_back_tests.run(gpu); + if (std.mem.eql(u8, cmd, "gdn-back-27b")) return gdn_back_tests.runShape(gpu, 5120, 64); std.debug.print("{s}", .{usage}); return error.UnknownCommand; } From 018d2b2a96de242e57886f3721fc13720be2f29d Mon Sep 17 00:00:00 2001 From: ZackSample <134018356+ZackSample@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:10:23 -0500 Subject: [PATCH 17/17] Qwen3.8-27B on CUDA learns: Living Weights' pocket beside every MLP, the trainer, its backward kernels and --slide - pocket.zig: fp32 SwiGLU neurons a layer, added after each MLP's down projection in every pass (prompt chunks, drafted windows, decode rounds), row by row so drafted equals "draft": false; untaught streams (the lesson writer's judge) read no pocket. A taught folder's widened MLP keeps its own 17408 rows tiled, the pocket's in fp32. - train.zig, train_more.zig, train_load.zig, train_ops.zig, qwen27_train.cu: the learner's passes (keys, loss, target) with 16 sequences side by side on the engine's own batched pass; the loss's gradient from the group-64 head down through the dense SwiGLU MLPs and pocket, gated attention and the DeltaNet (core gdn_train), on MLX copies of layers 12-63; wide 4-bit products (tf_q27_gemm_q4w) and the backward only on rows a nudge needs (same bits); input-weight fits on the GPU with the host's bits; greedy scoring through serving's own decode rounds. - tap.zig, hooks.zig: a prompt in a conversation read through the engine's prompt pass (the context fix's tapRows). - slide.zig, native.zig: --slide for qwen3_5, the pocket written through the core's shard writer. - tf-qwen27-learn: packed passes == alone, the push against finite differences, Q27_GATE (gate taps, with activations) and Q27_SCORE (replies teacher-forced through serial decode); tf-cuda-test q27-back and q27-gemm. --- zig/build/cuda.zig | 7 + zig/kernels/cuda/qwen27_train.cu | 537 +++++++++++++++++++ zig/src/cli/qwen27_learn.zig | 553 ++++++++++++++++++++ zig/src/cli/qwen27_taps.zig | 146 ++++++ zig/src/cuda/kernels.zig | 1 + zig/src/families/qwen27/cuda.zig | 9 + zig/src/families/qwen27/cuda/engine.zig | 38 +- zig/src/families/qwen27/cuda/forward.zig | 59 +++ zig/src/families/qwen27/cuda/hooks.zig | 72 +++ zig/src/families/qwen27/cuda/lanes.zig | 1 + zig/src/families/qwen27/cuda/native.zig | 25 +- zig/src/families/qwen27/cuda/pocket.zig | 186 +++++++ zig/src/families/qwen27/cuda/shape.zig | 20 +- zig/src/families/qwen27/cuda/slide.zig | 119 +++++ zig/src/families/qwen27/cuda/state.zig | 23 + zig/src/families/qwen27/cuda/tap.zig | 223 ++++++++ zig/src/families/qwen27/cuda/train.zig | 550 +++++++++++++++++++ zig/src/families/qwen27/cuda/train_load.zig | 147 ++++++ zig/src/families/qwen27/cuda/train_more.zig | 205 ++++++++ zig/src/families/qwen27/cuda/train_ops.zig | 420 +++++++++++++++ zig/src/families/qwen27/cuda/weights.zig | 114 +++- zig/tests/cuda/main.zig | 12 + zig/tests/cuda/q27_back_attn.zig | 422 +++++++++++++++ zig/tests/cuda/q27_back_rig.zig | 235 +++++++++ zig/tests/cuda/q27_back_tests.zig | 227 ++++++++ zig/tests/cuda/q27_gemm_tests.zig | 143 +++++ 26 files changed, 4477 insertions(+), 17 deletions(-) create mode 100644 zig/kernels/cuda/qwen27_train.cu create mode 100644 zig/src/cli/qwen27_learn.zig create mode 100644 zig/src/cli/qwen27_taps.zig create mode 100644 zig/src/families/qwen27/cuda/hooks.zig create mode 100644 zig/src/families/qwen27/cuda/pocket.zig create mode 100644 zig/src/families/qwen27/cuda/slide.zig create mode 100644 zig/src/families/qwen27/cuda/tap.zig create mode 100644 zig/src/families/qwen27/cuda/train.zig create mode 100644 zig/src/families/qwen27/cuda/train_load.zig create mode 100644 zig/src/families/qwen27/cuda/train_more.zig create mode 100644 zig/src/families/qwen27/cuda/train_ops.zig create mode 100644 zig/tests/cuda/q27_back_attn.zig create mode 100644 zig/tests/cuda/q27_back_rig.zig create mode 100644 zig/tests/cuda/q27_back_tests.zig create mode 100644 zig/tests/cuda/q27_gemm_tests.zig diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index ed204133a5..594eba392a 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -35,6 +35,7 @@ const kernels = [_]Kernel{ .{ .name = "train", .flags = &.{"-O3"} }, // ours: Sliding Weights' learning step (train.metal's kernels) .{ .name = "attn_train", .flags = &.{"-O3"} }, // ours: Living Weights' gated attention backward, shared .{ .name = "gdn_train", .flags = &.{ "-O3", "--fmad=false" } }, // ours: Living Weights' DeltaNet backward (gdn_train.zig) + .{ .name = "qwen27_train", .flags = &.{"-O3"} }, // ours: the 27B's pocket, dense MLP backward and group-64 products .{ .name = "qwen_ops", .flags = &.{"-O3"} }, // ours: the 27B's batched state copies, taps, drafter norms and rotary .{ .name = "qwen_vision", .flags = &.{ "-O3", "--fmad=false" } }, // ours: the Qwen3.5 vision tower's glue and attention .{ .name = "nemotron_norms", .flags = glue }, // ours, each with a host reference (glue_ref.zig): Nemotron's glue @@ -150,6 +151,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu runner.addImport("core", mods.core); runner.addImport("lanes", mods.lanes); runner.addImport("nemotron", mods.nemotron); + runner.addImport("qwen27", mods.qwen27); const exlr8 = exlr8_build.coreAlias(b, target, optimize, mods.core); runner.addImport("exlr8", exlr8); const exlr8_tests = exlr8_build.testModules(b, target, optimize, exlr8); @@ -162,6 +164,11 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu qwen_cli.addImport("cuda", cuda); qwen_cli.addImport("qwen27", mods.qwen27); b.installArtifact(b.addExecutable(.{ .name = "tf-qwen27-cuda", .root_module = qwen_cli })); + // Living Weights' trainer on the 27B, checked on the GPU (packed passes, the push, gate taps, scored replies) + const qwen_learn = b.createModule(.{ .root_source_file = b.path("zig/src/cli/qwen27_learn.zig"), .target = target, .optimize = optimize, .link_libc = true }); + qwen_learn.addImport("cuda", cuda); + qwen_learn.addImport("qwen27", mods.qwen27); + b.installArtifact(b.addExecutable(.{ .name = "tf-qwen27-learn", .root_module = qwen_learn })); nativeServer(b, target, optimize, cuda, mods.core, mods.lanes, mods.nemotron, mods.qwen27, mods.tokenizer, mods.living, build_options, true).root_module.strip = strip; } diff --git a/zig/kernels/cuda/qwen27_train.cu b/zig/kernels/cuda/qwen27_train.cu new file mode 100644 index 0000000000..f81b441bb7 --- /dev/null +++ b/zig/kernels/cuda/qwen27_train.cu @@ -0,0 +1,537 @@ +// Living Weights on the 27B: the pocket beside each dense MLP, its input gradients and group-64 4-bit products. + +#include +#include + +typedef __nv_bfloat16 bf16; + +__device__ __forceinline__ float f32(bf16 v) { return __bfloat162float(v); } +__device__ __forceinline__ bf16 b16(float v) { return __float2bfloat16(v); } +__device__ __forceinline__ float wide(float v) { return v; } +__device__ __forceinline__ float wide(bf16 v) { return __bfloat162float(v); } + +__device__ __forceinline__ float warp_sum(float v) { +#pragma unroll + for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o); + return v; +} + +// The sum over a block of `groups` warps, the same in every thread. +__device__ __forceinline__ float block_sum(float v, float* scratch, int groups) { + const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; + v = warp_sum(v); + if (lane == 0) scratch[w] = v; + __syncthreads(); + v = warp_sum(lane < groups ? scratch[lane] : 0.0f); + __syncthreads(); + return v; +} + +__device__ __forceinline__ float sigm(float v) { return 1.0f / (1.0f + expf(-v)); } +__device__ __forceinline__ float silu(float v) { return v / (1.0f + expf(-v)); } + +__device__ __forceinline__ float silu_grad(float v) { + const float s = sigm(v); + return s * (1.0f + v * (1.0f - s)); +} + +// ---- 4-bit products, any group -------------------------------------------------------------------------------------- + +// C [M, N] (+)= A [M, K] W for a 4-bit MLX [K, N] W: a linear's input gradient, split K partials in C + z M N. +template +__device__ __forceinline__ void gemm_q4(const TA* __restrict__ A, const unsigned* __restrict__ W, const bf16* __restrict__ S, + const bf16* __restrict__ B, float* __restrict__ C, int M, int N, int K, int lda, int ldc, + int accumulate, int kchunk, int group) { + __shared__ __align__(16) bf16 As[64][40]; + __shared__ __align__(16) bf16 Bs[64][40]; // W's tile transposed: [n][k] + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int m0 = blockIdx.y * 64, n0 = blockIdx.x * 64; + const int kb = blockIdx.z * kchunk, ke = min(K, kb + kchunk); + const int wm = (warp >> 1) * 32, wn = (warp & 1) * 32; + const int words = N / 8, groups = N / group; + float acc[2][4][4]; +#pragma unroll + for (int i = 0; i < 2; i++) +#pragma unroll + for (int j = 0; j < 4; j++) +#pragma unroll + for (int e = 0; e < 4; e++) acc[i][j][e] = 0.0f; + const bf16 zero = b16(0.0f); + const bool wide_a = sizeof(TA) == 2 && (lda & 7) == 0 && ((size_t)A & 15) == 0; + for (int k0 = kb; k0 < ke; k0 += 32) { + for (int e = tid; e < 64 * 4; e += 128) { + const int r = e >> 2, c = (e & 3) * 8, gm = m0 + r, gk = k0 + c; + if (wide_a && gm < M && gk + 8 <= ke) { + *reinterpret_cast(&As[r][c]) = *reinterpret_cast(A + (size_t)gm * lda + gk); + } else { + for (int i = 0; i < 8; i++) As[r][c + i] = (gm < M && gk + i < ke) ? b16(wide(A[(size_t)gm * lda + gk + i])) : zero; + } + } + for (int e = tid; e < 32 * 8; e += 128) { + const int r = e >> 3, c = e & 7, gk = k0 + r, gn = n0 + c * 8; + if (gk < ke && gn < N) { + const unsigned q = W[(size_t)gk * words + gn / 8]; + const float s = f32(S[(size_t)gk * groups + gn / group]), b = f32(B[(size_t)gk * groups + gn / group]); +#pragma unroll + for (int i = 0; i < 8; i++) Bs[c * 8 + i][r] = b16(fmaf(s, (float)((q >> (4 * i)) & 0xfu), b)); + } else { +#pragma unroll + for (int i = 0; i < 8; i++) Bs[c * 8 + i][r] = zero; + } + } + __syncthreads(); +#pragma unroll + for (int kk = 0; kk < 32; kk += 16) { + unsigned af[2][4], bq[4][2]; +#pragma unroll + for (int i = 0; i < 2; i++) { + const int r = wm + i * 16 + (lane >> 2), c = kk + (lane & 3) * 2; + af[i][0] = *reinterpret_cast(&As[r][c]); + af[i][1] = *reinterpret_cast(&As[r + 8][c]); + af[i][2] = *reinterpret_cast(&As[r][c + 8]); + af[i][3] = *reinterpret_cast(&As[r + 8][c + 8]); + } +#pragma unroll + for (int j = 0; j < 4; j++) { + const int n = wn + j * 8 + (lane >> 2), k = kk + (lane & 3) * 2; + bq[j][0] = *reinterpret_cast(&Bs[n][k]); + bq[j][1] = *reinterpret_cast(&Bs[n][k + 8]); + } +#pragma unroll + for (int i = 0; i < 2; i++) +#pragma unroll + for (int j = 0; j < 4; j++) + asm volatile( + "mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0, %1, %2, %3}, {%4, %5, %6, %7}, {%8, %9}, " + "{%0, %1, %2, %3};\n" + : "+f"(acc[i][j][0]), "+f"(acc[i][j][1]), "+f"(acc[i][j][2]), "+f"(acc[i][j][3]) + : "r"(af[i][0]), "r"(af[i][1]), "r"(af[i][2]), "r"(af[i][3]), "r"(bq[j][0]), "r"(bq[j][1])); + } + __syncthreads(); + } + const bool split = gridDim.z > 1; + float* out0 = split ? C + (size_t)blockIdx.z * M * N : C; + const int ld = split ? N : ldc; +#pragma unroll + for (int i = 0; i < 2; i++) +#pragma unroll + for (int j = 0; j < 4; j++) +#pragma unroll + for (int h = 0; h < 2; h++) { + const int r = m0 + wm + i * 16 + (lane >> 2) + h * 8, c = n0 + wn + j * 8 + (lane & 3) * 2; + if (r >= M) continue; +#pragma unroll + for (int e = 0; e < 2; e++) { + if (c + e >= N) continue; + float* out = out0 + (size_t)r * ld + c + e; + const float v = acc[i][j][h * 2 + e]; + *out = (accumulate && !split) ? *out + v : v; + } + } +} + +extern "C" __global__ void __launch_bounds__(128) tf_q27_gemm_q4(const float* A, const unsigned* W, const bf16* S, const bf16* B, + float* C, int M, int N, int K, int lda, int ldc, int accumulate, + int kchunk, int group) { + gemm_q4(A, W, S, B, C, M, N, K, lda, ldc, accumulate, kchunk, group); +} + +// tf_q27_gemm_q4 with bf16 A: the head's gradient from tf_train_softmax's bf16 rows. +extern "C" __global__ void __launch_bounds__(128) tf_q27_gemm_q4_bf(const bf16* A, const unsigned* W, const bf16* S, const bf16* B, + float* C, int M, int N, int K, int lda, int ldc, int accumulate, + int kchunk, int group) { + gemm_q4(A, W, S, B, C, M, N, K, lda, ldc, accumulate, kchunk, group); +} + +// ---- 4-bit products, wide tiles. + +__device__ __forceinline__ unsigned smem_at(const void* p) { return static_cast(__cvta_generic_to_shared(p)); } + +__device__ __forceinline__ void ld4(unsigned (&r)[4], const void* p) { + asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0, %1, %2, %3}, [%4];\n" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(smem_at(p))); +} + +__device__ __forceinline__ void ld4t(unsigned (&r)[4], const void* p) { + asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0, %1, %2, %3}, [%4];\n" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(smem_at(p))); +} + +// gemm_q4's products bit for bit. +template +__device__ __forceinline__ void gemm_q4w(const TA* __restrict__ A, const unsigned* __restrict__ W, const bf16* __restrict__ S, + const bf16* __restrict__ B, float* __restrict__ C, int M, int N, int K, int lda, int ldc, + int accumulate, int kchunk, int group, const int* __restrict__ rows) { + constexpr int BM = 128, BN = 128, BK = 32, AS = BK + 8, BS = BN + 8; + constexpr int AV = sizeof(TA) == 4 ? 4 : 2; // A's 16-byte loads a thread + __shared__ __align__(16) bf16 As[2][BM][AS]; + __shared__ __align__(16) bf16 Bs[2][BK][BS]; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int m0 = blockIdx.y * BM, n0 = blockIdx.x * BN; + const int kb = blockIdx.z * kchunk, ke = min(K, kb + kchunk); + const int wm = (warp >> 2) * 64, wn = (warp & 3) * 32; + const int words = N / 8, groups = N / group; + // this thread's share of a slab: A's 16-byte pieces, W's two words and their scales and biases + const TA* arow[AV]; + int acol[AV], ar[AV]; +#pragma unroll + for (int v = 0; v < AV; v++) { + const int f = tid + 256 * v; + ar[v] = sizeof(TA) == 4 ? f >> 3 : f >> 2; + acol[v] = sizeof(TA) == 4 ? (f & 7) * 4 : (f & 3) * 8; + const int gm = m0 + ar[v]; + arow[v] = gm < M ? A + (size_t)(rows ? rows[gm] : gm) * lda : nullptr; + } + const int kr = tid >> 3, nw = (tid & 7) * 2; + const int g0 = (n0 + nw * 8) / group, g1 = (n0 + nw * 8 + 8) / group; + uint4 ra[AV]; + uint2 rw; + float rs0, rb0, rs1, rb1; + auto fetch = [&](int k0) { +#pragma unroll + for (int v = 0; v < AV; v++) ra[v] = arow[v] ? *reinterpret_cast(arow[v] + k0 + acol[v]) : make_uint4(0, 0, 0, 0); + const size_t gk = (size_t)(k0 + kr); + rw = *reinterpret_cast(W + gk * words + n0 / 8 + nw); + rs0 = f32(S[gk * groups + g0]), rb0 = f32(B[gk * groups + g0]); + rs1 = f32(S[gk * groups + g1]), rb1 = f32(B[gk * groups + g1]); + }; + auto place = [&](int buf) { +#pragma unroll + for (int v = 0; v < AV; v++) { + if (sizeof(TA) == 4) { + const float4 x = *reinterpret_cast(&ra[v]); + __nv_bfloat162 lo = __floats2bfloat162_rn(x.x, x.y), hi = __floats2bfloat162_rn(x.z, x.w); + uint2 p; + p.x = *reinterpret_cast(&lo); + p.y = *reinterpret_cast(&hi); + *reinterpret_cast(&As[buf][ar[v]][acol[v]]) = p; + } else { + *reinterpret_cast(&As[buf][ar[v]][acol[v]]) = ra[v]; + } + } + const unsigned wv[2] = {rw.x, rw.y}; + const float sv[2] = {rs0, rs1}, bv[2] = {rb0, rb1}; +#pragma unroll + for (int e = 0; e < 2; e++) { + __align__(16) bf16 o[8]; +#pragma unroll + for (int i = 0; i < 8; i++) o[i] = b16(fmaf(sv[e], (float)((wv[e] >> (4 * i)) & 0xfu), bv[e])); + *reinterpret_cast(&Bs[buf][kr][nw * 8 + e * 8]) = *reinterpret_cast(o); + } + }; + float acc[4][4][4]; +#pragma unroll + for (int i = 0; i < 4; i++) +#pragma unroll + for (int j = 0; j < 4; j++) +#pragma unroll + for (int e = 0; e < 4; e++) acc[i][j][e] = 0.0f; + if (kb < ke) fetch(kb); + int buf = 0; + for (int k0 = kb; k0 < ke; k0 += BK, buf ^= 1) { + place(buf); + __syncthreads(); + if (k0 + BK < ke) fetch(k0 + BK); +#pragma unroll + for (int kk = 0; kk < BK; kk += 16) { + unsigned af[4][4], bq[4][2]; +#pragma unroll + for (int i = 0; i < 4; i++) ld4(af[i], &As[buf][wm + i * 16 + (lane & 7) + ((lane >> 3) & 1) * 8][kk + (lane >> 4) * 8]); +#pragma unroll + for (int jp = 0; jp < 2; jp++) { + unsigned r[4]; + ld4t(r, &Bs[buf][kk + (lane & 7) + ((lane >> 3) & 1) * 8][wn + (jp * 2 + (lane >> 4)) * 8]); + bq[2 * jp][0] = r[0], bq[2 * jp][1] = r[1], bq[2 * jp + 1][0] = r[2], bq[2 * jp + 1][1] = r[3]; + } +#pragma unroll + for (int i = 0; i < 4; i++) +#pragma unroll + for (int j = 0; j < 4; j++) + asm volatile( + "mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0, %1, %2, %3}, {%4, %5, %6, %7}, {%8, %9}, " + "{%0, %1, %2, %3};\n" + : "+f"(acc[i][j][0]), "+f"(acc[i][j][1]), "+f"(acc[i][j][2]), "+f"(acc[i][j][3]) + : "r"(af[i][0]), "r"(af[i][1]), "r"(af[i][2]), "r"(af[i][3]), "r"(bq[j][0]), "r"(bq[j][1])); + } + } + const bool split = gridDim.z > 1; + float* out0 = split ? C + (size_t)blockIdx.z * M * N : C; + const int ld = split ? N : ldc; +#pragma unroll + for (int i = 0; i < 4; i++) +#pragma unroll + for (int h = 0; h < 2; h++) { + const int r = m0 + wm + i * 16 + (lane >> 2) + h * 8; + if (r >= M) continue; + const int rr = (rows && !split) ? rows[r] : r; +#pragma unroll + for (int j = 0; j < 4; j++) { + const int c = n0 + wn + j * 8 + (lane & 3) * 2; + float2* out = reinterpret_cast(out0 + (size_t)rr * ld + c); + float2 v = make_float2(acc[i][j][h * 2], acc[i][j][h * 2 + 1]); + if (accumulate && !split) { + const float2 o = *out; + v.x = o.x + v.x; + v.y = o.y + v.y; + } + *out = v; + } + } +} + +extern "C" __global__ void __launch_bounds__(256, 2) tf_q27_gemm_q4w(const float* A, const unsigned* W, const bf16* S, const bf16* B, + float* C, int M, int N, int K, int lda, int ldc, int accumulate, + int kchunk, int group, const int* rows) { + gemm_q4w(A, W, S, B, C, M, N, K, lda, ldc, accumulate, kchunk, group, rows); +} + +extern "C" __global__ void __launch_bounds__(256, 2) tf_q27_gemm_q4w_bf(const bf16* A, const unsigned* W, const bf16* S, const bf16* B, + float* C, int M, int N, int K, int lda, int ldc, int accumulate, + int kchunk, int group, const int* rows) { + gemm_q4w(A, W, S, B, C, M, N, K, lda, ldc, accumulate, kchunk, group, rows); +} + +// ---- the dense MLP -------------------------------------------------------------------------------------------------- + +// act = silu(gate) up undone from dact: dgate = dact up silu'(gate), dup = dact silu(gate), n values. +extern "C" __global__ void tf_q27_swiglu_back(const bf16* gate, const bf16* up, const float* dact, float* dgate, float* dup, + long long n) { + const long long i = (long long)blockIdx.x * 256 + threadIdx.x; + if (i >= n) return; + const float g = f32(gate[i]), u = f32(up[i]), d = dact[i]; + dgate[i] = d * u * silu_grad(g); + dup[i] = d * silu(g); +} + +// ---- the pocket's neurons (SwiGLU, beside the dense MLP) ------------------------------------------------------------ + +#define POCKET_MAX 128 + +// Neuron j's dot products on row y (d values): z = (gate_j . y, up_j . y) and, when g is set, e = down_j . g. +__device__ __forceinline__ void pocket_dots(const bf16* y, const float* g, int d, const float* gate, const float* up, + const float* down, int j, float& zg, float& zu, float& e) { + const int lane = threadIdx.x & 31; + const float* gj = gate + (size_t)j * d; + const float* uj = up + (size_t)j * d; + const float* dj = down + (size_t)j * d; + float a = 0, b = 0, c = 0; + for (int i = lane; i < d; i += 32) { + const float v = f32(y[i]); + a += gj[i] * v; + b += uj[i] * v; + if (g) c += dj[i] * g[i]; + } + zg = warp_sum(a), zu = warp_sum(b), e = g ? warp_sum(c) : 0.0f; +} + +// Neuron j's scale on row r: the row's own (rs[r], a pass's sequence scale) from neuron `from` on, else 1. +__device__ __forceinline__ float pocket_scale(const float* rs, int from, int j, int r) { + return (rs != nullptr && j >= from) ? rs[r] : 1.0f; +} + +// out[r] = bf16(out[r] + sum_j f_j silu(gate_j . y_r) (up_j . y_r) down_j); grid rows, block 256. +extern "C" __global__ void __launch_bounds__(256) tf_q27_pocket_rows(const bf16* y, int d, const float* gate, const float* up, + const float* down, int n, bf16* out, const float* rs, int from) { + __shared__ float act[POCKET_MAX]; + const int r = blockIdx.x, lane = threadIdx.x & 31, w = threadIdx.x >> 5; + const bf16* yr = y + (size_t)r * d; + for (int j = w; j < n; j += 8) { + float zg, zu, e; + pocket_dots(yr, nullptr, d, gate, up, down, j, zg, zu, e); + if (lane == 0) act[j] = pocket_scale(rs, from, j, r) * silu(zg) * zu; + } + __syncthreads(); + for (int k = threadIdx.x; k < d; k += 256) { + float v = 0; + for (int j = 0; j < n; j++) v += act[j] * down[(size_t)j * d + k]; + bf16* o = out + (size_t)r * d + k; + *o = b16(f32(*o) + v); + } +} + +// The pocket undone on row r: dx[r] += sum_j f_j (down_j . g) (silu'(zg) zu gate_j + silu(zg) up_j). +extern "C" __global__ void __launch_bounds__(256) tf_q27_pocket_back(const bf16* y, int d, const float* gate, const float* up, + const float* down, int n, const float* g, float* dx, + const float* rs, int from) { + __shared__ float cg[POCKET_MAX], cu[POCKET_MAX]; + const int r = blockIdx.x, lane = threadIdx.x & 31, w = threadIdx.x >> 5; + const bf16* yr = y + (size_t)r * d; + const float* gr = g + (size_t)r * d; + for (int j = w; j < n; j += 8) { + float zg, zu, e; + pocket_dots(yr, gr, d, gate, up, down, j, zg, zu, e); + if (lane == 0) { + const float f = pocket_scale(rs, from, j, r); + cg[j] = f * e * silu_grad(zg) * zu; + cu[j] = f * e * silu(zg); + } + } + __syncthreads(); + for (int k = threadIdx.x; k < d; k += 256) { + float v = 0; + for (int j = 0; j < n; j++) v += cg[j] * gate[(size_t)j * d + k] + cu[j] * up[(size_t)j * d + k]; + dx[(size_t)r * d + k] += v; + } +} + +// grad[j] += w act_j push[rows[j]]: neuron j's output vector's gradient (no row when negative). +extern "C" __global__ void __launch_bounds__(256) tf_q27_pocket_grad(const bf16* y, int d, const float* gate, const float* up, + int n, const float* push, const int* rows, float w, + float* grad) { + __shared__ float scratch[32]; + const int j = blockIdx.x, t = threadIdx.x; + if (j >= n) return; + const int r = rows[j]; + if (r < 0) return; + const bf16* yr = y + (size_t)r * d; + float a = 0, b = 0; + for (int i = t; i < d; i += 256) { + const float v = f32(yr[i]); + a += gate[(size_t)j * d + i] * v; + b += up[(size_t)j * d + i] * v; + } + a = block_sum(a, scratch, 8); + b = block_sum(b, scratch, 8); + const float k = w * silu(a) * b; + for (int i = t; i < d; i += 256) grad[(size_t)j * d + i] += k * push[(size_t)r * d + i]; +} + +// ---- a pass's keeps ------------------------------------------------------------------------------------------------- + +// dst[r, col0 + c] = src[r, c] for c below w: a projection's bf16 rows into their columns of a wider kept row. +extern "C" __global__ void tf_q27_cols(const bf16* src, int w, bf16* dst, int ld, int col0, int rows) { + const long long i = (long long)blockIdx.x * 256 + threadIdx.x; + if (i >= (long long)rows * w) return; + const long long r = i / w, c = i % w; + dst[r * ld + col0 + c] = src[i]; +} + +// y[i] = bf16(y[i] + x[i]) for n values: a nudge onto its row of the MLP's bf16 output. +extern "C" __global__ void tf_q27_add_bf16(bf16* y, const float* x, int n) { + const int i = blockIdx.x * 256 + threadIdx.x; + if (i < n) y[i] = b16(f32(y[i]) + x[i]); +} + +// x[r] = 0 for each row r of a pass the backward no longer needs (mask[r] == 0), ld values a row; grid rows. +extern "C" __global__ void tf_q27_zero_rows(float* x, int ld, const unsigned char* mask) { + const int r = blockIdx.x; + if (mask[r]) return; + for (int i = threadIdx.x; i < ld; i += 256) x[(size_t)r * ld + i] = 0.0f; +} + +// ---- a pocket neuron's input weights fitted on the device. + +// Kinds as pocket_fit.Kind numbers them. +#define FIT_FACT 0 +#define FIT_HELD 1 +#define FIT_STEADY 2 +#define FIT_OTHER 3 + +// The eight lanes' sum as the host's @reduce(.Add) forms it: ORDER 0 in order, 1 as halves, quarters, pairs. +template +__device__ __forceinline__ float fit_reduce8(float v) { + const int lane = threadIdx.x & 31; + if (ORDER == 0) { + float s = __shfl_sync(0xffffffffu, v, 0); + for (int j = 1; j < 8; j++) s = __fadd_rn(s, __shfl_sync(0xffffffffu, v, j)); + return s; + } + // (v0 + v4, v1 + v5, v2 + v6, v3 + v7), then (w0 + w2, w1 + w3), then x0 + x1 + const float w = __fadd_rn(v, __shfl_sync(0xffffffffu, v, (lane + 4) & 31)); + const float x = __fadd_rn(w, __shfl_sync(0xffffffffu, w, (lane + 2) & 31)); + const float y = __fadd_rn(x, __shfl_sync(0xffffffffu, x, (lane + 1) & 31)); + return __shfl_sync(0xffffffffu, y, 0); +} + +// A step's dot products: c[l][i] the row's hinge coefficient (0 on the right side, held and free rows). +template +__device__ __forceinline__ void fit_dots(const bf16* __restrict__ X, int m, int d, const float* __restrict__ U, + const unsigned char* __restrict__ kinds, const float* __restrict__ invs, float below, + float* __restrict__ C, int* __restrict__ wrong) { + extern __shared__ float us[]; + const int l = blockIdx.y, lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + for (int k = threadIdx.x; k < d; k += 256) us[k] = U[(size_t)l * d + k]; + __syncthreads(); + const int i = blockIdx.x * 8 + warp; + if (i >= m) return; + const int kind = kinds[(size_t)l * m + i]; + float* c = C + (size_t)l * m + i; + if (kind == FIT_HELD || kind > FIT_OTHER) { + if (lane == 0) *c = 0.0f; + return; + } + const bf16* x = X + ((size_t)l * m + i) * d; + float acc = 0.0f; + for (int t = lane; t < d; t += 32) acc = __fadd_rn(acc, __fmul_rn(us[t], f32(x[t]))); + // lane j < 8: (acc[j] + acc[j + 8]) + (acc[j + 16] + acc[j + 24]). + const float a8 = __shfl_down_sync(0xffffffffu, acc, 8), a16 = __shfl_down_sync(0xffffffffu, acc, 16), + a24 = __shfl_down_sync(0xffffffffu, acc, 24); + const float v = __fadd_rn(__fadd_rn(acc, a8), __fadd_rn(a16, a24)); + const float z = __fmul_rn(fit_reduce8(v), invs[l]); + if (lane != 0) return; + float ci = 0.0f; + if (kind == FIT_FACT) { + if (z < 1.0f) { + ci = __fmul_rn(-2.0f, __fsub_rn(1.0f, z)); + atomicAdd(&wrong[l * 4 + 0], 1); + } + } else if (z > -below) { + ci = __fmul_rn(2.0f, __fadd_rn(z, below)); + atomicAdd(&wrong[l * 4 + (kind == FIT_STEADY ? 1 : 2)], 1); + } + *c = ci; +} + +extern "C" __global__ void __launch_bounds__(256) tf_q27_fit_dots(const bf16* X, int m, int d, const float* U, const unsigned char* kinds, + const float* invs, float below, float* C, int* wrong) { + fit_dots<0>(X, m, d, U, kinds, invs, below, C, wrong); +} + +extern "C" __global__ void __launch_bounds__(256) tf_q27_fit_dots_tree(const bf16* X, int m, int d, const float* U, + const unsigned char* kinds, const float* invs, float below, + float* C, int* wrong) { + fit_dots<1>(X, m, d, U, kinds, invs, below, C, wrong); +} + +// A step's gradient and Adam: each group's wrong rows summed in row order (y + c x, as axpyRow). +extern "C" __global__ void __launch_bounds__(256) tf_q27_fit_step(const bf16* __restrict__ X, int m, int d, + const unsigned char* __restrict__ kinds, const float* __restrict__ C, + const int* __restrict__ wrong, const float* __restrict__ invs, + float* __restrict__ U, float* __restrict__ M, float* __restrict__ Vv, + float rate, float c1, float c2) { + __shared__ float cs[1024]; + __shared__ unsigned char ks[1024]; + const int l = blockIdx.y, col = blockIdx.x * 256 + threadIdx.x; + float p[3] = {0.0f, 0.0f, 0.0f}; + for (int r0 = 0; r0 < m; r0 += 1024) { + const int n = min(1024, m - r0); + __syncthreads(); + for (int r = threadIdx.x; r < n; r += 256) { + cs[r] = C[(size_t)l * m + r0 + r]; + ks[r] = kinds[(size_t)l * m + r0 + r]; + } + __syncthreads(); + if (col >= d) continue; + for (int r = 0; r < n; r++) { + const float c = cs[r]; + if (c == 0.0f) continue; + const float x = f32(X[((size_t)l * m + r0 + r) * d + col]); + const int at = ks[r] == FIT_FACT ? 0 : (ks[r] == FIT_STEADY ? 1 : 2); + p[at] = __fadd_rn(p[at], __fmul_rn(c, x)); + } + } + if (col >= d) return; + const float inv = invs[l]; + float g = 0.0f; +#pragma unroll + for (int at = 0; at < 3; at++) g = __fadd_rn(g, __fmul_rn(__fdiv_rn(inv, (float)max(wrong[l * 4 + at], 1)), p[at])); + const size_t k = (size_t)l * d + col; + const float ui = U[k]; + const float gg = __fadd_rn(g, __fmul_rn(2e-4f, ui)); + const float mi = __fadd_rn(__fmul_rn(0.9f, M[k]), __fmul_rn(0.1f, gg)); + const float vi = __fadd_rn(__fmul_rn(0.999f, Vv[k]), __fmul_rn(__fmul_rn(0.001f, gg), gg)); + M[k] = mi; + Vv[k] = vi; + const float st = __fdiv_rn(__fmul_rn(rate, __fdiv_rn(mi, c1)), __fadd_rn(__fsqrt_rn(__fdiv_rn(vi, c2)), 1e-8f)); + U[k] = __fsub_rn(ui, st); +} diff --git a/zig/src/cli/qwen27_learn.zig b/zig/src/cli/qwen27_learn.zig new file mode 100644 index 0000000000..3b3947ae8b --- /dev/null +++ b/zig/src/cli/qwen27_learn.zig @@ -0,0 +1,553 @@ +//! tf-qwen27-learn MODEL KERNELS IDS_JSON: the 27B's trainer on the GPU (packing, push vs differences, a pocket). +const std = @import("std"); +const cuda = @import("cuda"); +const qwen = @import("qwen27"); +const qwen27_taps = @import("qwen27_taps.zig"); +const gates = qwen27_taps.gates; +const scores = qwen27_taps.scores; + +const train = qwen.train; +const Trainer = train.Trainer; +const D = 5120; +const turn: train.Turn = .{ .decide = 0, .bits = .empty, .whole = true }; + +fn now(io: std.Io) f64 { + return @as(f64, @floatFromInt(std.Io.Clock.awake.now(io).toNanoseconds())) / 1e9; +} + +fn dot(a: []const f32, b: []const f32) f64 { + var s: f64 = 0; + for (a, b) |x, y| s += @as(f64, x) * y; + return s; +} + +pub fn bf(b: u16) f64 { + return @as(f32, @bitCast(@as(u32, b) << 16)); +} + +fn norm16(xs: []const u16) f64 { + var s: f64 = 0; + for (xs) |b| s += bf(b) * bf(b); + return @sqrt(s); +} + +/// The loss's slope along `dir` at sequence sq's key-k nudge of layer l: a least-squares line through +-h .. +-6h. +fn slope(t: *Trainer, sq: *const train.Seq, k: usize, l: usize, dir: []const f32, h: f64) !f64 { + var num: f64 = 0; + var den: f64 = 0; + for (1..7) |m| for ([_]f64{ 1, -1 }) |sgn| { + const x = sgn * @as(f64, @floatFromInt(m)) * h; + for (t.deltaAt(0, k, l), dir) |*o, u| o.* = @floatCast(x * u); + var r: [1]train.Result = undefined; + try t.pass(&.{sq.*}, .loss, turn, &r); + num += x * r[0].loss; + den += x * x; + }; + @memset(t.deltaAt(0, k, l), 0); + return num / den; +} + +fn readIds(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u32 { + const text = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 24)); + defer gpa.free(text); + var doc = try std.json.parseFromSlice(std.json.Value, gpa, text, .{}); + defer doc.deinit(); + const arr = switch (doc.value) { + .array => |a| a, + .object => |o| (o.get("code") orelse return error.BadIds).array, + else => return error.BadIds, + }; + const out = try gpa.alloc(u32, arr.items.len); + for (out, arr.items) |*o, v| o.* = @intCast(v.integer); + return out; +} + +fn greedyVsPass(gpa: std.mem.Allocator, io: std.Io, e: *qwen.Engine, t: *Trainer, all: []const u32, failures: *usize) !void { + const V = qwen.config.vocab; + const steps = 48; + const prompts = 12; + var seq = try e.sequence(4096); + defer seq.deinit(); + const dec = try gpa.alloc(u16, steps * V); + defer gpa.free(dec); + const pre = try gpa.alloc(u16, V); + defer gpa.free(pre); + var picks_dev = try cuda.DeviceBuffer.alloc(e.ctx.d, 1024 * 4); + defer picks_dev.free(); + var rows_equal: usize = 0; + var rows_all: usize = 0; + var picks_equal: usize = 0; + var most: f64 = 0; + const a0 = now(io); + for (0..prompts) |k| { + const p = all[k * 300 ..][0 .. 20 + 7 * k]; + // greedy serial decode: the prompt's pass, then one-row rounds, each round's logits kept + try e.prefill(&seq, p); + var f = e.forward(); + try f.head(&seq); + var pick: [1]u32 = undefined; + try f.picks(1, &pick); + var toks: std.ArrayList(u32) = .empty; + defer toks.deinit(gpa); + try toks.append(gpa, pick[0]); + try e.ops().download(std.mem.sliceAsBytes(dec[0..V]), e.scratch.logits); + try e.s.synchronize(); + // the first pick's logits are the head over the prompt's last row (dense, 1 row) + while (toks.items.len < steps) { + const last = toks.items[toks.items.len - 1]; + const part = [_]qwen.Part{.{ .seq = &seq, .tokens = &.{last} }}; + try f.round(&part); + try f.picks(1, &pick); + try e.ops().download(std.mem.sliceAsBytes(dec[toks.items.len * V ..][0..V]), e.scratch.logits); + try e.s.synchronize(); + try f.commit(&part, &.{&.{0}}); + try toks.append(gpa, pick[0]); + } + // one batched prompt pass over prompt + decoded tokens, every row's logits (the trainer's keep) + const ids = try std.mem.concat(gpa, u32, &.{ p, toks.items }); + defer gpa.free(ids); + const n = ids.len - 1; + var keep = t.keep; + keep.layers = t.light; + var g = e.forward(); + g.keep = &keep; + try t.states[0].reset(e.ops(), e.w.g); + try g.chunks(&.{.{ .ids = ids[0..n], .seq = &t.states[0], .last = false }}); + try e.ops().argmax(t.logits, V, V, picks_dev.ptr, n); + var got: [1024]u32 = undefined; + try e.ops().download(std.mem.sliceAsBytes(got[0..n]), picks_dev.ptr); + try e.s.synchronize(); + var agree: usize = 0; + var same_rows: usize = 0; + for (0..steps) |j| { + const row = p.len - 1 + j; + agree += @intFromBool(got[row] == toks.items[j]); + const d = e.ctx.d; + try d.check(d.api.cuMemcpyDtoH_v2(pre.ptr, t.logits + row * V * 2, V * 2), "cuMemcpyDtoH"); + var eq = true; + for (pre, dec[j * V ..][0..V]) |x, y| { + if (x != y) eq = false; + most = @max(most, @abs(bf(x) - bf(y))); + } + same_rows += @intFromBool(eq); + } + rows_all += steps; + rows_equal += same_rows; + picks_equal += agree; + std.debug.print(" prompt {d} ({d} tokens): {d}/{d} pass argmaxes equal the greedy tokens, {d}/{d} rows' logits bit-equal\n", .{ k, p.len, agree, steps, same_rows, steps }); + } + // the same decoded tokens teacher-forced through decode rounds. + for ([_]bool{ false, true }) |multi| { + try e.fit(prompts); + var seqs: [prompts]qwen.state.Seq = undefined; + for (&seqs) |*q| q.* = try e.sequence(4096); + defer for (&seqs) |*q| q.deinit(); + var toks_all: [prompts][]u32 = undefined; + var bit_rows: usize = 0; + var pick_rows: usize = 0; + var rows_n: usize = 0; + var f = e.forward(); + const decs = try gpa.alloc(u16, prompts * steps * V); + defer gpa.free(decs); + // serial decode again per prompt (its logits per row), then the windows + for (0..prompts) |k| { + const p = all[k * 300 ..][0 .. 20 + 7 * k]; + try e.prefill(&seqs[k], p); + try f.head(&seqs[k]); + var pick: [1]u32 = undefined; + try f.picks(1, &pick); + toks_all[k] = try gpa.alloc(u32, steps); + toks_all[k][0] = pick[0]; + try e.ops().download(std.mem.sliceAsBytes(decs[(k * steps) * V ..][0..V]), e.scratch.logits); + try e.s.synchronize(); + for (1..steps) |j| { + const part = [_]qwen.Part{.{ .seq = &seqs[k], .tokens = toks_all[k][j - 1 .. j] }}; + try f.round(&part); + try f.picks(1, &pick); + try e.ops().download(std.mem.sliceAsBytes(decs[(k * steps + j) * V ..][0..V]), e.scratch.logits); + try e.s.synchronize(); + try f.commit(&part, &.{&.{0}}); + toks_all[k][j] = pick[0]; + } + try e.prefill(&seqs[k], p); + } + defer for (toks_all) |x| gpa.free(x); + const win = 16; + var at: usize = 0; // window start: tokens at..at+win feed rows predicting at+1.. + const got = try gpa.alloc(u16, prompts * win * V); + defer gpa.free(got); + while (at + 1 < steps) : (at += win) { + const w = @min(win, steps - 1 - at); + var parts: [prompts]qwen.Part = undefined; + var paths: [prompts][]const u32 = undefined; + const path = [_]u32{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; + const groups: usize = if (multi) 1 else prompts; + for (0..groups) |gi| { + const members: usize = if (multi) prompts else 1; + for (0..members) |mi| { + const k = if (multi) mi else gi; + parts[mi] = .{ .seq = &seqs[k], .tokens = toks_all[k][at..][0..w] }; + paths[mi] = path[0..w]; + } + try f.round(parts[0..members]); + try e.ops().download(std.mem.sliceAsBytes(got[0 .. members * w * V]), e.scratch.logits); + try e.s.synchronize(); + try f.commit(parts[0..members], paths[0..members]); + for (0..members) |mi| { + const k = if (multi) mi else gi; + for (0..w) |r| { + const row = got[(mi * w + r) * V ..][0..V]; + const want = decs[(k * steps + at + 1 + r) * V ..][0..V]; + bit_rows += @intFromBool(std.mem.eql(u16, row, want)); + var best: usize = 0; + for (row, 0..) |x, i| if (bf(x) > bf(row[best])) { + best = i; + }; + pick_rows += @intFromBool(best == toks_all[k][at + 1 + r]); + rows_n += 1; + } + } + } + } + std.debug.print("{s} decode rounds teacher-forced ({s}, 16-row windows): {d}/{d} rows' logits bit-equal to serial decode, {d}/{d} picks\n", .{ if (bit_rows == rows_n) "PASS" else "FAIL", if (multi) "every prompt's stream in one round" else "one stream a round", bit_rows, rows_n, pick_rows, rows_n }); + if (bit_rows != rows_n) failures.* += 1; + } + // prompts prefilled side by side (Forward.chunks, as the greedy scoring and serving's prefill_batch run them). + { + var alone = try e.sequence(4096); + defer alone.deinit(); + var side: [prompts]qwen.state.Seq = undefined; + for (&side) |*q| q.* = try e.sequence(4096); + defer for (&side) |*q| q.deinit(); + var pieces: [prompts]qwen.Forward.Piece = undefined; + for (0..prompts) |k| { + try side[k].reset(e.ops(), e.w.g); + pieces[k] = .{ .ids = all[k * 300 ..][0 .. 20 + 7 * k], .seq = &side[k], .last = true }; + } + var f = e.forward(); + try f.chunks(&pieces); + var equal: usize = 0; + const a1 = try gpa.alloc(u16, V); + defer gpa.free(a1); + const b1 = try gpa.alloc(u16, V); + defer gpa.free(b1); + for (0..prompts) |k| { + try e.prefill(&alone, pieces[k].ids); + for ([_]*qwen.state.Seq{ &alone, &side[k] }, [_][]u16{ a1, b1 }) |q, out| { + const part = [_]qwen.Part{.{ .seq = q, .tokens = &.{ 13, 220 } }}; + try f.round(&part); + try e.ops().download(std.mem.sliceAsBytes(out), e.scratch.logits + V * 2); + try e.s.synchronize(); + try f.commit(&part, &.{&.{ 0, 1 }}); + } + var ha: [D]u16 = undefined; + var hb: [D]u16 = undefined; + try e.ops().download(std.mem.sliceAsBytes(&ha), alone.head_in); + try e.ops().download(std.mem.sliceAsBytes(&hb), side[k].head_in); + try e.s.synchronize(); + equal += @intFromBool(std.mem.eql(u16, &ha, &hb) and std.mem.eql(u16, a1, b1)); + } + std.debug.print("{s} prompts prefilled side by side: {d}/{d} with the head's input and a round's logits after them bit-equal to alone\n", .{ if (equal == prompts) "PASS" else "FAIL", equal, prompts }); + if (equal != prompts) failures.* += 1; + } + // the trainer's greedy scoring against serial decode: each decoded reply unchanged, then one token changed + { + var replies: [prompts][]u32 = undefined; + var ids: [2 * prompts][]u32 = undefined; + var sq: [2 * prompts]train.Seq = undefined; + for (0..prompts) |k| { + const p = all[k * 300 ..][0 .. 20 + 7 * k]; + var out: std.ArrayList(u32) = .empty; + try e.generate(&seq, p, 40, &out); + replies[k] = try out.toOwnedSlice(gpa); + ids[k] = try std.mem.concat(gpa, u32, &.{ p, replies[k] }); + ids[prompts + k] = try gpa.dupe(u32, ids[k]); + const at = p.len + (k * 7) % replies[k].len; // a token changed: the reply is no longer greedy from there + ids[prompts + k][at] = (ids[prompts + k][at] + 1) % 1000; + sq[k] = .{ .ids = ids[k], .start = p.len, .decide = p.len - 1 }; + sq[prompts + k] = .{ .ids = ids[prompts + k], .start = p.len, .decide = p.len - 1 }; + } + defer for (replies) |r| gpa.free(r); + defer for (ids) |x| gpa.free(x); + var same: [2 * prompts]bool = undefined; + const g0 = now(io); + try t.greedy(sq[0..prompts], same[0..prompts]); + try t.greedy(sq[prompts..], same[prompts..]); + const g1 = now(io); + var right: usize = 0; + for (same, 0..) |x, i| right += @intFromBool(x == (i < prompts)); + std.debug.print("{s} the trainer's greedy scoring: {d}/{d} verdicts right (decoded replies unchanged, then one token changed), {d:.0} ms\n", .{ if (right == same.len) "PASS" else "FAIL", right, same.len, (g1 - g0) * 1e3 }); + if (right != same.len) failures.* += 1; + } + // a note, not a check: a prompt pass over the reply is not decoding's arithmetic (why the scoring runs rounds) + std.debug.print("NOTE greedy decode vs one prompt pass over the reply: {d}/{d} picks equal, {d}/{d} rows' logits bit-equal (most apart {d:.4}), {d:.1} s\n", .{ picks_equal, rows_all, rows_equal, rows_all, most, now(io) - a0 }); +} + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len < 4) { + std.debug.print("usage: tf-qwen27-learn MODEL KERNELS IDS_JSON\n", .{}); + return 2; + } + const all = try readIds(gpa, io, args[3]); + defer gpa.free(all); + const n = @min(all.len, 256); + if (n < 24) return 2; + const seq_ids = all[0..n]; + var driver = try cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + const l0 = now(io); + const e = try qwen.Engine.init(gpa, io, &ctx, args[1], args[2], .{ .context = 4096 }); + defer e.deinit(); + const l1 = now(io); + if (std.c.getenv("Q27_GATE")) |list| return gates(gpa, io, e, std.mem.span(list)); + if (std.c.getenv("Q27_SCORE")) |list| return scores(gpa, io, e, std.mem.span(list)); + const t = try Trainer.init(gpa, io, e); + defer t.deinit(); + const l2 = now(io); + std.debug.print("engine loaded in {d:.1} s, trainer in {d:.1} s\n", .{ l1 - l0, l2 - l1 }); + var failures: usize = 0; + // (0) a prompt in a conversation read through the engine's pass (tap.zig) against the trainer's pass. + if (std.c.getenv("Q27_TAP") != null) { + const sq: train.Seq = .{ .ids = seq_ids, .start = n - 4, .decide = n - 5 }; + var keys: [1]train.Result = undefined; + try t.pass(&.{sq}, .keys, turn, &keys); + const tl = [_]usize{ 0, 13, 40, 62 }; + const rows_n = n - 1; + const want = try gpa.alloc(u32, rows_n); + defer gpa.free(want); + for (want, 0..) |*w, i| w.* = @intCast(i); + const got = try gpa.alloc(u16, rows_n * tl.len * D); + defer gpa.free(got); + for ([_]usize{ 0, n / 2, n / 2 }, 0..) |context, round| { + const from: usize = if (round == 2) context else 0; // the third read finds the conversation kept + const a = now(io); + try t.tapRows(seq_ids[0..rows_n], context, want[from..], &tl, got[0 .. (rows_n - from) * tl.len * D]); + const b = now(io); + var differ: usize = 0; + for (want[from..], 0..) |r, i| for (tl, 0..) |l, j| { + for (t.normed(l, r), got[(i * tl.len + j) * D ..][0..D]) |p, q| differ += @intFromBool(p != q); + }; + const ok = differ == 0; + std.debug.print("{s} taps after a {d}-row conversation ({d} rows from {d}, {d:.0} ms): {d} values differ from the pass's\n", .{ if (ok) "PASS" else "FAIL", context, rows_n - from, from, (b - a) * 1e3, differ }); + if (!ok) failures += 1; + } + std.debug.print("taps: {d} conversations run, {d} found kept\n", .{ t.tap.?.runs, t.tap.?.reused }); + } + // Q27_GREEDY: greedy decode (serial rounds) against one batched prompt pass over the prompt and the decoded. + if (std.c.getenv("Q27_GREEDY") != null) try greedyVsPass(gpa, io, e, t, all, &failures); + // Q27_TIME: only the full pass's time (4) + const timing = std.c.getenv("Q27_TIME") != null; + const answer: usize = if (std.c.getenv("Q27_ANSWER")) |v| std.fmt.parseInt(usize, std.mem.span(v), 10) catch 8 else 8; + const start = n - @min(answer, n / 2); + + // (1) packed sequences: each one's loss as alone + if (!timing) { + var seqs: [6]train.Seq = undefined; + var alone: [6]f32 = undefined; + for (&seqs, 0..) |*s, i| { + const len = @min(n, 120) - 3 * i; + s.* = .{ .ids = seq_ids[0..len], .start = len - 6, .decide = len - 7 }; + var one: [1]train.Result = undefined; + try t.pass(seqs[i .. i + 1], .loss, turn, &one); + alone[i] = one[0].loss; + } + var got: [6]train.Result = undefined; + const p0 = now(io); + try t.pass(&seqs, .loss, turn, &got); + const p1 = now(io); + var worst: f32 = 0; + for (got, alone) |g, a| worst = @max(worst, @abs(g.loss - a)); + const ok = worst <= 1e-4; + std.debug.print("{s} six sequences side by side ({d} rows in {d:.0} ms): each loss as alone within {e} (alone: {d:.4} {d:.4} {d:.4} ...)\n", .{ if (ok) "PASS" else "FAIL", t.rows, (p1 - p0) * 1e3, worst, alone[0], alone[1], alone[2] }); + if (!ok) failures += 1; + } + + if (!timing) { + // (2) push against finite differences at four layers: two rows of the sequence, keys 0 and 1 + var layers = [_]usize{ 13, 26, 39, 52 }; + if (std.c.getenv("Q27_LAYERS")) |v| { + var it = std.mem.tokenizeScalar(u8, std.mem.span(v), ','); + for (&layers) |*l| l.* = std.fmt.parseInt(usize, it.next() orelse break, 10) catch l.*; + } + const rows = [_]usize{ start - 1, start - 5 }; + var sq: train.Seq = .{ .ids = seq_ids, .start = start, .decide = start - 1 }; + var mask: u64 = 0; + for (layers) |l| mask |= @as(u64, 1) << @intCast(l); + sq.nudge = .{ .layers = .{ mask, mask, 0 }, .rows = .{ rows[0], rows[1], 0 } }; + for (layers) |l| for (0..2) |k| @memset(t.deltaAt(0, k, l), 0); + var out: [1]train.Result = undefined; + const q0 = now(io); + try t.pass(&.{sq}, .target, turn, &out); + const q1 = now(io); + std.debug.print("target pass: {d} rows, loss {d:.5}, back to layer {d} in {d:.0} ms\n", .{ n - 1, out[0].loss, layers[0], (q1 - q0) * 1e3 }); + if (std.c.getenv("Q27_DEBUG") != null) for (layers) |l| for (0..2) |k| { + const p = t.pushAt(0, k, l); + var nan: usize = 0; + for (p) |v| if (std.math.isNan(v)) { + nan += 1; + }; + std.debug.print(" debug layer {d} key {d} row {d}: |push| {e:.4}, {d} NaN\n", .{ l, k, rows[k], @sqrt(dot(p, p)), nan }); + }; + const push = try gpa.alloc(f32, layers.len * 2 * D); + defer gpa.free(push); + const resid_n = try gpa.alloc(f64, layers.len * 2); + defer gpa.free(resid_n); + for (layers, 0..) |l, li| for (0..2) |k| { + @memcpy(push[(li * 2 + k) * D ..][0..D], t.pushAt(0, k, l)); + resid_n[li * 2 + k] = norm16(t.residual(l + 1, rows[k])); + }; + var prng = std.Random.DefaultPrng.init(7); + const step_frac: f64 = if (std.c.getenv("Q27_STEP")) |v| std.fmt.parseFloat(f64, std.mem.span(v)) catch 0.004 else 0.004; + var worst_rel: f64 = 0; + var lines: usize = 0; + const dir = try gpa.alloc(f32, D); + defer gpa.free(dir); + const rnd = try gpa.alloc(f32, D); + defer gpa.free(rnd); + for (layers, 0..) |l, li| for (0..2) |k| { + const p = push[(li * 2 + k) * D ..][0..D]; + const pn = @sqrt(dot(p, p)); + const rn = resid_n[li * 2 + k]; + for (0..2) |which| { + var s: f64 = 0; + for (rnd) |*x| { + x.* = prng.random().floatNorm(f32); + s += @as(f64, x.*) * x.*; + } + for (dir, p, rnd) |*x, v, q| x.* = @floatCast(if (which == 0) v / pn else (v / pn + q / @sqrt(s)) / std.math.sqrt2); + const want = dot(p, dir); + // the step moves the loss by about `dl` nats at its first point: small enough to stay linear + const h = if (std.c.getenv("Q27_DL")) |v| (std.fmt.parseFloat(f64, std.mem.span(v)) catch 0.02) / @max(@abs(want), 1e-12) else step_frac * @max(rn, 1.0); + const fd = try slope(t, &sq, k, l, dir, h); + const rel = @abs(fd - want) / @max(@abs(want), 1e-30); + worst_rel = @max(worst_rel, rel); + std.debug.print(" layer {d} row {d} ({s}, |residual| {d:.1}, step {d:.3}): push . u {e:.4}, finite differences' slope {e:.4}, relative error {d:.4}\n", .{ l, rows[k], if (which == 0) "along push" else "half random", rn, h, want, fd, rel }); + lines += 1; + } + }; + const grad_ok = worst_rel < 0.1; + std.debug.print("{s} push against finite differences: worst relative error {d:.4} ({d} checks)\n", .{ if (grad_ok) "PASS" else "FAIL", worst_rel, lines }); + if (!grad_ok) failures += 1; + + // (3) a pocket neuron at layer 39: its output's gradient (act push) against the loss moving with it + { + const l: usize = 39; + const r = rows[0]; + var keys: [1]train.Result = undefined; + sq.nudge = .{}; + try t.pass(&.{sq}, .keys, turn, &keys); + // input weights that read 2 on this row and little elsewhere: the row less the sequence's mean row, scaled + const z = try gpa.alloc(f64, D); + defer gpa.free(z); + @memset(z, 0); + const rows_n = sq.ids.len - 1; + for (0..rows_n) |j| { + if (j == r) continue; + for (t.normed(l, j), 0..) |b, i| z[i] -= bf(b) / @as(f64, @floatFromInt(rows_n - 1)); + } + var zx: f64 = 0; + for (t.normed(l, r), 0..) |b, i| { + z[i] += bf(b); + zx += z[i] * bf(b); + } + const u = try gpa.alloc(f32, D); + defer gpa.free(u); + for (u, z) |*o, v| o.* = @floatCast(2 * v / zx); + var most: f64 = -1e30; + for (0..rows_n) |j| { + if (j == r) continue; + var d: f64 = 0; + for (t.normed(l, j), u) |b, w| d += bf(b) * w; + most = @max(most, d); + } + std.debug.print(" pocket neuron: u x = 2 on row {d}, at most {d:.3} on the sequence's other rows\n", .{ r, most }); + const neurons = 64; + const rows3 = try gpa.alloc(f32, 3 * neurons * D); + defer gpa.free(rows3); + @memset(rows3, 0); + const gate = rows3[0 .. neurons * D]; + const upr = rows3[neurons * D ..][0 .. neurons * D]; + const down = rows3[2 * neurons * D ..][0 .. neurons * D]; + for (0..D) |i| { + gate[i] = 16 * u[i]; + upr[i] = u[i] / 16; + } + try e.pockets.set(e.s, l, gate, upr, down, 1); + sq.nudge = .{ .layers = .{ @as(u64, 1) << @intCast(l), 0, 0 }, .rows = .{ r, 0, 0 } }; + @memset(t.deltaAt(0, 0, l), 0); + var got: [1]train.Result = undefined; + try t.pass(&.{sq}, .target, turn, &got); + var zg: f64 = 0; + var zu: f64 = 0; + for (t.normed(l, r), 0..) |b, i| { + zg += gate[i] * bf(b); + zu += upr[i] * bf(b); + } + const act = zg / (1 + @exp(-zg)) * zu; + const pg = try gpa.dupe(f32, t.pushAt(0, 0, l)); + defer gpa.free(pg); + const pn = @sqrt(dot(pg, pg)); + const rn = norm16(t.residual(l + 1, r)); + const step = step_frac * rn / @max(act, 1e-6); + sq.nudge = .{}; + var num: f64 = 0; + var den: f64 = 0; + for (1..7) |m| for ([_]f64{ 1, -1 }) |sgn| { + const xs = sgn * @as(f64, @floatFromInt(m)) * step; + for (down[0..D], pg) |*o, v| o.* = @floatCast(xs * v / pn); + try e.pockets.set(e.s, l, gate, upr, down, 1); + var rr: [1]train.Result = undefined; + try t.pass(&.{sq}, .loss, turn, &rr); + num += xs * rr[0].loss; + den += xs * xs; + }; + const fd = num / den; + const want = act * pn; + const rel = @abs(fd - want) / @max(@abs(want), 1e-30); + const ok = rel < 0.1; + std.debug.print("{s} a pocket neuron at layer {d} (activation {d:.3}): act |push| {e:.4}, finite difference of its output {e:.4}, relative error {d:.4}\n", .{ if (ok) "PASS" else "FAIL", l, act, want, fd, rel }); + if (!ok) failures += 1; + @memset(rows3, 0); + try e.pockets.set(e.s, l, gate, upr, down, 0); + } + } + + // (4) a full pass's time: sixteen sequences, keys then loss then target down to layer 13 + { + // Q27_LESSON: a lesson's values pass instead: 8 answers of 78 rows, 22 of them the reply. + const lesson = std.c.getenv("Q27_LESSON") != null; + const count: usize = if (lesson) 8 else 16; + var seqs: [16]train.Seq = undefined; + var rowsum: usize = 0; + var mask: u64 = @as(u64, 1) << 13 | @as(u64, 1) << 40; + if (lesson) { + mask = 0; + for ([_]usize{ 19, 20, 21, 23, 24, 25, 26, 27, 28, 36 }) |l| mask |= @as(u64, 1) << @intCast(l); + } + for (seqs[0..count], 0..) |*s, i| { + const len = if (lesson) @min(n, 79) else @min(n, 40 + 3 * i); + const reply: usize = if (lesson) 22 else 6; + rowsum += len - 1; + s.* = .{ .ids = seq_ids[i * 3 ..][0..len], .start = len - reply, .decide = len - reply - 1, .nudge = .{ .layers = .{ mask, 0, 0 }, .rows = .{ len - reply - 1, 0, 0 } } }; + if (!lesson) s.ids = seq_ids[0..len]; + for (0..e.w.g.layers) |l| @memset(t.deltaAt(i, 0, l), 0); + } + var got: [16]train.Result = undefined; + for ([_]train.Mode{ .keys, .loss, .target, .target, .target }) |m| { + const a = now(io); + try t.pass(seqs[0..count], m, turn, got[0..count]); + const b = now(io); + var h = std.hash.Wyhash.init(0); + for (got[0..count]) |r| h.update(std.mem.asBytes(&r.loss)); + if (m == .target) for (0..count) |si| for (0..3) |k| for (0..e.w.g.layers) |l| h.update(std.mem.sliceAsBytes(t.pushAt(si, k, l))); + std.debug.print("pass {s}: {d} sequences, {d} rows, {d:.0} ms (losses and pushes {x:0>16})\n", .{ @tagName(m), count, rowsum, (b - a) * 1e3, h.final() }); + } + } + std.debug.print("{d} failures\n", .{failures}); + return if (failures == 0) 0 else 1; +} diff --git a/zig/src/cli/qwen27_taps.zig b/zig/src/cli/qwen27_taps.zig new file mode 100644 index 0000000000..e258f973e4 --- /dev/null +++ b/zig/src/cli/qwen27_taps.zig @@ -0,0 +1,146 @@ +//! tf-qwen27-learn's reads of a taught folder: the pocket's gate taps (Q27_GATE) and replies scored by serial decode. +const qwen27_learn_mod = @import("qwen27_learn.zig"); +const std = @import("std"); +const qwen = @import("qwen27"); +const D = 5120; +const bf = qwen27_learn_mod.bf; + +/// Q27_GATE=LIST (flashnext-gate's list and output): for each line "tagrowsids" the prompt runs through the. +pub fn gates(gpa: std.mem.Allocator, io: std.Io, e: *qwen.Engine, path: []const u8) !u8 { + const L = e.w.g.layers; + const text = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(64 << 20)); + defer gpa.free(text); + var gate_rows = try gpa.alloc([]f32, L); + defer gpa.free(gate_rows); + // Q27_GATE_ACT: also each neuron's up row times x, its activation silu(g x) (w x). + const acts = std.c.getenv("Q27_GATE_ACT") != null; + var up_rows = try gpa.alloc([]f32, L); + defer gpa.free(up_rows); + var down_norm = try gpa.alloc([]f64, L); + defer gpa.free(down_norm); + var used = try gpa.alloc(usize, L); + defer gpa.free(used); + var layers: std.ArrayList(usize) = .empty; + defer layers.deinit(gpa); + var total: usize = 0; + for (0..L) |l| { + const cap = if (e.pockets.layers[l]) |r| r.cap else 0; + gate_rows[l] = try gpa.alloc(f32, cap * D); + up_rows[l] = try gpa.alloc(f32, cap * D); + down_norm[l] = try gpa.alloc(f64, cap); + used[l] = 0; + if (cap == 0) continue; + const dn = try gpa.alloc(f32, cap * D); + defer gpa.free(dn); + used[l] = e.pockets.read(e.s, l, gate_rows[l], up_rows[l], dn); + for (0..cap) |i| { + var sq: f64 = 0; + for (dn[i * D ..][0..D]) |v| sq += @as(f64, v) * v; + down_norm[l][i] = @sqrt(sq); + } + total += used[l]; + if (used[l] > 0) try layers.append(gpa, l); + } + defer for (gate_rows, up_rows, down_norm) |g, u, dn| { + gpa.free(g); + gpa.free(u); + gpa.free(dn); + }; + std.debug.print("pocket: {d} neurons in use at {d} layers\n", .{ total, layers.items.len }); + var tp: ?qwen.tap.Tap = null; + defer if (tp) |*x| x.deinit(gpa); + var lines = std.mem.tokenizeScalar(u8, text, '\n'); + var out = std.Io.File.stdout().writer(io, &.{}); + while (lines.next()) |line| { + var cols = std.mem.splitScalar(u8, line, '\t'); + const tag = cols.next() orelse continue; + var rows: std.ArrayList(u32) = .empty; + defer rows.deinit(gpa); + var rt = std.mem.tokenizeAny(u8, cols.next() orelse continue, ", "); + while (rt.next()) |part| try rows.append(gpa, try std.fmt.parseInt(u32, part, 10)); + var ids: std.ArrayList(u32) = .empty; + defer ids.deinit(gpa); + var it = std.mem.tokenizeAny(u8, cols.next() orelse continue, ", "); + while (it.next()) |part| try ids.append(gpa, try std.fmt.parseInt(u32, part, 10)); + const n = ids.items.len; + if (tp) |*x| if (x.seq.capacity < n + 1) { + x.deinit(gpa); + tp = null; + }; + if (tp == null) tp = try qwen.tap.Tap.init(gpa, e, @max(4096, std.mem.alignForward(usize, n + 1, 1024))); + const got = try gpa.alloc(u16, rows.items.len * layers.items.len * D); + defer gpa.free(got); + try tp.?.read(ids.items, 0, rows.items, layers.items, got); + for (rows.items, 0..) |r, ri| for (layers.items, 0..) |l, j| { + const x = got[(ri * layers.items.len + j) * D ..][0..D]; + for (0..used[l]) |i| { + var ux: f64 = 0; + for (gate_rows[l][i * D ..][0..D], x) |g, b| ux += @as(f64, g) * bf(b); + if (!acts) { + try out.interface.print("{s} {d} {d} {d} {d:.4}\n", .{ tag, r, l, i, ux }); + continue; + } + var wx: f64 = 0; + for (up_rows[l][i * D ..][0..D], x) |w, b| wx += @as(f64, w) * bf(b); + const act = ux / (1 + @exp(-ux)) * wx; + try out.interface.print("{s} {d} {d} {d} {d:.4} {d:.5} {e:.4} {e:.4}\n", .{ tag, r, l, i, ux, wx, act, @abs(act) * down_norm[l][i] }); + } + }; + } + return 0; +} + +/// Q27_SCORE=LIST: for each line "tagprompt_lenids" the prompt is prefilled and the rest teacher-forced. +pub fn scores(gpa: std.mem.Allocator, io: std.Io, e: *qwen.Engine, path: []const u8) !u8 { + const V = qwen.config.vocab; + const text = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(64 << 20)); + defer gpa.free(text); + const row = try gpa.alloc(u16, V); + defer gpa.free(row); + var out = std.Io.File.stdout().writer(io, &.{}); + var lines = std.mem.tokenizeScalar(u8, text, '\n'); + while (lines.next()) |line| { + var cols = std.mem.splitScalar(u8, line, '\t'); + const tag = cols.next() orelse continue; + const plen = try std.fmt.parseInt(usize, std.mem.trim(u8, cols.next() orelse continue, " "), 10); + var ids: std.ArrayList(u32) = .empty; + defer ids.deinit(gpa); + var it = std.mem.tokenizeAny(u8, cols.next() orelse continue, ", "); + while (it.next()) |part| try ids.append(gpa, try std.fmt.parseInt(u32, part, 10)); + if (plen == 0 or plen >= ids.items.len) continue; + var seq = try e.sequence(@max(4096, std.mem.alignForward(usize, ids.items.len + 16, 1024))); + defer seq.deinit(); + try e.prefill(&seq, ids.items[0..plen]); + var f = e.forward(); + try f.head(&seq); + var pick: [1]u32 = undefined; + try f.picks(1, &pick); + var j: usize = 0; + while (plen + j < ids.items.len) : (j += 1) { + try e.ops().download(std.mem.sliceAsBytes(row), e.scratch.logits); + try e.s.synchronize(); + const want = ids.items[plen + j]; + var most: f64 = -std.math.inf(f64); + var top: usize = 0; + for (row, 0..) |x, k| if (bf(x) > most) { + most = bf(x); + top = k; + }; + var sum: f64 = 0; + var above: usize = 0; + const mine = bf(row[want]); + for (row) |x| { + sum += @exp(bf(x) - most); + above += @intFromBool(bf(x) > mine); + } + const lse = most + @log(sum); + try out.interface.print("{s} {d} {d} {d:.4} {d} {d} {d:.4}\n", .{ tag, j, want, mine - lse, above + 1, top, most - lse }); + if (plen + j + 1 >= ids.items.len) break; + const part = [_]qwen.Part{.{ .seq = &seq, .tokens = &.{want} }}; + try f.round(&part); + try f.picks(1, &pick); + try f.commit(&part, &.{&.{0}}); + } + } + return 0; +} diff --git a/zig/src/cuda/kernels.zig b/zig/src/cuda/kernels.zig index 5756f7b8a2..ed981ba9a9 100644 --- a/zig/src/cuda/kernels.zig +++ b/zig/src/cuda/kernels.zig @@ -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 attn_train: []const u8 = if (available) &Blob("fatbin_attn_train").bytes else &.{}; pub const gdn_train: []const u8 = if (available) &Blob("fatbin_gdn_train").bytes else &.{}; +pub const qwen27_train: []const u8 = if (available) &Blob("fatbin_qwen27_train").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 &.{}; diff --git a/zig/src/families/qwen27/cuda.zig b/zig/src/families/qwen27/cuda.zig index 3e10f18896..bc11795ab6 100644 --- a/zig/src/families/qwen27/cuda.zig +++ b/zig/src/families/qwen27/cuda.zig @@ -17,6 +17,11 @@ pub const drafts = @import("cuda/drafts.zig"); pub const vision = @import("cuda/vision.zig"); pub const image = @import("cuda/image.zig"); pub const reuse = @import("cuda/reuse.zig"); +pub const train_ops = @import("cuda/train_ops.zig"); +pub const train = @import("cuda/train.zig"); +pub const tap = @import("cuda/tap.zig"); +pub const pocket = @import("cuda/pocket.zig"); +pub const slide = @import("cuda/slide.zig"); test { _ = config; @@ -36,4 +41,8 @@ test { _ = vision; _ = image; _ = reuse; + _ = train_ops; + _ = pocket; + _ = slide; + _ = @import("cuda/hooks.zig"); } diff --git a/zig/src/families/qwen27/cuda/engine.zig b/zig/src/families/qwen27/cuda/engine.zig index 91b8103d2c..308e1a539d 100644 --- a/zig/src/families/qwen27/cuda/engine.zig +++ b/zig/src/families/qwen27/cuda/engine.zig @@ -10,6 +10,8 @@ const vision = @import("vision.zig"); const wts = @import("weights.zig"); const Forward = @import("forward.zig").Forward; const Part = @import("forward.zig").Part; +const pocket = @import("pocket.zig"); +const hooks = @import("hooks.zig"); /// prefill.CHUNK: a prompt chunk's rows (prompt_rows on a GPU of 80 GB or more). pub const prompt_rows = 4096; @@ -70,6 +72,8 @@ pub const Engine = struct { context: usize, kv8: bool, // --kv-cache fp8: every stream's attention caches e4m3 with a scale a row grid: bool = false, // a prompt cache: prompts in zero-anchored chunks (Chunks), not even splits + pockets: pocket.Pockets, // Living Weights' neurons beside each layer's MLP (none until a folder or a lesson has them) + dir: []const u8 = "", // the checkpoint folder (the trainer reads its MLX copies there) pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: []const u8, o: Options) !*Engine { const cfg = try c.Config.read(gpa, io, dir); @@ -86,6 +90,29 @@ pub const Engine = struct { errdefer e.k.deinit(); e.w = try wts.load(gpa, io, e.ops(), dir, cfg); errdefer e.w.deinit(); + e.dir = try gpa.dupe(u8, dir); + errdefer gpa.free(e.dir); + e.pockets = try pocket.Pockets.init(gpa, ctx.d, g.hidden, g.layers); + errdefer e.pockets.deinit(); + if (std.c.getenv("TF_Q27_POCKET_DECOUPLE") != null and e.w.pocket.len > 0) { + const norms = try gpa.alloc([]f32, g.layers); + defer gpa.free(norms); + const raw = try gpa.alloc(u16, g.hidden); + defer gpa.free(raw); + for (norms, 0..) |*n, l| { + n.* = try gpa.alloc(f32, g.hidden); + try ctx.d.check(ctx.d.api.cuMemcpyDtoH_v2(raw.ptr, e.w.layers[l].post_norm, g.hidden * 2), "cuMemcpyDtoH"); + for (n.*, raw) |*dst, b| dst.* = @bitCast(@as(u32, b) << 16); + } + defer for (norms) |n| gpa.free(n); + var mean: f64 = 0; + for (norms[20]) |v| mean += v; + const share = try pocket.decouple(gpa, g.hidden, e.w.pocket, norms); + std.log.info("qwen27: pocket diagnostic: outputs decoupled from later neurons' reads ({d:.1}% of their squared size removed; layer 20's post norm mean {d:.3})", .{ 100 * share, mean / @as(f64, @floatFromInt(g.hidden)) }); + } + const learned = try e.pockets.loadAll(e.s, e.w.pocket); + e.w.dropPocket(); + if (learned > 0) std.log.info("qwen27: the folder's Living Weights pocket: {d} learned neurons beside the MLPs", .{learned}); e.scratch = try st.Scratch.init(gpa, ctx.d, g, prompt_rows, o.context); errdefer e.scratch.deinit(); try e.s.synchronize(); @@ -93,6 +120,8 @@ pub const Engine = struct { } pub fn deinit(e: *Engine) void { + e.pockets.deinit(); + e.gpa.free(e.dir); e.scratch.deinit(); e.w.deinit(); e.k.deinit(); @@ -105,7 +134,14 @@ pub const Engine = struct { } pub fn forward(e: *Engine) Forward { - return .{ .gpa = e.gpa, .w = &e.w, .ops = e.ops(), .t = .{ .set = &e.k.triton, .s = e.s }, .s = &e.scratch }; + const mlp: ?hooks.MlpAdd = if (e.pockets.any()) .{ .ctx = e, .f = servePocket } else null; + return .{ .gpa = e.gpa, .w = &e.w, .ops = e.ops(), .t = .{ .set = &e.k.triton, .s = e.s }, .s = &e.scratch, .mlp = mlp, .taught_rows = e.pockets.rowsBuffer() }; + } + + /// The serving forward's MLP hook: each layer's pocket added to its MLP's output. + fn servePocket(ctx: *anyopaque, layer: usize, y: u64, out: u64, rows: usize, taught: u64) anyerror!void { + const e: *Engine = @ptrCast(@alignCast(ctx)); + try e.pockets.add(e.s, layer, y, out, rows, taught); } /// A stream's state for `capacity` positions (its caches, recurrences and conv windows), empty. diff --git a/zig/src/families/qwen27/cuda/forward.zig b/zig/src/families/qwen27/cuda/forward.zig index e188647925..de4c35ac29 100644 --- a/zig/src/families/qwen27/cuda/forward.zig +++ b/zig/src/families/qwen27/cuda/forward.zig @@ -8,6 +8,7 @@ const st = @import("state.zig"); const wts = @import("weights.zig"); const rnd = @import("round.zig"); const vision = @import("vision.zig"); +const hooks = @import("hooks.zig"); const bf = 2; pub const Part = rnd.Part; @@ -22,6 +23,10 @@ pub const Forward = struct { s: *st.Scratch, dump: ?Dump = null, // a debugging copy of every norm's (h, y) rows, as capture.py's hook writes them taps: ?u64 = null, // rows of the drafter's five layer taps (5 x hidden bf16), written by round and chunk + mlp: ?hooks.MlpAdd = null, // after each layer's MLP: a taught folder's pocket, or a training pass's (hooks.zig) + taught_rows: u64 = 0, // f32 [prompt_rows] device room for a call's row scales when an untaught stream rides it + keep: ?*const hooks.Keep = null, // a training pass's keeps and every row's logits (chunks only) + top: ?usize = null, // chunks: stop after this layer's MLP input is kept (a read that needs none above it; no logits) pub const Dump = struct { io: std.Io, dir: []const u8, n: usize = 0, rows: usize = 0 }; @@ -46,6 +51,24 @@ pub const Forward = struct { return .{ .d = f.ops.k.d, .s = f.ops.s, .discrete = f.ops.k.discrete }; } + /// A call's row scales for the MLP hook: 1 on a taught stream's rows, 0 on an untaught one's. + fn taught(f: *Forward, lens: []const usize, untaught: []const bool) !u64 { + if (f.mlp == null or f.taught_rows == 0) return 0; + if (std.mem.indexOfScalar(bool, untaught, true) == null) return 0; + var total: usize = 0; + for (lens) |n| total += n; + const host = try f.gpa.alloc(f32, total); + defer f.gpa.free(host); + var at: usize = 0; + for (lens, untaught) |n, u| { + @memset(host[at..][0..n], if (u) 0 else 1); + at += n; + } + try f.ops.upload(f.taught_rows, std.mem.sliceAsBytes(host)); + try f.ops.s.synchronize(); // the host copy must outlive the async upload + return f.taught_rows; + } + fn upload32(f: *Forward, dst: u64, values: []const i32) !void { try f.ops.upload(dst, std.mem.sliceAsBytes(values)); try f.ops.s.synchronize(); // the host copy must outlive the async upload @@ -92,6 +115,13 @@ pub const Forward = struct { const w = f.w; const r = try rnd.stage(f.gpa, f.ops, f.t, s, g_, parts); const W = r.rows; + var lens: [st.max_streams]usize = undefined; + var flags: [st.max_streams]bool = undefined; + for (parts, 0..) |p, k| { + lens[k] = p.tokens.len; + flags[k] = p.seq.untaught; + } + const taught_rows = try f.taught(lens[0..parts.len], flags[0..parts.len]); try f.t.embed(r.ids, w.embed.w, w.embed.s, w.embed.b, s.x, W, g_.hidden); var x = s.x; var pending: ?u64 = null; @@ -133,6 +163,7 @@ pub const Forward = struct { try f.ops.dense(s.y, s.xs, layer.up, s.up, W); try f.t.swiglu(s.gate, s.up, s.act, s.act_xs, W, g_.intermediate); try f.ops.dense(s.act, s.act_xs, layer.down, s.pending, W); + if (f.mlp) |m| try m.f(m.ctx, i, s.y, s.pending, W, taught_rows); pending = s.pending; try f.tapLayer(i, x, W); } @@ -238,6 +269,7 @@ pub const Forward = struct { if (W < 1 or W > s.rows) return error.ChunkTooLong; if (seq.pos + W > seq.capacity) return error.PromptTooLong; const p0 = seq.pos; + const taught_rows = try f.taught(&.{W}, &.{seq.untaught}); { const host = try f.gpa.alloc(i32, W * (2 + c.conv_taps)); defer f.gpa.free(host); @@ -320,6 +352,7 @@ pub const Forward = struct { try f.ops.prefillDense(s.y, layer.up, s.up, W); try f.t.swiglu(s.gate, s.up, s.act, s.act_xs, W, g_.intermediate); try f.ops.prefillDense(s.act, layer.down, s.pending, W); + if (f.mlp) |m| try m.f(m.ctx, i, s.y, s.pending, W, taught_rows); pending = s.pending; try f.tapLayer(i, x, W); } @@ -350,6 +383,13 @@ pub const Forward = struct { } const W = starts[S]; if (W > s.rows) return error.ChunkTooLong; + var lens: [st.max_streams]usize = undefined; + var flags: [st.max_streams]bool = undefined; + for (pieces, 0..) |p, k| { + lens[k] = p.ids.len; + flags[k] = p.seq.untaught; + } + const taught_rows = try f.taught(lens[0..S], flags[0..S]); const keep = c.conv_taps - 1; const kv = g_.kvInner() * bf; const row = g_.convDim() * bf; @@ -432,12 +472,14 @@ pub const Forward = struct { lin_n = 0; for (w.layers, 0..) |layer, i| { x = try f.norm(x, pending, layer.input_norm, W); + if (f.keep) |k| try k.input(i, x, W); switch (layer.mixer) { .delta => |d| { try f.ops.prefillDense(s.y, d.qkv, s.qkv, W); try f.ops.prefillDense(s.y, d.z, s.z, W); try f.ops.prefillDense(s.y, d.b, s.b, W); try f.ops.prefillDense(s.y, d.a, s.a, W); + if (f.keep) |k| try k.delta(i, s.qkv, s.z, s.b, s.a, W); const cat = s.conv_cat + lin_n * st.max_streams * keep * row; try f.t.gdnPre(s.qkv, cat, d.conv, s.windows, s.sids, s.a, s.b, d.a_log, d.dt_bias, s.gq, s.gk, s.gv, s.gg, s.gbeta, W, f.gdnShape()); for (pieces, 0..) |p, k| { @@ -454,6 +496,7 @@ pub const Forward = struct { try f.ops.prefillDense(s.y, a.q, s.qg, W); try f.ops.prefillDense(s.y, a.k, s.key, W); try f.ops.prefillDense(s.y, a.v, s.prompt_values, W); + if (f.keep) |k| try k.attention(i, s.qg, s.key, s.prompt_values, W); try f.t.attnPrep(s.qg, s.key, a.q_norm, a.k_norm, s.pos, w.inv_freq, s.q_rot, s.prompt_keys, W, f.attnShape(), c.eps); try f.ops.copies(s.copy_items + at_layer[i] * item, at_layer[i + 1] - at_layer[i]); try f.ops.quant(s.quant_items + quant_at[i] * @sizeOf(kern.Quant), quant_at[i + 1] - quant_at[i], quant_rows); @@ -464,18 +507,34 @@ pub const Forward = struct { else try f.ops.prefillAttention(s.q_rot + starts[k] * qrow, p.seq.keys[i], p.seq.values[i], s.attn + starts[k] * qrow, p.seq.pos, p.ids.len, g_.query_heads, g_.kv_heads, scale); try f.t.gateMul(s.attn, s.qg, s.gated, s.gated_xs, W, g_.query_heads, c.head_dim); + if (f.keep) |k| try k.gated(i, s.gated, W); try f.ops.prefillDense(s.gated, a.o, s.r, W); }, } x = try f.norm(x, s.r, layer.post_norm, W); + if (f.keep) |k| try k.post(i, x, s.y, W); + if (f.top) |top| if (i == top) { + // a read of MLP inputs up to here: the layers above and the head are never read. + for (pieces) |p| p.seq.pos += p.ids.len; + try f.ops.s.synchronize(); + return; + }; try f.ops.prefillDense(s.y, layer.gate, s.gate, W); try f.ops.prefillDense(s.y, layer.up, s.up, W); + if (f.keep) |k| try k.mlp(i, s.gate, s.up, W); try f.t.swiglu(s.gate, s.up, s.act, s.act_xs, W, g_.intermediate); try f.ops.prefillDense(s.act, layer.down, s.pending, W); + if (f.mlp) |m| try m.f(m.ctx, i, s.y, s.pending, W, taught_rows); pending = s.pending; try f.tapLayer(i, x, W); } const spare = if (x == s.x) s.h else s.x; + if (f.keep) |k| if (k.logits != 0) { + // every row's head (a training pass's loss reads them all) + try f.t.addRmsnorm(x, pending.?, w.norm, spare, k.last, k.last_xs, W, g_.hidden, c.eps); + try k.final(spare, W); + try f.ops.prefillDense(k.last, w.head, k.logits, W); + }; for (pieces, 0..) |p, k| { p.seq.pos += p.ids.len; if (!p.last) continue; diff --git a/zig/src/families/qwen27/cuda/hooks.zig b/zig/src/families/qwen27/cuda/hooks.zig new file mode 100644 index 0000000000..109a6a1fd0 --- /dev/null +++ b/zig/src/families/qwen27/cuda/hooks.zig @@ -0,0 +1,72 @@ +//! A training pass's hooks in the 27B's batched prompt pass: per-layer keeps, the MLP hook and every row's logits. +const std = @import("std"); +const cuda = @import("cuda"); +const c = @import("shape.zig"); +const to = @import("train_ops.zig"); + +/// After layer `layer`'s MLP: out gains what the hook adds; `taught` (f32 a row, 0: every row) zeroes untaught rows. +pub const MlpAdd = struct { + ctx: *anyopaque, + f: *const fn (ctx: *anyopaque, layer: usize, y: u64, out: u64, rows: usize, taught: u64) anyerror!void, +}; + +/// One layer's kept bf16 rows (0: not kept), named as the backward reads them (train.zig). +pub const LayerKeep = struct { h_in: u64 = 0, proj: u64 = 0, pq: u64 = 0, pk: u64 = 0, pv: u64 = 0, gated: u64 = 0, h_mid: u64 = 0, y: u64 = 0, gate: u64 = 0, up: u64 = 0 }; + +pub const Keep = struct { + t: to.Ops, // the trainer's kernels (column copies) + d: *const cuda.Driver, + g: c.Geometry, + layers: []const LayerKeep, + final_h: u64 = 0, // [rows, hidden] the residual into the final norm + last: u64 = 0, // [rows, hidden] every row normed, then the head's input + last_xs: u64 = 0, // [rows, hidden / 64] fp32 its group sums + logits: u64 = 0, // [rows, vocab] every row's logits (0: none) + + fn copy(k: *const Keep, dst: u64, src: u64, bytes: usize) !void { + if (dst == 0 or bytes == 0) return; + try k.d.check(k.d.api.cuMemcpyDtoDAsync_v2(dst, src, bytes, k.t.s.handle), "cuMemcpyDtoDAsync"); + } + + pub fn input(k: *const Keep, i: usize, h: u64, rows: usize) !void { + try k.copy(k.layers[i].h_in, h, rows * k.g.hidden * 2); + } + + /// The DeltaNet in-projection's four outputs side by side, as gdn_train's P reads them. + pub fn delta(k: *const Keep, i: usize, qkv: u64, z: u64, b: u64, a: u64, rows: usize) !void { + const p = k.layers[i].proj; + if (p == 0) return; + const g = k.g; + const conv = g.convDim(); + const width = conv + g.vInner() + 2 * g.linear_v_heads; + try k.t.cols(qkv, conv, p, width, 0, rows); + try k.t.cols(z, g.vInner(), p, width, conv, rows); + try k.t.cols(b, g.linear_v_heads, p, width, conv + g.vInner(), rows); + try k.t.cols(a, g.linear_v_heads, p, width, conv + g.vInner() + g.linear_v_heads, rows); + } + + pub fn attention(k: *const Keep, i: usize, qg: u64, key: u64, v: u64, rows: usize) !void { + const l = k.layers[i]; + try k.copy(l.pq, qg, rows * 2 * k.g.qInner() * 2); + try k.copy(l.pk, key, rows * k.g.kvInner() * 2); + try k.copy(l.pv, v, rows * k.g.kvInner() * 2); + } + + pub fn gated(k: *const Keep, i: usize, x: u64, rows: usize) !void { + try k.copy(k.layers[i].gated, x, rows * k.g.qInner() * 2); + } + + pub fn post(k: *const Keep, i: usize, h: u64, y: u64, rows: usize) !void { + try k.copy(k.layers[i].h_mid, h, rows * k.g.hidden * 2); + try k.copy(k.layers[i].y, y, rows * k.g.hidden * 2); + } + + pub fn mlp(k: *const Keep, i: usize, gate: u64, up: u64, rows: usize) !void { + try k.copy(k.layers[i].gate, gate, rows * k.g.intermediate * 2); + try k.copy(k.layers[i].up, up, rows * k.g.intermediate * 2); + } + + pub fn final(k: *const Keep, h: u64, rows: usize) !void { + try k.copy(k.final_h, h, rows * k.g.hidden * 2); + } +}; diff --git a/zig/src/families/qwen27/cuda/lanes.zig b/zig/src/families/qwen27/cuda/lanes.zig index acbd27a1c1..d88009e204 100644 --- a/zig/src/families/qwen27/cuda/lanes.zig +++ b/zig/src/families/qwen27/cuda/lanes.zig @@ -219,6 +219,7 @@ pub const Cuda = struct { errdefer x.gpa.destroy(seq); seq.* = x.e.sequence(capacity) catch |err| return if (err == error.OutOfMemory) err else error.OutOfDeviceMemory; errdefer seq.deinit(); + seq.untaught = s.untaught; try x.seqs.put(x.gpa, s, seq); return seq; } diff --git a/zig/src/families/qwen27/cuda/native.zig b/zig/src/families/qwen27/cuda/native.zig index cbe9817214..7b6f55a2ce 100644 --- a/zig/src/families/qwen27/cuda/native.zig +++ b/zig/src/families/qwen27/cuda/native.zig @@ -11,6 +11,9 @@ const dr = @import("draft.zig"); const vision = @import("vision.zig"); const image = @import("image.zig"); const reuse = @import("reuse.zig"); +const living = @import("living"); +const slide_mod = @import("slide.zig"); +const train = @import("train.zig"); pub const model_type = "qwen3_5"; pub const formats: []const []const u8 = &.{"mlx-q4g64"}; @@ -34,7 +37,19 @@ pub fn useCache(p: *anyopaque) void { own.e.grid = true; } -pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, drafter: ?[]const u8 = null, vision: ?Vision = null, kv8: bool = false }; +pub const Options = struct { context: usize, drafts: bool, segments: usize = 1, drafter: ?[]const u8 = null, vision: ?Vision = null, kv8: bool = false, slide: bool = false }; + +/// Living Weights' learner (--slide): lessons put neurons in the pocket beside each layer's dense MLP. +pub const slide = slide_mod; + +/// The first file a lesson would rewrite through a link (config.json, the index, a shard holding an MLP), or null. +pub const linked = slide_mod.linked; + +/// What a learner over the loaded engine `p` learns into; `dir` must outlive it. +pub fn learnModel(p: *anyopaque, dir: []const u8) slide.Model { + const own: *Owned = @ptrCast(@alignCast(p)); + return .{ .e = own.e, .dir = dir, .lay = own.lay }; +} /// --vision's limits: the visual tokens a request's images share, and its images. pub const Vision = struct { image_tokens: u32, max_images: u32 }; @@ -60,7 +75,8 @@ pub const Loaded = struct { stream_bytes: usize, /// Streams that allocate nothing (none here: every stream's state is its own). free_streams: u32 = 0, - /// What a --slide trainer keeps out of the streams' room (none: the 27B does not learn on CUDA yet). + /// --slide: the engine its learner trains, and what its trainer allocates, kept out of the streams' room. + learns: ?*anyopaque = null, learn_bytes: usize = 0, /// What the image tower keeps out of the streams' room (--vision): one call's scratch and a request's rows. vision_bytes: usize = 0, @@ -70,7 +86,7 @@ pub const Loaded = struct { target: *reuse.Target, // what the prompt cache copies (reuse.zig) }; -const Owned = struct { gpa: std.mem.Allocator, e: *engine.Engine, lanes: Lanes, target: reuse.Target = undefined, draft: ?*dr.DFlash2 = null, tower: ?*vision.Tower = null }; +const Owned = struct { gpa: std.mem.Allocator, e: *engine.Engine, lanes: Lanes, target: reuse.Target = undefined, draft: ?*dr.DFlash2 = null, tower: ?*vision.Tower = null, lay: living.Layout = undefined }; /// The drafter the Python engine pairs with the 27B once pulled (z-lab/Qwen3.8-27B-DFlash2). const drafter_repo = "models--z-lab--Qwen3.8-27B-DFlash2"; @@ -108,6 +124,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ own.* = .{ .gpa = gpa, .e = e, .lanes = try Lanes.init(gpa, e, most_streams) }; errdefer own.lanes.deinit(); own.target = .{ .e = e, .seqs = &own.lanes.seqs }; + if (o.slide) own.lay = try slide_mod.layoutOf(gpa, io, dir); if (o.drafts) if (try drafterDir(gpa, io, o.drafter)) |draft_dir| { defer gpa.free(draft_dir); const f = e.forward(); @@ -132,6 +149,8 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ // each stream's caches, its drafter context, and its share of a round's attention partials (`fit`) .stream_bytes = st.Seq.bytes(e.w.g, o.context, o.kv8) + st.Scratch.partialBytes(e.w.g, st.Scratch.streamPartRows(o.context)) + if (own.draft != null) dr.Context.bytes() else 0, .vision_bytes = vision_bytes, + .learns = if (o.slide) own else null, + .learn_bytes = if (o.slide) train.memory(e.w.g) else 0, .ctx = own, .deinit = release, .target = &own.target, diff --git a/zig/src/families/qwen27/cuda/pocket.zig b/zig/src/families/qwen27/cuda/pocket.zig new file mode 100644 index 0000000000..998eb91941 --- /dev/null +++ b/zig/src/families/qwen27/cuda/pocket.zig @@ -0,0 +1,186 @@ +//! Living Weights' pocket beside each dense MLP: fp32 SwiGLU neurons a layer, added to the MLP's output in every pass. +const std = @import("std"); +const cuda = @import("cuda"); +const to = @import("train_ops.zig"); + +/// A layer's neurons on the device: fp32 [cap, hidden] gate rows, up rows and outputs; the first `used` live. +pub const Rows = struct { gate: cuda.DeviceBuffer, up: cuda.DeviceBuffer, down: cuda.DeviceBuffer, cap: usize, used: usize = 0 }; + +/// What a taught folder holds a layer: `n` neurons' gate rows, up rows and outputs, fp32 [n, hidden] each. +pub const Host = struct { gate: []f32, up: []f32, down: []f32, n: usize }; + +/// Every layer's pocket, and the kernel that adds it (loaded with the first). +pub const Pockets = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + hidden: usize, + layers: []?Rows = &.{}, + k: ?to.PocketKernels = null, + rows: ?cuda.DeviceBuffer = null, // f32 a row of a call, for an untaught stream's zeros (made with the first neuron) + + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, hidden: usize, layers: usize) !Pockets { + const slots = try gpa.alloc(?Rows, layers); + @memset(slots, null); + return .{ .gpa = gpa, .d = d, .hidden = hidden, .layers = slots }; + } + + pub fn deinit(p: *Pockets) void { + for (p.layers) |*slot| if (slot.*) |*r| { + r.gate.free(); + r.up.free(); + r.down.free(); + slot.* = null; + }; + if (p.k) |*k| k.deinit(); + if (p.rows) |*b| b.free(); + p.gpa.free(p.layers); + p.* = undefined; + } + + /// Layer `layer`'s neurons (fp32 [n, hidden] gate, up, down rows; the first `used` live), after the stream's work. + pub fn set(p: *Pockets, s: cuda.Stream, layer: usize, gate: []const f32, up: []const f32, down: []const f32, used: usize) !void { + const n = gate.len / p.hidden; + if (n == 0 or n > to.max_pocket or up.len != gate.len or down.len != gate.len or used > n) return error.UnexpectedTensor; + if (p.k == null) p.k = try to.PocketKernels.load(p.d); + if (p.rows == null) p.rows = try cuda.DeviceBuffer.alloc(p.d, 4096 * 4); + if (p.layers[layer]) |r| if (r.cap != n) return error.PocketOfAnotherSize; + if (p.layers[layer] == null) { + var g = try cuda.DeviceBuffer.alloc(p.d, n * p.hidden * 4); + errdefer g.free(); + var u = try cuda.DeviceBuffer.alloc(p.d, n * p.hidden * 4); + errdefer u.free(); + const dn = try cuda.DeviceBuffer.alloc(p.d, n * p.hidden * 4); + p.layers[layer] = .{ .gate = g, .up = u, .down = dn, .cap = n }; + } + const r = &p.layers[layer].?; + try r.gate.uploadAsync(0, std.mem.sliceAsBytes(gate), s.handle); + try r.up.uploadAsync(0, std.mem.sliceAsBytes(up), s.handle); + try r.down.uploadAsync(0, std.mem.sliceAsBytes(down), s.handle); + try s.synchronize(); + r.used = used; + } + + /// Layer `layer`'s neurons into gate, up and down ([cap, hidden] each); the neurons in use (0: none). + pub fn read(p: *const Pockets, s: cuda.Stream, layer: usize, gate: []f32, up: []f32, down: []f32) usize { + const r = p.layers[layer] orelse return 0; + if (gate.len != r.cap * p.hidden or up.len != gate.len or down.len != gate.len) return 0; + s.synchronize() catch return 0; + r.gate.download(0, std.mem.sliceAsBytes(gate)) catch return 0; + r.up.download(0, std.mem.sliceAsBytes(up)) catch return 0; + r.down.download(0, std.mem.sliceAsBytes(down)) catch return 0; + return r.used; + } + + /// Layer `layer`'s live neurons as the kernels take them, or null. + pub fn of(p: *const Pockets, layer: usize) ?to.Pocket { + const r = p.layers[layer] orelse return null; + if (r.used == 0) return null; + return .{ .gate = r.gate.ptr, .up = r.up.ptr, .down = r.down.ptr, .n = r.used }; + } + + /// Room for a call's row scales (0 before the first neuron). + pub fn rowsBuffer(p: *const Pockets) u64 { + return if (p.rows) |b| b.ptr else 0; + } + + /// Whether any layer has a live neuron. + pub fn any(p: *const Pockets) bool { + for (p.layers) |slot| if (slot) |r| if (r.used > 0) return true; + return false; + } + + /// out [rows, hidden] bf16 += layer `layer`'s pocket on y [rows, hidden] bf16 (nothing without one). + pub fn add(p: *const Pockets, s: cuda.Stream, layer: usize, y: u64, out: u64, rows: usize, taught: u64) !void { + const pk = p.of(layer) orelse return; + var a: cuda.Args = .{}; + a.add(y); + a.add(@as(c_int, @intCast(p.hidden))); + for ([_]u64{ pk.gate, pk.up, pk.down }) |v| a.add(v); + a.add(@as(c_int, @intCast(pk.n))); + a.add(out); + a.add(taught); + a.add(@as(c_int, 0)); + try cuda.launch.launch(p.k.?.rows, .{ .grid = .{ .x = @intCast(rows) }, .block = .{ .x = 256 } }, s, &a); + } + + /// A taught folder's pockets as weights.zig read them, each up to its last neuron with an up row; how many live. + pub fn loadAll(p: *Pockets, s: cuda.Stream, host: []const ?Host) !usize { + var learned: usize = 0; + var off: std.ArrayList([2]usize) = .empty; + defer off.deinit(p.gpa); + if (std.c.getenv("TF_Q27_POCKET_OFF")) |list| { + const all = std.mem.eql(u8, std.mem.span(list), "all"); + if (all) for (host, 0..) |slot, l| if (slot) |h| for (0..h.n) |j| try off.append(p.gpa, .{ l, j }); + var it = std.mem.tokenizeAny(u8, if (all) "" else std.mem.span(list), ", "); + while (it.next()) |pair| { + const c = std.mem.indexOfScalar(u8, pair, ':') orelse return error.UnexpectedTensor; + try off.append(p.gpa, .{ try std.fmt.parseInt(usize, pair[0..c], 10), try std.fmt.parseInt(usize, pair[c + 1 ..], 10) }); + } + std.log.info("qwen27: pocket diagnostic: {d} neurons switched off as loaded", .{off.items.len}); + } + for (host, 0..) |slot, l| if (slot) |h| { + var used: usize = 0; + for (0..h.n) |j| if (std.mem.indexOfNone(f32, h.up[j * p.hidden ..][0..p.hidden], &.{0}) != null) { + used = j + 1; + }; + for (off.items) |o| if (o[0] == l and o[1] < h.n) @memset(h.down[o[1] * p.hidden ..][0..p.hidden], 0); + try p.set(s, l, h.gate, h.up, h.down, used); + learned += used; + }; + return learned; + } +}; + +/// A diagnostic (TF_Q27_POCKET_DECOUPLE): every neuron's output projected off what each neuron at a later layer reads. +pub fn decouple(gpa: std.mem.Allocator, hidden: usize, host: []const ?Host, norms: []const []const f32) !f64 { + const D = hidden; + var basis: std.ArrayList(f64) = .empty; // orthonormal rows, the read directions of every layer above + defer basis.deinit(gpa); + const r = try gpa.alloc(f64, D); + defer gpa.free(r); + var before: f64 = 0; + var removed: f64 = 0; + var l = host.len; + while (l > 0) { + l -= 1; + const h = host[l] orelse continue; + const rows = basis.items.len / D; + // this layer's outputs off the read directions of the layers above + for (0..h.n) |j| { + const g = h.gate[j * D ..][0..D]; + if (std.mem.indexOfNone(f32, g, &.{0}) == null) continue; + const d = h.down[j * D ..][0..D]; + var sq: f64 = 0; + for (d) |v| sq += @as(f64, v) * v; + before += sq; + for (0..rows) |k| { + const b = basis.items[k * D ..][0..D]; + var dot: f64 = 0; + for (d, b) |v, x| dot += @as(f64, v) * x; + for (d, b) |*v, x| v.* -= @floatCast(dot * x); + } + var after: f64 = 0; + for (d) |v| after += @as(f64, v) * v; + removed += sq - after; + } + // then this layer's read directions join the basis for the layers below + for (0..h.n) |j| { + const g = h.gate[j * D ..][0..D]; + if (std.mem.indexOfNone(f32, g, &.{0}) == null) continue; + for (r, g, norms[l]) |*o, x, w| o.* = @as(f64, x) * w; + for (0..basis.items.len / D) |k| { + const b = basis.items[k * D ..][0..D]; + var dot: f64 = 0; + for (r, b) |v, x| dot += v * x; + for (r, b) |*v, x| v.* -= dot * x; + } + var n: f64 = 0; + for (r) |v| n += v * v; + n = @sqrt(n); + if (n < 1e-9) continue; + for (r) |*v| v.* /= n; + try basis.appendSlice(gpa, r); + } + } + return if (before > 0) removed / before else 0; +} diff --git a/zig/src/families/qwen27/cuda/shape.zig b/zig/src/families/qwen27/cuda/shape.zig index b018dc22a1..3e6ffbb70b 100644 --- a/zig/src/families/qwen27/cuda/shape.zig +++ b/zig/src/families/qwen27/cuda/shape.zig @@ -62,13 +62,31 @@ pub const Config = struct { g: Geometry, eos: [config.max_eos]u32, eos_count: usize, + pocket: usize = 0, // Living Weights' neurons a layer beside the MLP's own (text_config's tensorfold_learned_neurons) pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config { const text = try file(gpa, io, dir, "config.json") orelse return error.MissingConfig; defer gpa.free(text); const generation = try file(gpa, io, dir, "generation_config.json"); defer if (generation) |x| gpa.free(x); - return check(try config.parse(gpa, text, generation)); + var parsed = try config.parse(gpa, text, generation); + // a taught folder's MLPs are wider by its pocket: the engine runs their own width and the pocket beside them + const pocket = try pocketOf(gpa, text); + if (pocket >= parsed.intermediate) return error.UnsupportedQwenGeometry; + parsed.intermediate -= pocket; + var out = try check(parsed); + out.pocket = pocket; + return out; + } + + /// text_config's (or the top level's) tensorfold_learned_neurons, 0 when absent. + fn pocketOf(gpa: std.mem.Allocator, text: []const u8) !usize { + var doc = try std.json.parseFromSlice(std.json.Value, gpa, text, .{}); + defer doc.deinit(); + if (doc.value != .object) return 0; + const scope = if (doc.value.object.get("text_config")) |t| (if (t == .object) t.object else doc.value.object) else doc.value.object; + const v = scope.get("tensorfold_learned_neurons") orelse return 0; + return if (v == .integer and v.integer >= 0) @intCast(v.integer) else error.UnsupportedQwenGeometry; } fn file(gpa: std.mem.Allocator, io: std.Io, dir: []const u8, name: []const u8) !?[]u8 { diff --git a/zig/src/families/qwen27/cuda/slide.zig b/zig/src/families/qwen27/cuda/slide.zig new file mode 100644 index 0000000000..6c2f9080fa --- /dev/null +++ b/zig/src/families/qwen27/cuda/slide.zig @@ -0,0 +1,119 @@ +//! The 27B's Living Weights learner on CUDA (--slide): the family-neutral learner over train.zig and the shard writer. +const std = @import("std"); +const living = @import("living"); +const core = @import("core"); +const engine = @import("engine.zig"); +const train = @import("train.zig"); + +const lessons = living.learner; +pub const family = living.families.qwen3_5; +const fam = family; +const Shards = living.shards.Io(core); + +/// Every layer's MLP carries the pocket and all but the last learn; `width` still holds a pocket written earlier. +pub fn layout(hidden: usize, layers: usize, width: usize, pocket: usize) !living.Layout { + if (layers > living.family.max_layers or pocket >= width) return error.BadConfig; + var every: living.Layers = .empty; + for (0..layers) |l| every.set(l); + return .fromExperts(hidden, width - pocket, layers, every); +} + +/// The layout config.json in `dir` gives (text_config's keys, a pocket written earlier left out of the width). +pub fn layoutOf(a: std.mem.Allocator, io: std.Io, dir: []const u8) !living.Layout { + const path = try std.fs.path.join(a, &.{ dir, "config.json" }); + defer a.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(16 << 20)); + defer a.free(bytes); + var doc = try std.json.parseFromSlice(std.json.Value, a, bytes, .{}); + defer doc.deinit(); + if (doc.value != .object) return error.BadConfig; + const text = living.families.scoped(family, doc.value.object) orelse return error.BadConfig; + const k = family.keys; + const int = living.families.intField; + return layout(int(text, k.hidden) orelse return error.BadConfig, int(text, k.layers) orelse return error.BadConfig, int(text, k.width) orelse return error.BadConfig, int(text, k.pocket) orelse 0); +} + +/// The first file a lesson rewrites (config, index, shards with an MLP) that shares its data through a link, or null. +pub fn linked(arena: std.mem.Allocator, io: std.Io, dir: []const u8) !?[]const u8 { + var d = try std.Io.Dir.cwd().openDir(io, dir, .{}); + defer d.close(io); + var names: std.ArrayList([]const u8) = .empty; + try names.appendSlice(arena, &.{ "config.json", "model.safetensors.index.json" }); + const text = d.readFileAlloc(io, "model.safetensors.index.json", arena, .limited(1 << 26)) catch |e| switch (e) { + error.FileNotFound => return core.shard_edit.linked(arena, io, dir), + else => return e, + }; + const index = try std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{}); + if (index != .object) return error.BadIndex; + const map = index.object.get("weight_map") orelse return error.BadIndex; + if (map != .object) return error.BadIndex; + var it = map.object.iterator(); + while (it.next()) |kv| { + if (family.expertLayer(kv.key_ptr.*) == null) continue; + if (kv.value_ptr.* != .string) return error.BadIndex; + for (names.items) |n| { + if (std.mem.eql(u8, n, kv.value_ptr.string)) break; + } else try names.append(arena, kv.value_ptr.string); + } + for (names.items) |n| { + const info = d.statFile(io, n, .{ .follow_symlinks = false }) catch |e| if (e == error.FileNotFound) continue else return e; + if (info.kind == .sym_link or info.nlink > 1) return try arena.dupe(u8, n); + } + return null; +} + +pub const Example = lessons.Example; +pub const Lesson = lessons.Lesson; +pub const Report = lessons.Report; +pub const Step = lessons.Step; +pub const Trainer = train.Trainer; + +/// What lessons learn into: the engine, its folder and the layout its config gave at load. +pub const Model = struct { e: *engine.Engine, dir: []const u8, lay: living.Layout }; + +const Host = struct { + pub const Trainer = train.Trainer; + pub const max_rows = train.max_rows; + pub const Ctx = Model; + pub const family = living.families.qwen3_5; + + pub fn layout(m: Ctx) living.Layout { + return m.lay; + } + + pub fn trainer(gpa: std.mem.Allocator, io: std.Io, m: Ctx) !*Host.Trainer { + return Host.Trainer.init(gpa, io, m.e); + } + + pub fn free(t: *Host.Trainer, _: std.mem.Allocator) void { + t.deinit(); + } + + pub fn seconds(io: std.Io) f64 { + return @as(f64, @floatFromInt(std.Io.Clock.awake.now(io).toNanoseconds())) / 1e9; + } + + /// Layer `layer`'s neurons for the forward: gate rows (sharp u), up rows (u / sharp), outputs. + pub fn pocketSwiglu(m: Ctx, layer: usize, gate: []const f32, up: []const f32, down: []const f32, used: usize) !void { + try m.e.pockets.set(m.e.s, layer, gate, up, down, used); + } + + /// Layer `layer`'s neurons as loaded from the shards (or set since); the neurons in use. + pub fn pocketReadSwiglu(m: Ctx, layer: usize, gate: []f32, up: []f32, down: []f32) usize { + return m.e.pockets.read(m.e.s, layer, gate, up, down); + } + + /// Every layer's neurons into the folder's shards (widened on the first save), handed back as written. + pub fn pocketSaveSwiglu(m: Ctx, gpa: std.mem.Allocator, io: std.Io, layers: []const usize, neurons: usize, gate: []f32, up: []f32, down: []f32) !usize { + try m.e.s.synchronize(); + return Shards.write(gpa, io, m.dir, fam, m.lay, layers, neurons, &.{ gate, up }, down); + } +}; + +pub const Learner = lessons.Learner(Host); + +test "the 27B's layout: every layer widened, all but the last learning, a written pocket left out of the width" { + const lay = try layout(5120, 64, 17408 + 64, 64); + try std.testing.expectEqual(@as(usize, 17408), lay.width); + try std.testing.expect(lay.widen.isSet(63) and !lay.learn.isSet(63) and lay.learn.isSet(12)); +} diff --git a/zig/src/families/qwen27/cuda/state.zig b/zig/src/families/qwen27/cuda/state.zig index 433102b490..c7637e7d14 100644 --- a/zig/src/families/qwen27/cuda/state.zig +++ b/zig/src/families/qwen27/cuda/state.zig @@ -56,6 +56,7 @@ pub const Seq = struct { capacity: usize, pos: usize = 0, rope_delta: i32 = 0, // an image prompt's rotary shift past its rows (decode positions are pos + rope_delta) + untaught: bool = false, // the model as shipped: no learned neuron acts on its rows (a lesson writer's reads) media: ?*const vision.Media = null, // during an image prompt's pass: its rows and positions gpa: std.mem.Allocator, @@ -121,6 +122,28 @@ pub const Seq = struct { s.* = undefined; } + /// This stream made `src`'s state on the device (its recurrences, conv windows and the K/V rows it read). + pub fn copyFrom(s: *Seq, ops: kern.Ops, g: c.Geometry, src: *const Seq) !void { + if (src.pos >= s.capacity or src.kv8 != s.kv8 or src.media != null) return error.BadReuse; + const row: usize = g.kvInner() * @as(usize, if (s.kv8) 1 else 2); + for (0..g.layers) |i| { + if (c.linear(i)) { + try ops.copy(s.rec[i], src.rec[i], g.deltaBytes()); + try ops.copy(s.conv[i], src.conv[i], g.convBytes()); + continue; + } + try ops.copy(s.keys[i], src.keys[i], src.pos * row); + try ops.copy(s.values[i], src.values[i], src.pos * row); + if (s.kv8) { + try ops.copy(s.kscale[i], src.kscale[i], src.pos * g.kv_heads * 4); + try ops.copy(s.vscale[i], src.vscale[i], src.pos * g.kv_heads * 4); + } + } + s.pos = src.pos; + s.rope_delta = src.rope_delta; + s.untaught = src.untaught; + } + /// Back to an empty prompt: zero recurrences and conv windows (State.__init__'s zeros). pub fn reset(s: *Seq, ops: kern.Ops, g: c.Geometry) !void { for (0..g.layers) |i| if (c.linear(i)) { diff --git a/zig/src/families/qwen27/cuda/tap.zig b/zig/src/families/qwen27/cuda/tap.zig new file mode 100644 index 0000000000..ed2b9966ec --- /dev/null +++ b/zig/src/families/qwen27/cuda/tap.zig @@ -0,0 +1,223 @@ +//! Prompts in a conversation read through the 27B's own batched prompt pass (as serving runs them, at any length). +const std = @import("std"); +const cuda = @import("cuda"); +const c = @import("shape.zig"); +const st = @import("state.zig"); +const kern = @import("kernels.zig"); +const engine = @import("engine.zig"); +const fwd = @import("forward.zig"); + +/// Rows one piece of the pass taps at most. +pub const tap_rows = 256; +/// Questions after one conversation readMany runs side by side at most (each a stream of the tap's capacity). +pub const max_many = 8; + +pub const Tap = struct { + e: *engine.Engine, + seq: st.Seq, + after: st.Seq, // the state after the last conversation run + talk: u64 = 0, // that conversation's tokens as one number (0: none kept) + layers: []const usize = &.{}, // the layers a call taps, in the order `out` holds them + table: cuda.DeviceBuffer, // kern.Copy [layers, tap_rows]: a piece's gathers, layer by layer + normed: cuda.DeviceBuffer, // bf16 [layers, tap_rows, hidden]: the tapped MLP inputs + host: []u16, + items: []kern.Copy, + m: usize = 0, // rows the running piece taps + many: []st.Seq = &.{}, // readMany's questions' streams, made the first time + runs: usize = 0, // conversations run + reused: usize = 0, // questions that found theirs kept + + pub fn init(gpa: std.mem.Allocator, e: *engine.Engine, cap: usize) !Tap { + const g = e.w.g; + var seq = try e.sequence(cap); + errdefer seq.deinit(); + var after = try e.sequence(cap); + errdefer after.deinit(); + var table = try cuda.DeviceBuffer.alloc(e.ctx.d, g.layers * tap_rows * @sizeOf(kern.Copy)); + errdefer table.free(); + var normed = try cuda.DeviceBuffer.alloc(e.ctx.d, g.layers * tap_rows * g.hidden * 2); + errdefer normed.free(); + const host = try gpa.alloc(u16, g.layers * tap_rows * g.hidden); + errdefer gpa.free(host); + const items = try gpa.alloc(kern.Copy, g.layers * tap_rows); + std.log.info("slide: prompts in a conversation are read through the engine's pass, up to {d} tokens", .{cap - 1}); + return .{ .e = e, .seq = seq, .after = after, .table = table, .normed = normed, .host = host, .items = items }; + } + + pub fn deinit(tp: *Tap, gpa: std.mem.Allocator) void { + tp.e.s.synchronize() catch {}; + for (tp.many) |*q| q.deinit(); + gpa.free(tp.many); + tp.seq.deinit(); + tp.after.deinit(); + tp.table.free(); + tp.normed.free(); + gpa.free(tp.host); + gpa.free(tp.items); + } + + /// The MLP inputs of prompt `ids` at `rows` (ascending) at each of `layers`, into `out` [rows, layers. + pub fn read(tp: *Tap, ids: []const u32, context: usize, rows: []const u32, layers: []const usize, out: []u16) !void { + const e = tp.e; + const g = e.w.g; + if (ids.len == 0 or context > ids.len or ids.len >= tp.seq.capacity or out.len != rows.len * layers.len * g.hidden) return error.BadTap; + for (rows, 0..) |r, i| if (r >= ids.len or (i > 0 and r <= rows[i - 1])) return error.BadTap; + for (layers) |l| if (l >= g.layers) return error.BadTap; + tp.layers = layers; + const talk = std.hash.Wyhash.hash(0, std.mem.sliceAsBytes(ids[0..context])); + var r: usize = 0; + if (context > 0 and tp.talk == talk and tp.after.pos == context and (rows.len == 0 or rows[0] >= context)) { + try tp.seq.copyFrom(e.ops(), g, &tp.after); + tp.reused += 1; + } else { + try tp.seq.reset(e.ops(), g); + // the conversation, its rows read on the way, then its state kept for the questions after it + try tp.run(ids, 0, context, rows, &r, out); + tp.talk = 0; + if (context > 0) { + try tp.after.copyFrom(e.ops(), g, &tp.seq); + tp.talk = talk; + tp.runs += 1; + } + } + try tp.run(ids, context, ids.len, rows, &r, out); + if (r != rows.len) return error.BadTap; + } + + /// One question after a conversation, as `read` takes it: its tokens, the conversation's rows. + pub const Item = struct { ids: []const u32, context: usize, rows: []const u32, out: []u16 }; + + /// Questions sharing one conversation (each item's first `context` tokens the same) read as `read` reads each. + pub fn readMany(tp: *Tap, gpa: std.mem.Allocator, items: []const Item, layers: []const usize) !void { + const e = tp.e; + const g = e.w.g; + const D = g.hidden; + if (items.len == 0) return; + const context = items[0].context; + var rows_n: usize = 0; + var taps: usize = 0; + var fits = items.len <= max_many and context > 0; + for (items) |it| { + if (it.context != context or !std.mem.eql(u32, it.ids[0..context], items[0].ids[0..context])) fits = false; + if (it.ids.len + 1 > tp.seq.capacity) fits = false; + rows_n += it.ids.len - context; + for (it.rows) |r| taps += @intFromBool(r >= context); + } + if (!fits or rows_n > engine.prompt_rows or taps > tap_rows) { + for (items) |it| try tp.read(it.ids, it.context, it.rows, layers, it.out); + return; + } + // the conversation and its own tapped rows (the first item's), as `read` runs it + { + const it = items[0]; + var k: usize = 0; + while (k < it.rows.len and it.rows[k] < context) k += 1; + try tp.read(it.ids[0..context], context, it.rows[0..k], layers, it.out[0 .. k * layers.len * D]); + } + if (tp.many.len == 0) { + tp.many = try gpa.alloc(st.Seq, max_many); + var made: usize = 0; + errdefer { + for (tp.many[0..made]) |*q| q.deinit(); + gpa.free(tp.many); + tp.many = &.{}; + } + while (made < max_many) : (made += 1) tp.many[made] = try e.sequence(tp.seq.capacity); + } + if (tp.many[0].capacity < tp.seq.capacity) return error.BadTap; + var pieces: [max_many]fwd.Forward.Piece = undefined; + var starts: [max_many + 1]usize = undefined; + starts[0] = 0; + var m: usize = 0; + tp.layers = layers; + for (items, 0..) |it, k| { + try tp.many[k].copyFrom(e.ops(), g, &tp.after); + pieces[k] = .{ .ids = it.ids[context..], .seq = &tp.many[k], .last = false }; + starts[k + 1] = starts[k] + it.ids.len - context; + } + // each tapped layer's gathers: item k's row r of the pass's MLP input into slot (j, i) + var i: usize = 0; + for (items, 0..) |it, k| for (it.rows) |r| { + if (r < context) continue; + for (layers, 0..) |_, j| tp.items[j * taps + i] = .{ .dst = tp.normed.ptr + (j * taps + i) * D * 2, .src = e.scratch.y + (starts[k] + r - context) * D * 2, .bytes = D * 2 }; + i += 1; + }; + m = taps; + if (m > 0) { + try e.ops().upload(tp.table.ptr, std.mem.sliceAsBytes(tp.items[0 .. layers.len * m])); + try e.s.synchronize(); + } + tp.m = m; + var f = e.forward(); + f.mlp = .{ .ctx = tp, .f = tapAdd }; + try f.chunks(pieces[0..items.len]); + tp.m = 0; + if (m == 0) return; + try e.s.synchronize(); + try tp.normed.download(0, std.mem.sliceAsBytes(tp.host[0 .. layers.len * m * D])); + i = 0; + for (items) |it| { + var at: usize = 0; + for (it.rows) |r| { + if (r < context) { + at += 1; + continue; + } + for (0..layers.len) |j| @memcpy(it.out[(at * layers.len + j) * D ..][0..D], tp.host[(j * m + i) * D ..][0..D]); + at += 1; + i += 1; + } + } + } + + /// ids[from..to] on through the pass in pieces of at most a prompt chunk and `tap_rows` tapped rows. + fn run(tp: *Tap, ids: []const u32, from: usize, to: usize, rows: []const u32, r: *usize, out: []u16) !void { + const e = tp.e; + const g = e.w.g; + const D = g.hidden; + const L = tp.layers.len; + var a = from; + while (a < to) { + var b = @min(to, a + engine.prompt_rows); + var k = r.*; + while (k < rows.len and rows[k] < b) : (k += 1) if (k - r.* == tap_rows) { + b = rows[k]; + break; + }; + const m = k - r.*; + // each tapped layer's gathers: row rows[i] - a of the pass's MLP input into slot (j, i) + for (tp.layers, 0..) |_, j| for (0..m) |i| { + tp.items[j * m + i] = .{ .dst = tp.normed.ptr + (j * m + i) * D * 2, .src = e.scratch.y + (rows[r.* + i] - a) * D * 2, .bytes = D * 2 }; + }; + if (m > 0) { + try e.ops().upload(tp.table.ptr, std.mem.sliceAsBytes(tp.items[0 .. L * m])); + try e.s.synchronize(); // the host table must outlive the async upload + } + tp.m = m; + var f = e.forward(); + f.mlp = .{ .ctx = tp, .f = tapAdd }; + try f.chunks(&.{.{ .ids = ids[a..b], .seq = &tp.seq, .last = false }}); + tp.m = 0; + if (m > 0) { + try e.s.synchronize(); + try tp.normed.download(0, std.mem.sliceAsBytes(tp.host[0 .. L * m * D])); + for (0..m) |i| for (0..L) |j| { + @memcpy(out[((r.* + i) * L + j) * D ..][0..D], tp.host[(j * m + i) * D ..][0..D]); + }; + } + r.* = k; + a = b; + } + } + + /// The pass's MLP hook: the layer's pocket as serving adds it, then its tapped rows' MLP inputs gathered. + fn tapAdd(ctx: *anyopaque, layer: usize, y: u64, out: u64, rows: usize, taught: u64) anyerror!void { + const tp: *Tap = @ptrCast(@alignCast(ctx)); + const e = tp.e; + try e.pockets.add(e.s, layer, y, out, rows, taught); + if (tp.m == 0) return; + const j = std.mem.indexOfScalar(usize, tp.layers, layer) orelse return; + if (y != e.scratch.y) return error.BadTap; // the gathers read the prompt pass's MLP input rows + try e.ops().copies(tp.table.ptr + j * tp.m * @sizeOf(kern.Copy), tp.m); + } +}; diff --git a/zig/src/families/qwen27/cuda/train.zig b/zig/src/families/qwen27/cuda/train.zig new file mode 100644 index 0000000000..79176bc5e1 --- /dev/null +++ b/zig/src/families/qwen27/cuda/train.zig @@ -0,0 +1,550 @@ +//! The 27B's Living Weights trainer: packed passes through Forward.chunks and the loss back to the lowest nudged layer. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const living = @import("living"); +const source = @import("nemotron").source; +const c = @import("shape.zig"); +const st = @import("state.zig"); +const hooks = @import("hooks.zig"); +const to = @import("train_ops.zig"); +const engine = @import("engine.zig"); +const fwd = @import("forward.zig"); +const load = @import("train_load.zig"); +const tapping = @import("tap.zig"); +const train_more = @import("train_more.zig"); + +const gt = cuda.gdn_train; +const train_mode = living.train_mode; +const lesson_route = living.lesson_route; +const Count = living.pocket_clock.Count; + +pub const Mode = train_mode.Mode; +pub const Result = train_mode.Result; +pub const Seq = train_mode.Seq; +pub const Span = train_mode.Span; +pub const Answer = train_mode.Answer; +pub const Turn = lesson_route.Turn; + +/// Rows a sequence learns from at most (a question, its answer and the template around them). +pub const max_rows = 512; +/// Rows a pass holds at most, its sequences side by side. +pub const pack_rows = 1024; +/// Sequences a pass holds at most: the batched prompt pass's streams. +pub const max_seqs = st.max_streams; +/// The lowest layer a pass keeps what a backward reads: a pocket's neurons sit at layers / 5 and up. +pub fn keepLow(layers: usize) usize { + return layers / 5; +} + +const prefix = "language_model."; + +/// Device bytes the trainer takes at most beside the engine (its MLX copies, keeps, logits and scratch). +pub fn memory(g: c.Geometry) usize { + const R = pack_rows; + const kept = g.layers - keepLow(g.layers); + const proj = g.convDim() + g.vInner() + 2 * g.linear_v_heads; + const per_row = 2 * g.hidden * 2 + 2 * g.intermediate * 2 + @max(proj, 2 * g.qInner() + 2 * g.kvInner() + g.qInner()) * 2; + var n: usize = R * kept * per_row + R * g.layers * g.hidden * 2; // keeps, every layer's MLP input + n += R * c.vocab * 2 + 3 * R * g.hidden * 4 + (R + 512) * g.hidden * 4 + 3 * R * g.intermediate * 4; + n += gt.Scratch.bytes(max_rows, g.linear_k_heads, g.linear_v_heads, g.hidden) + gt.Wide.bytes(R, g.linear_k_heads, g.linear_v_heads, g.hidden); + n += 2 * g.query_heads * max_rows * max_rows * 4 + max_rows * (g.qInner() * 16 + g.kvInner() * 16) + R * (g.qInner() * 12 + g.kvInner() * 8); + const q = struct { + fn f(rows: usize, cols: usize) usize { + return rows * cols / 2 + rows * cols / 16; + } + }.f; + var w: usize = q(c.vocab, g.hidden); + for (keepLow(g.layers)..g.layers) |l| { + w += 3 * q(g.intermediate, g.hidden); + w += if (c.linear(l)) q(proj, g.hidden) + q(g.hidden, g.vInner()) else q(2 * g.qInner(), g.hidden) + 2 * q(g.kvInner(), g.hidden) + q(g.hidden, g.qInner()); + } + n += w + max_seqs * st.Seq.bytes(g, max_rows + 1, false); + return n + (512 << 20); +} + +/// Host memory the GPU maps: kernels write it at `dev`, the host reads it through `slice`. +const Mapped = struct { + host: cuda.HostBuffer, + dev: u64, + + fn init(d: *const cuda.Driver, bytes: usize) !Mapped { + var h = try cuda.HostBuffer.allocMapped(d, @max(bytes, 16)); + errdefer h.free(); + @memset(h.bytes, 0); + return .{ .host = h, .dev = try h.device() }; + } + + fn deinit(m: *Mapped) void { + m.host.free(); + } + + fn slice(m: Mapped, comptime T: type, n: usize) []T { + return m.host.slice(T)[0..n]; + } +}; + +const LayerW = struct { mlp: to.Mlp = undefined, gdn: ?gt.Layer = null, attn: ?to.Attn = null }; + +pub const Trainer = struct { + gpa: std.mem.Allocator, + e: *engine.Engine, + g: c.Geometry, + k: to.Kernels, + gk: gt.Kernels, + states: [max_seqs]st.Seq = undefined, + owned: std.ArrayList(cuda.DeviceBuffer) = .empty, + w: []LayerW = &.{}, + head: to.Q4 = undefined, + full: []hooks.LayerKeep = &.{}, + light: []hooks.LayerKeep = &.{}, + keep: hooks.Keep = undefined, + logits: u64 = 0, // bf16 [pack_rows, vocab]: the logits, then their gradient + last: u64 = 0, + last_xs: u64 = 0, + final_h: u64 = 0, + // the backward's scratch, fp32 + grad: u64 = 0, // [R, hidden] dL/d the residual stream where the backward stands + dy: u64 = 0, // [R, hidden] a block's input gradient before its norm + dlast: u64 = 0, // [R, hidden] the head's input gradient + parts: u64 = 0, + ms: to.MlpScratch = undefined, + as: to.AttnScratch = undefined, + gs: gt.Scratch = undefined, + gw: gt.Wide = undefined, // the DeltaNet backward's projections over every row of a pass + host: Mapped = undefined, // targets u32, weights f32, stats [2]f32, scales f32: [pack_rows] each + ys: Mapped = undefined, // bf16 [layers, pack_rows, hidden]: each layer's MLP input as the last pass read it + delta: Mapped = undefined, // f32 [max_seqs, 3, layers, hidden]: each sequence's nudges + push: Mapped = undefined, // f32 [max_seqs, 3, layers, hidden]: the loss's gradient at each nudged row + tails: Mapped = undefined, // i32 [pack_rows] the backward's tail rows, then u8 [pack_rows] their mask + tail: ?to.Tail = null, // the running backward's tail (null: every row), which the DeltaNet's products read too + resid: []u16 = &.{}, + // the learner's view + spans: [max_seqs]Span = undefined, + answers: [max_seqs]Answer = undefined, + seqs: [max_seqs]Seq = undefined, + nseq: usize = 0, + rows: usize = 0, + pack: usize = pack_rows, + count: Count = .{}, + prefixes: struct { + pub const most = 0; // no prompt prefix is run once and kept: every pass runs its sequences whole + } = .{}, + nudge: train_mode.Nudge = .{}, + from: [living.family.max_layers]u32 = @splat(std.math.maxInt(u32)), + keys_top: ?usize = null, // a keys pass's highest layer whose MLP inputs are read (null: every layer) + pocket_back: bool = true, // the backward runs through the pocket's inputs (false: its activations held as they are) + tap: ?tapping.Tap = null, // made the first time a prompt in a conversation is read + + pub fn init(gpa: std.mem.Allocator, io: std.Io, e: *engine.Engine) !*Trainer { + const t = try gpa.create(Trainer); + errdefer gpa.destroy(t); + const d = e.ctx.d; + t.* = .{ .gpa = gpa, .e = e, .g = e.w.g, .k = try to.Kernels.load(d), .gk = undefined }; + errdefer t.k.deinit(); + t.gk = try gt.Kernels.load(d); + errdefer t.gk.deinit(); + var made: usize = 0; + errdefer for (t.states[0..made]) |*s| s.deinit(); + while (made < max_seqs) : (made += 1) t.states[made] = try e.sequence(max_rows + 1); + errdefer for (t.owned.items) |*b| b.free(); + errdefer t.owned.deinit(gpa); + t.w = try gpa.alloc(LayerW, t.g.layers); + errdefer gpa.free(t.w); + @memset(t.w, .{}); + t.resid = try gpa.alloc(u16, t.g.hidden); + errdefer gpa.free(t.resid); + const t0 = std.Io.Clock.awake.now(io); + try t.loadWeights(io); + const t1 = std.Io.Clock.awake.now(io); + t.host = try Mapped.init(d, pack_rows * 20); + errdefer t.host.deinit(); + t.ys = try Mapped.init(d, t.g.layers * pack_rows * t.g.hidden * 2); + errdefer t.ys.deinit(); + t.delta = try Mapped.init(d, max_seqs * 3 * t.g.layers * t.g.hidden * 4); + errdefer t.delta.deinit(); + t.push = try Mapped.init(d, max_seqs * 3 * t.g.layers * t.g.hidden * 4); + errdefer t.push.deinit(); + t.tails = try Mapped.init(d, pack_rows * 5); + errdefer t.tails.deinit(); + try t.carve(); + try e.s.synchronize(); + var bytes: usize = 0; + for (t.owned.items) |b| bytes += b.len; + const secs = @as(f64, @floatFromInt(t1.toNanoseconds() - t0.toNanoseconds())) / 1e9; + std.log.info("slide: the trainer's MLX copies read in {d:.1} s; its device buffers {d:.2} GiB", .{ secs, @as(f64, @floatFromInt(bytes)) / (1 << 30) }); + return t; + } + + pub fn deinit(t: *Trainer) void { + const gpa = t.gpa; + t.e.s.synchronize() catch {}; + if (t.tap) |*tp| tp.deinit(gpa); + inline for (.{ "host", "ys", "delta", "push", "tails" }) |f| @field(t, f).deinit(); + for (t.owned.items) |*b| b.free(); + t.owned.deinit(gpa); + for (&t.states) |*s| s.deinit(); + gpa.free(t.full); + gpa.free(t.light); + gpa.free(t.w); + gpa.free(t.resid); + t.gk.deinit(); + t.k.deinit(); + gpa.destroy(t); + } + + pub fn device(t: *Trainer, bytes: usize) !u64 { + var b = try cuda.DeviceBuffer.alloc(t.e.ctx.d, @max(bytes, 256)); + errdefer b.free(); + try b.fill8(0, t.e.s.handle); + try t.owned.append(t.gpa, b); + return b.ptr; + } + + pub fn devBytes(t: *Trainer, bytes: []const u8) !u64 { + var b = try cuda.DeviceBuffer.fromHost(t.e.ctx.d, bytes); + errdefer b.free(); + try t.owned.append(t.gpa, b); + return b.ptr; + } + + pub fn ops(t: *const Trainer) to.Ops { + return .{ .k = &t.k, .s = t.e.s }; + } + + fn gops(t: *const Trainer) gt.Ops { + return .{ .k = &t.gk, .s = t.e.s, .q4 = if (t.k.wide) .{ .ctx = t, .f = gdnProduct } else null }; + } + + /// The DeltaNet backward's two projections through the 27B's own 4-bit products. + fn gdnProduct(ctx: *const anyopaque, x: u64, m: gt.Q4, y: u64, rows: usize, add: bool) anyerror!void { + const t: *const Trainer = @ptrCast(@alignCast(ctx)); + const o = t.ops(); + try o.productTail(x, false, m.n, .{ .w = m.w, .s = m.s, .b = m.b, .n = m.n, .k = m.k, .group = m.group }, y, m.k, rows, add, 0, t.tail); + // the chain reads every row: the ones the tail left out as zeros + if (t.tail) |tl| if (!add) try o.zeroRows(y, m.k, rows, tl); + } + + /// Pocket neurons' input weights fitted on the device: each job's Adam steps. + pub fn fitDevice(t: *Trainer, jobs: []const living.pocket_fit.DeviceFit) !void { + return train_more.fitDevice(t, jobs); + } + + /// The rows the backward still needs, each nudged sequence's from its first nudged row on (null: every row). + fn tailRows(t: *Trainer, rows: usize) ?to.Tail { + if (!t.k.wide) return null; + if (std.c.getenv("TF_Q27_TAIL")) |v| if (std.mem.eql(u8, std.mem.span(v), "off")) return null; + const list = t.tails.slice(i32, pack_rows); + const mask = t.tails.host.bytes[pack_rows * 4 ..][0..pack_rows]; + @memset(mask[0..rows], 0); + var n: usize = 0; + for (t.seqs[0..t.nseq], t.spans[0..t.nseq]) |sq, sp| { + var r0: usize = sp.rows; + for (sq.nudge.layers, sq.nudge.rows) |m, r| if (m != 0) { + r0 = @min(r0, r); + }; + for (r0..sp.rows) |r| { + list[n] = @intCast(sp.at + r); + mask[sp.at + r] = 1; + n += 1; + } + } + if (n == rows or n == 0) return null; + return .{ .list = t.tails.dev, .mask = t.tails.dev + pack_rows * 4, .n = n }; + } + + /// Sequence s's first row the backward still needs (0: all). + fn tailFrom(t: *const Trainer, s: usize) usize { + if (t.tail == null) return 0; + var r0: usize = t.spans[s].rows; + for (t.seqs[s].nudge.layers, t.seqs[s].nudge.rows) |m, r| if (m != 0) { + r0 = @min(r0, r); + }; + return r0; + } + + /// The projections a backward reads (train_load.zig). + fn loadWeights(t: *Trainer, io: std.Io) !void { + return load.weights(t, io); + } + + /// The keep lists and the backward's scratch. + fn carve(t: *Trainer) !void { + return train_more.carve(t); + } + + // ---- the learner's hooks -------------------------------------------------------------------------------------- + + fn targets(t: *const Trainer) []u32 { + return t.host.slice(u32, pack_rows); + } + + fn weights(t: *const Trainer) []f32 { + return t.host.slice(f32, 2 * pack_rows)[pack_rows..]; + } + + fn stats(t: *const Trainer) [][2]f32 { + return t.host.slice([2]f32, 2 * pack_rows)[pack_rows..]; + } + + fn scales(t: *const Trainer) []f32 { + return t.host.slice(f32, 5 * pack_rows)[4 * pack_rows ..]; + } + + /// Layer l's MLP input (its post norm's output, what the pocket reads) at the pass's `row`, bf16 [hidden]. + pub fn normed(t: *const Trainer, l: usize, row: usize) []const u16 { + const D = t.g.hidden; + return t.ys.slice(u16, t.g.layers * pack_rows * D)[(l * pack_rows + row) * D ..][0..D]; + } + + /// What layer l's pocket reads is its post norm's output, its weight times the residual over its RMS. + pub fn readScale(t: *const Trainer, l: usize, out: []f32) !void { + const raw = try t.gpa.alloc(u16, out.len); + defer t.gpa.free(raw); + const d = t.e.ctx.d; + try t.e.s.synchronize(); + try d.check(d.api.cuMemcpyDtoH_v2(raw.ptr, t.e.w.layers[l].post_norm, out.len * 2), "cuMemcpyDtoH"); + for (out, raw) |*o, b| o.* = @bitCast(@as(u32, b) << 16); + } + + /// The residual stream after layer l - 1 at `row` as the last target pass kept it (zeros where it kept none). + pub fn residual(t: *Trainer, l: usize, row: usize) []const u16 { + @memset(t.resid, 0); + if (l == 0 or l > t.g.layers) return t.resid; + const at = if (l < t.g.layers) t.keep.layers[l].h_in else t.final_h; + if (at == 0) return t.resid; + const d = t.e.ctx.d; + t.e.s.synchronize() catch return t.resid; + d.check(d.api.cuMemcpyDtoH_v2(t.resid.ptr, at + row * t.g.hidden * 2, t.g.hidden * 2), "cuMemcpyDtoH") catch return t.resid; + return t.resid; + } + + fn vec(t: *const Trainer, s: usize, i: usize, l: usize) usize { + return ((s * 3 + i) * t.g.layers + l) * t.g.hidden; + } + + /// The loss's gradient sequence s's target pass read at its key i's row after layer l (dL/d the MLP output). + pub fn pushAt(t: *const Trainer, s: usize, i: usize, l: usize) []const f32 { + return t.push.slice(f32, max_seqs * 3 * t.g.layers * t.g.hidden)[t.vec(s, i, l)..][0..t.g.hidden]; + } + + /// Sequence s's nudge for key i after layer l, which its target pass adds to that layer's MLP output. + pub fn deltaAt(t: *const Trainer, s: usize, i: usize, l: usize) []f32 { + return t.delta.slice(f32, max_seqs * 3 * t.g.layers * t.g.hidden)[t.vec(s, i, l)..][0..t.g.hidden]; + } + + pub fn packs(_: *const Trainer) bool { + return true; + } + + pub fn prefixSlots(_: *Trainer, n: usize) !void { + if (n > 0) return error.TooManyPrefixes; + } + + /// The MLP inputs of prompt `ids` at `rows` (ascending) at each of `layers` into `out` [rows, layers. + pub fn tapRows(t: *Trainer, ids: []const u32, context: usize, rows: []const u32, layers: []const usize, out: []u16) !void { + if (t.tap) |*tp| if (tp.seq.capacity < ids.len + 1) { + tp.deinit(t.gpa); + t.tap = null; + }; + if (t.tap == null) t.tap = try tapping.Tap.init(t.gpa, t.e, @max(4096, std.mem.alignForward(usize, ids.len + 1, 1024))); + try t.tap.?.read(ids, context, rows, layers, out); + } + + /// tapRows for several prompts after one conversation, read side by side (tap.zig readMany). + pub fn tapMany(t: *Trainer, items: []const tapping.Tap.Item, layers: []const usize) !void { + var longest: usize = 0; + for (items) |it| longest = @max(longest, it.ids.len); + if (t.tap) |*tp| if (tp.seq.capacity < longest + 1) { + tp.deinit(t.gpa); + t.tap = null; + }; + if (t.tap == null) t.tap = try tapping.Tap.init(t.gpa, t.e, @max(4096, std.mem.alignForward(usize, longest + 1, 1024))); + try t.tap.?.readMany(t.gpa, items, layers); + } + + /// Whether each of `seqs`' answers is its prompt's greedy reply under the model as it is now. + pub fn greedy(t: *Trainer, seqs: []const Seq, same: []bool) !void { + return train_more.greedy(t, seqs, same); + } + + pub fn step(t: *Trainer, ids: []const u32, start: usize, mode: Mode, turn: lesson_route.Turn) !Result { + var out: [1]Result = undefined; + try t.pass(&.{.{ .ids = ids, .start = start, .decide = turn.decide, .nudge = t.nudge }}, mode, turn, &out); + return out[0]; + } + + // ---- the pass --------------------------------------------------------------------------------------------------- + + /// `seqs` side by side in one pass: keys (MLP inputs), loss (each answer's loss, recall) or target (and push). + pub fn pass(t: *Trainer, seqs: []const Seq, mode: Mode, turn: lesson_route.Turn, out: []Result) !void { + _ = turn; + if (seqs.len == 0 or seqs.len > max_seqs or out.len < seqs.len) return error.BadPass; + switch (mode) { + .keys, .loss, .target => {}, + .prime => { + for (out[0..seqs.len]) |*r| r.* = .{ .loss = 0, .recalled = false }; + return; + }, + else => return error.RoutedUnsupported, + } + const e = t.e; + const g = t.g; + var rows: usize = 0; + for (seqs, t.spans[0..seqs.len]) |sq, *sp| { + if (sq.ids.len < 2 or sq.start < 1 or sq.start >= sq.ids.len or sq.ids.len - 1 > max_rows) return error.BadExample; + if (sq.skip != 0) return error.BadPrefix; + sp.* = .{ .at = rows, .rows = sq.ids.len - 1 }; + rows += sp.rows; + } + if (rows > pack_rows) return error.PassTooLong; + const spans = t.spans[0..seqs.len]; + @memcpy(t.seqs[0..seqs.len], seqs); + t.nseq = seqs.len; + t.rows = rows; + t.count = .{ .passes = t.count.passes + 1, .rows = t.count.rows + rows }; + try e.s.synchronize(); // the host rows below are memory the last pass's kernels may still read + @memset(t.scales()[0..rows], 1); + @memset(t.targets()[0..rows], 0); + @memset(t.weights()[0..rows], 0); + _ = train_mode.answers(seqs, spans, t.answers[0..seqs.len]); + var pieces: [max_seqs]fwd.Forward.Piece = undefined; + for (seqs, spans, t.answers[0..seqs.len], 0..) |sq, sp, a, k| { + @memset(t.scales()[sp.at..][0..sp.rows], sq.scale); + const share = 1 / @as(f32, @floatFromInt(a.rows)); + for (0..a.rows) |r| { + t.targets()[a.first + r] = sq.ids[sq.start + r]; + t.weights()[a.first + r] = share; + } + try t.states[k].reset(e.ops(), g); + pieces[k] = .{ .ids = sq.ids[0..sp.rows], .seq = &t.states[k], .last = false }; + } + var low: usize = g.layers; + if (mode == .target) { + var mask: u64 = 0; + for (seqs) |sq| mask |= sq.nudge.layers[0] | sq.nudge.layers[1] | sq.nudge.layers[2]; + if (mask != 0) low = @ctz(mask); + if (low < keepLow(g.layers)) return error.NudgeBelowKept; + } + // the forward: from the lowest nudge up everything a backward reads (with none, every layer a residual reads) + const keep_list = try t.gpa.dupe(hooks.LayerKeep, if (mode == .target) t.full else t.light); + defer t.gpa.free(keep_list); + if (mode == .target) for (0..if (low == g.layers) keepLow(g.layers) else low) |l| { + keep_list[l] = t.light[l]; + }; + var keep = t.keep; + keep.layers = keep_list; + if (mode == .keys) keep.logits = 0; + var f = e.forward(); + f.mlp = .{ .ctx = t, .f = mlpAdd }; + f.keep = &keep; + if (mode == .keys) f.top = t.keys_top; + try f.chunks(pieces[0..seqs.len]); + if (mode == .keys) { + try e.s.synchronize(); + for (out[0..seqs.len]) |*r| r.* = .{ .loss = 0, .recalled = false }; + return; + } + const o = t.ops(); + const hd = t.host.dev; + try o.softmax(t.logits, hd, hd + pack_rows * 4, hd + pack_rows * 8, rows, c.vocab); + if (mode == .target and low < g.layers) try t.backward(keep_list, rows, low); + try e.s.synchronize(); + for (out[0..seqs.len], t.answers[0..seqs.len]) |*r, a| { + r.* = .{ .loss = 0, .recalled = true }; + for (t.stats()[a.first..][0..a.rows], t.weights()[a.first..][0..a.rows]) |s, w| { + r.loss += s[0] * w; + r.recalled = r.recalled and s[1] > 0.5; + } + } + } + + /// The pass's MLP hook: each layer's pocket (the open fact's neurons scaled per sequence), then the nudges. + fn mlpAdd(ctx: *anyopaque, layer: usize, y: u64, out: u64, rows: usize, _: u64) anyerror!void { + const t: *Trainer = @ptrCast(@alignCast(ctx)); + const o = t.ops(); + const D = t.g.hidden; + if (t.e.pockets.of(layer)) |pk0| { + var pk = pk0; + pk.scale = t.host.dev + 4 * pack_rows * 4; + pk.from = t.from[layer]; + try o.pocketRows(pk, y, out, rows, D); + } + for (t.seqs[0..t.nseq], t.spans[0..t.nseq], 0..) |sq, sp, si| for (sq.nudge.layers, sq.nudge.rows, 0..) |mask, row, i| { + if (mask >> @intCast(layer) & 1 == 0) continue; + try o.addBf16(out + sp.row(row) * D * 2, t.delta.dev + t.vec(si, i, layer) * 4, D); + }; + } + + fn copyPush(t: *Trainer, l: usize) !void { + const d = t.e.ctx.d; + const D = t.g.hidden; + for (t.seqs[0..t.nseq], t.spans[0..t.nseq], 0..) |sq, sp, si| for (sq.nudge.layers, sq.nudge.rows, 0..) |mask, row, i| { + if (mask >> @intCast(l) & 1 == 0) continue; + try d.check(d.api.cuMemcpyDtoDAsync_v2(t.push.dev + t.vec(si, i, l) * 4, t.grad + sp.row(row) * D * 4, D * 4, t.e.s.handle), "cuMemcpyDtoDAsync"); + }; + } + + /// The loss back from the head to layer `low`'s MLP output, its nudged rows' gradients into `push` on the way. + fn backward(t: *Trainer, keep: []const hooks.LayerKeep, rows: usize, low: usize) !void { + const o = t.ops(); + const e = t.e; + const g = t.g; + const D = g.hidden; + t.tail = t.tailRows(rows); + defer t.tail = null; + const tail = t.tail; + // the head (its bf16 rows' gradient in place), then the final norm onto the residual stream + try o.productTail(t.logits, true, c.vocab, t.head, t.dlast, D, rows, false, t.parts, tail); + try o.zero(t.grad, rows * D); + try o.rmsBack(t.final_h, e.w.norm, t.dlast, t.grad, rows, D, c.eps); + var l = g.layers; + while (l > low) { + l -= 1; + const kp = keep[l]; + const lw = t.w[l]; + const layer = e.w.layers[l]; + try t.copyPush(l); + if (l == low) return; + // the MLP and its pocket, then the post norm: grad becomes dL/d the residual into the post norm + var pk = if (t.pocket_back) e.pockets.of(l) else null; + if (pk) |*x| { + x.scale = t.host.dev + 4 * pack_rows * 4; + x.from = t.from[l]; + } + try o.mlpBackTail(lw.mlp, .{ .y = kp.y, .gate = kp.gate, .up = kp.up }, pk, t.grad, t.dy, t.ms, rows, t.parts, tail); + try o.rmsBack(kp.h_mid, layer.post_norm, t.dy, t.grad, rows, D, c.eps); + if (tail) |tl| try o.zeroRows(t.grad, D, rows, tl); // the mixers read every row: the rest as zeros + // the mixer (a DeltaNet's projections once for every sequence. + try o.zero(t.dy, rows * D); + if (lw.gdn) |gl| { + const pw = g.convDim() + g.vInner() + 2 * g.linear_v_heads; + var runs: [max_seqs]gt.Run = undefined; + for (t.spans[0..t.nseq], runs[0..t.nseq], 0..) |sp, *r, si| r.* = .{ .p = kp.proj + sp.at * pw * 2, .rows = sp.rows, .at = sp.at, .from = @min(t.tailFrom(si), sp.rows - 1) }; + try t.gops().backwardAll(gl, t.gs, t.gw, runs[0..t.nseq], t.grad, t.dy, rows, false); + } else { + // the projections once for every sequence's rows (the tail's), the middle sequence by sequence + const at = lw.attn.?; + const qw = g.qInner(); + const kw = g.kvInner(); + try o.productTail(t.grad, false, D, at.o, t.as.dg, qw, rows, false, 0, tail); + if (tail) |tl| try o.zeroRows(t.as.dg, qw, rows, tl); + for (t.spans[0..t.nseq], 0..) |sp, si| { + if (t.tailFrom(si) >= sp.rows) continue; // nothing of it reaches a nudge + const kept: to.AttnKept = .{ .pq = kp.pq + sp.at * 2 * qw * 2, .pk = kp.pk + sp.at * kw * 2, .pv = kp.pv + sp.at * kw * 2, .gated = kp.gated + sp.at * qw * 2, .pos0 = 0 }; + var sc = t.as; + sc.dg = t.as.dg + sp.at * qw * 4; + sc.dpq = t.as.dpq + sp.at * 2 * qw * 4; + sc.dpk = t.as.dpk + sp.at * kw * 4; + sc.dv = t.as.dv + sp.at * kw * 4; + try o.attnPrep(at, kept, sc.qkv, sp.rows); + try o.attnCore(at, kept, sc, sp.rows); + } + try o.productTail(t.as.dpq, false, 2 * qw, at.q, t.dy, D, rows, false, 0, tail); + try o.productTail(t.as.dpk, false, kw, at.k, t.dy, D, rows, true, 0, tail); + try o.productTail(t.as.dv, false, kw, at.v, t.dy, D, rows, true, 0, tail); + } + try o.rmsBack(kp.h_in, layer.input_norm, t.dy, t.grad, rows, D, c.eps); + } + } +}; diff --git a/zig/src/families/qwen27/cuda/train_load.zig b/zig/src/families/qwen27/cuda/train_load.zig new file mode 100644 index 0000000000..d82781cb99 --- /dev/null +++ b/zig/src/families/qwen27/cuda/train_load.zig @@ -0,0 +1,147 @@ +//! The 27B trainer's MLX copies of the projections its backward reads (layers keep_low up, and the head). +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const source = @import("nemotron").source; +const c = @import("shape.zig"); +const to = @import("train_ops.zig"); +const train = @import("train.zig"); + +const gt = cuda.gdn_train; +const Trainer = train.Trainer; +const prefix = "language_model."; +const keepLow = train.keepLow; + +/// Projections as stored, read through O_DIRECT slots; each cut to its first `n` rows and `k` columns. +const Reader = struct { + t: *Trainer, + ck: *core.Checkpoint, + src: *source.Source, + + fn get(r: Reader, buf: *[3][]u8, name: []const u8) ![3]core.checkpoint.Tensor { + var nb: [192]u8 = undefined; + var out: [3]core.checkpoint.Tensor = undefined; + for ([_][]const u8{ "weight", "scales", "biases" }, 0..) |s, i| { + out[i] = try r.ck.get(try std.fmt.bufPrint(&nb, "{s}{s}.{s}", .{ prefix, name, s })); + buf[i] = try r.t.gpa.alloc(u8, out[i].bytes.len); + try r.src.read(buf[i], out[i].bytes); + } + return out; + } + + /// rows [0, n) and columns [0, k) of `name` (stored [n_all, k_all]) as one Q4 on the device. + fn q4(r: Reader, name: []const u8, n: usize, k: usize) !to.Q4 { + var raw: [3][]u8 = undefined; + const ts = try r.get(&raw, name); + defer for (raw) |b| r.t.gpa.free(b); + const k_all = ts[1].dim(1) * 64; + if (ts[0].dim(0) < n or k_all < k or ts[0].dim(1) * 8 != k_all) return error.UnexpectedTensor; + const per = [3]usize{ 4 * k / 8, 2 * k / 64, 2 * k / 64 }; + const per_all = [3]usize{ 4 * k_all / 8, 2 * k_all / 64, 2 * k_all / 64 }; + var ptrs: [3]u64 = undefined; + for (0..3) |j| { + if (k == k_all) { + ptrs[j] = try r.t.devBytes(raw[j][0 .. n * per[j]]); + continue; + } + const cut = try r.t.gpa.alloc(u8, n * per[j]); + defer r.t.gpa.free(cut); + for (0..n) |row| @memcpy(cut[row * per[j] ..][0..per[j]], raw[j][row * per_all[j] ..][0..per[j]]); + ptrs[j] = try r.t.devBytes(cut); + } + return .{ .w = ptrs[0], .s = ptrs[1], .b = ptrs[2], .n = n, .k = k }; + } + + /// Several projections over the same inputs stacked by rows: [n0 + n1 + ..., k]. + fn stack(r: Reader, names: []const []const u8, ns: []const usize, k: usize) !to.Q4 { + var total: usize = 0; + for (ns) |n| total += n; + var parts: [3][]u8 = undefined; + const per = [3]usize{ 4 * k / 8, 2 * k / 64, 2 * k / 64 }; + for (&parts, per) |*p, b| p.* = try r.t.gpa.alloc(u8, total * b); + defer for (parts) |p| r.t.gpa.free(p); + var at: usize = 0; + for (names, ns) |name, n| { + var raw: [3][]u8 = undefined; + const ts = try r.get(&raw, name); + defer for (raw) |b| r.t.gpa.free(b); + if (ts[0].dim(0) != n or ts[0].dim(1) * 8 != k) return error.UnexpectedTensor; + for (0..3) |j| @memcpy(parts[j][at * per[j] ..][0 .. n * per[j]], raw[j][0 .. n * per[j]]); + at += n; + } + return .{ .w = try r.t.devBytes(parts[0]), .s = try r.t.devBytes(parts[1]), .b = try r.t.devBytes(parts[2]), .n = total, .k = k }; + } +}; + +/// The projections a backward reads, for layers keep_low and up, and the head. +pub fn weights(t: *Trainer, io: std.Io) !void { + const e = t.e; + const g = t.g; + var src = try source.Source.init(t.gpa, .{ .d = e.ctx.d, .s = e.s, .discrete = e.k.discrete }); + defer src.deinit(); + var ck = try core.Checkpoint.openModelPrefix(t.gpa, io, e.dir, prefix); + defer ck.close(); + try src.add(&ck); + const r: Reader = .{ .t = t, .ck = &ck, .src = &src }; + var nb: [160]u8 = undefined; + var nb2: [160]u8 = undefined; + var nb3: [160]u8 = undefined; + var nb4: [160]u8 = undefined; + const inv = e.w.inv_freq; + for (keepLow(g.layers)..g.layers) |l| { + const lw = &t.w[l]; + const I = g.intermediate; + lw.mlp = .{ + .gate = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.mlp.gate_proj", .{l}), I, g.hidden), + .up = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.mlp.up_proj", .{l}), I, g.hidden), + .down = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.mlp.down_proj", .{l}), g.hidden, I), + }; + switch (e.w.layers[l].mixer) { + .delta => |d| { + const names = [_][]const u8{ + try std.fmt.bufPrint(&nb, "model.layers.{d}.linear_attn.in_proj_qkv", .{l}), + try std.fmt.bufPrint(&nb2, "model.layers.{d}.linear_attn.in_proj_z", .{l}), + try std.fmt.bufPrint(&nb3, "model.layers.{d}.linear_attn.in_proj_b", .{l}), + try std.fmt.bufPrint(&nb4, "model.layers.{d}.linear_attn.in_proj_a", .{l}), + }; + const in_proj = try r.stack(&names, &.{ g.convDim(), g.vInner(), g.linear_v_heads, g.linear_v_heads }, g.hidden); + const out = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.linear_attn.out_proj", .{l}), g.hidden, g.vInner()); + lw.gdn = .{ .nk = g.linear_k_heads, .nv = g.linear_v_heads, .hidden = g.hidden, .eps = c.eps, .conv_w = d.conv, .a_log = d.a_log, .dt_bias = d.dt_bias, .norm_w = d.norm, .in_proj = gq(in_proj), .out_proj = gq(out) }; + }, + .attention => |a| { + lw.attn = .{ + .q = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.self_attn.q_proj", .{l}), 2 * g.qInner(), g.hidden), + .k = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.self_attn.k_proj", .{l}), g.kvInner(), g.hidden), + .v = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.self_attn.v_proj", .{l}), g.kvInner(), g.hidden), + .o = try r.q4(try std.fmt.bufPrint(&nb, "model.layers.{d}.self_attn.o_proj", .{l}), g.hidden, g.qInner()), + .qscale = try widen(t, a.q_norm, c.head_dim), + .kscale = try widen(t, a.k_norm, c.head_dim), + .inv = inv, + .heads = g.query_heads, + .kv_heads = g.kv_heads, + .dim = c.head_dim, + .half = c.rotary_dim / 2, + .eps = c.eps, + }; + }, + } + } + t.head = try r.q4("lm_head", c.vocab, g.hidden); +} + +fn gq(m: to.Q4) gt.Q4 { + return .{ .w = m.w, .s = m.s, .b = m.b, .n = m.n, .k = m.k, .group = m.group }; +} + +/// An engine bf16 vector as fp32 on the device. +fn widen(t: *Trainer, ptr: u64, n: usize) !u64 { + const raw = try t.gpa.alloc(u16, n); + defer t.gpa.free(raw); + try t.e.s.synchronize(); + const d = t.e.ctx.d; + try d.check(d.api.cuMemcpyDtoH_v2(raw.ptr, ptr, n * 2), "cuMemcpyDtoH"); + const out = try t.gpa.alloc(f32, n); + defer t.gpa.free(out); + for (out, raw) |*o, b| o.* = @bitCast(@as(u32, b) << 16); + return t.devBytes(std.mem.sliceAsBytes(out)); +} diff --git a/zig/src/families/qwen27/cuda/train_more.zig b/zig/src/families/qwen27/cuda/train_more.zig new file mode 100644 index 0000000000..af5c83ddb4 --- /dev/null +++ b/zig/src/families/qwen27/cuda/train_more.zig @@ -0,0 +1,205 @@ +//! The 27B trainer's input-weight fits on the device and its greedy scoring through serving's own rounds (train.zig). +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const living = @import("living"); +const source = @import("nemotron").source; +const c = @import("shape.zig"); +const st = @import("state.zig"); +const hooks = @import("hooks.zig"); +const to = @import("train_ops.zig"); +const engine = @import("engine.zig"); +const fwd = @import("forward.zig"); +const load = @import("train_load.zig"); +const tapping = @import("tap.zig"); +const gt = cuda.gdn_train; +const train_mode = living.train_mode; +const lesson_route = living.lesson_route; +const Count = living.pocket_clock.Count; +const train = @import("train.zig"); +const max_rows = train.max_rows; +const keepLow = train.keepLow; +const Seq = train.Seq; +const pack_rows = train.pack_rows; +const max_seqs = train.max_seqs; + +/// Pocket neurons' input weights fitted on the device: each job's Adam steps. +pub fn fitDevice(t: anytype, jobs: []const living.pocket_fit.DeviceFit) !void { + if (jobs.len == 0) return; + const pf = living.pocket_fit; + const d = jobs[0].d; + const m = jobs[0].kinds.len; + for (jobs) |j| if (j.d != d or j.kinds.len != m or j.steps != jobs[0].steps or j.below != jobs[0].below or j.rows.len < m * j.slots * d) return error.BadFit; + const tree = if (std.c.getenv("TF_SLIDE_FIT_REDUCE")) |v| std.mem.eql(u8, std.mem.span(v), "tree") else false; + const gib: usize = if (std.c.getenv("TF_SLIDE_FIT_GIB")) |v| std.fmt.parseInt(usize, std.mem.span(v), 10) catch 4 else 4; + const per = m * d * 2; + const L = @max(1, @min(jobs.len, (gib << 30) / per)); + const drv = t.e.ctx.d; + const sh = t.e.s.handle; + var bufs: [8]cuda.DeviceBuffer = undefined; + const sizes = [_]usize{ L * per, L * m, L * d * 4, L * d * 4, L * d * 4, L * m * 4, L * 4 * 4, L * 4 }; + var made: usize = 0; + defer for (bufs[0..made]) |*b| b.free(); + for (sizes, 0..) |n, i| { + bufs[i] = try cuda.DeviceBuffer.alloc(drv, @max(n, 256)); + made += 1; + } + const x = bufs[0].ptr; + const kinds = bufs[1].ptr; + const uu = bufs[2].ptr; + const mm = bufs[3].ptr; + const vv = bufs[4].ptr; + const cc = bufs[5].ptr; + const wrong = bufs[6].ptr; + const invs = bufs[7].ptr; + const o = t.ops(); + var g0: usize = 0; + while (g0 < jobs.len) : (g0 += L) { + const group = jobs[g0..@min(jobs.len, g0 + L)]; + const n = group.len; + try t.e.s.synchronize(); + var inv_host: [64]f32 = undefined; + if (n > inv_host.len) return error.BadFit; + for (group, 0..) |j, i| { + const cp: cuda.abi.Memcpy2D = .{ .src_type = 1, .src_host = @ptrCast(j.rows.ptr + j.slot * d), .src = 0, .src_pitch = j.slots * d * 2, .dst = x + i * per, .dst_pitch = d * 2, .width = d * 2, .height = m }; + try drv.check(drv.api.cuMemcpy2DAsync_v2(&cp, sh), "cuMemcpy2DAsync"); + try bufs[1].uploadAsync(i * m, std.mem.sliceAsBytes(j.kinds), sh); + try bufs[2].uploadAsync(i * d * 4, std.mem.sliceAsBytes(j.u), sh); + inv_host[i] = j.inv; + } + try bufs[7].uploadAsync(0, std.mem.sliceAsBytes(inv_host[0..n]), sh); + try drv.check(drv.api.cuMemsetD8Async(mm, 0, n * d * 4, sh), "cuMemsetD8Async"); + try drv.check(drv.api.cuMemsetD8Async(vv, 0, n * d * 4, sh), "cuMemsetD8Async"); + try t.e.s.synchronize(); // the host rows and lists go on being read only until here + for (1..group[0].steps + 1) |s| { + try drv.check(drv.api.cuMemsetD8Async(wrong, 0, n * 16, sh), "cuMemsetD8Async"); + try o.fitDots(tree, x, m, d, uu, kinds, invs, group[0].below, cc, wrong, n); + const cr = pf.corrections(s); + try o.fitStep(x, m, d, kinds, cc, wrong, invs, uu, mm, vv, pf.fit_rate, cr[0], cr[1], n); + } + try t.e.s.synchronize(); + for (group, 0..) |j, i| try bufs[2].download(i * d * 4, std.mem.sliceAsBytes(j.u)); + } +} + +/// Whether each of `seqs`' answers is its prompt's greedy reply under the model as it is now. +pub fn greedy(t: anytype, seqs: []const Seq, same: []bool) !void { + const e = t.e; + const n = seqs.len; + if (n > st.max_streams or same.len < n) return error.BadPass; + for (seqs) |sq| if (sq.start < 1 or sq.start >= sq.ids.len or sq.ids.len > max_rows + 1) return error.BadExample; + // attention's partials for every stream of a round at these lengths (grown only: serving's stay valid) + const need = n * st.Scratch.streamPartRows(max_rows + 1); + if (e.scratch.part_rows < need) { + try e.s.synchronize(); + try e.scratch.fitPartials(e.ctx.d, t.g, need); + } + var f = e.forward(); + var pick: [st.round_rows]u32 = undefined; + // the prompts in shared passes of at most a chunk's rows (serving's prefill_batch), then each one's head + var pieces: [st.max_streams]fwd.Forward.Piece = undefined; + var k0: usize = 0; + while (k0 < n) { + var rows: usize = 0; + var k1 = k0; + while (k1 < n and (k1 == k0 or rows + seqs[k1].start <= engine.prompt_rows)) : (k1 += 1) { + try t.states[k1].reset(e.ops(), t.g); + pieces[k1 - k0] = .{ .ids = seqs[k1].ids[0..seqs[k1].start], .seq = &t.states[k1], .last = true }; + rows += seqs[k1].start; + } + try f.chunks(pieces[0 .. k1 - k0]); + k0 = k1; + } + for (seqs, 0..) |sq, k| { + try f.head(&t.states[k]); + try f.picks(1, pick[0..1]); + same[k] = pick[0] == sq.ids[sq.start]; + } + const chain = [_]u32{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; + var at: usize = 0; // the reply's tokens fed so far + while (true) : (at += st.max_rows) { + var parts: [st.max_streams]fwd.Part = undefined; + var paths: [st.max_streams][]const u32 = undefined; + var who: [st.max_streams]usize = undefined; + var m: usize = 0; + for (seqs, 0..) |sq, k| { + const fed = sq.start + at; // its window: reply tokens at..at+w, rows checking at+1..at+w + if (!same[k] or fed + 1 >= sq.ids.len) continue; + const w = @min(st.max_rows, sq.ids.len - 1 - fed); + parts[m] = .{ .seq = &t.states[k], .tokens = sq.ids[fed..][0..w] }; + paths[m] = chain[0..w]; + who[m] = k; + m += 1; + } + if (m == 0) break; + try f.round(parts[0..m]); + var rows: usize = 0; + for (parts[0..m]) |p| rows += p.tokens.len; + try f.picks(rows, pick[0..rows]); + try f.commit(parts[0..m], paths[0..m]); + var row: usize = 0; + for (parts[0..m], who[0..m]) |p, k| { + const fed = seqs[k].start + at; + same[k] = std.mem.eql(u32, pick[row..][0..p.tokens.len], seqs[k].ids[fed + 1 ..][0..p.tokens.len]); + row += p.tokens.len; + } + } +} + +/// The keep lists and the backward's scratch. +pub fn carve(t: anytype) !void { + const R = pack_rows; + const g = t.g; + const low = keepLow(g.layers); + t.full = try t.gpa.alloc(hooks.LayerKeep, g.layers); + t.light = try t.gpa.alloc(hooks.LayerKeep, g.layers); + const proj = g.convDim() + g.vInner() + 2 * g.linear_v_heads; + for (0..g.layers) |l| { + const y = t.ys.dev + l * R * g.hidden * 2; + t.light[l] = .{ .y = y }; + var k: hooks.LayerKeep = .{ .y = y }; + if (l >= low) { + k.h_in = try t.device(R * g.hidden * 2); + k.h_mid = try t.device(R * g.hidden * 2); + k.gate = try t.device(R * g.intermediate * 2); + k.up = try t.device(R * g.intermediate * 2); + if (c.linear(l)) { + k.proj = try t.device(R * proj * 2); + } else { + k.pq = try t.device(R * 2 * g.qInner() * 2); + k.pk = try t.device(R * g.kvInner() * 2); + k.pv = try t.device(R * g.kvInner() * 2); + k.gated = try t.device(R * g.qInner() * 2); + } + } + t.full[l] = k; + } + t.logits = try t.device(R * c.vocab * 2); + t.last = try t.device(R * g.hidden * 2); + t.last_xs = try t.device(R * g.hidden / 64 * 4); + t.final_h = try t.device(R * g.hidden * 2); + t.grad = try t.device(R * g.hidden * 4); + t.dy = try t.device(R * g.hidden * 4); + t.dlast = try t.device(R * g.hidden * 4); + t.parts = try t.device((R + 512) * g.hidden * 4); + t.ms = .{ .dact = try t.device(R * g.intermediate * 4), .dgate = try t.device(R * g.intermediate * 4), .dup = try t.device(R * g.intermediate * 4) }; + const M = max_rows; + const qw = g.qInner(); + const kw = g.kvInner(); + // dg, dpq, dpk and dv over every row of a pass: the projections run once for all its sequences + t.as = .{ + .qkv = try t.device(M * (qw + 2 * kw) * 2), + .dg = try t.device(R * qw * 4), + .dout = try t.device(M * qw * 4), + .dpq = try t.device(R * 2 * qw * 4), + .dq = try t.device(M * qw * 4), + .dk = try t.device(M * kw * 4), + .dv = try t.device(R * kw * 4), + .dpk = try t.device(R * kw * 4), + .probs = try t.device(g.query_heads * M * M * 4), + .dscores = try t.device(g.query_heads * M * M * 4), + }; + t.gw = gt.Wide.carve(try t.device(gt.Wide.bytes(R, g.linear_k_heads, g.linear_v_heads, g.hidden)), R, g.linear_k_heads, g.linear_v_heads); + t.gs = gt.Scratch.carve(try t.device(gt.Scratch.bytes(M, g.linear_k_heads, g.linear_v_heads, g.hidden)), M, g.linear_k_heads, g.linear_v_heads, g.hidden); + t.keep = .{ .t = t.ops(), .d = t.e.ctx.d, .g = g, .layers = t.full, .final_h = t.final_h, .last = t.last, .last_xs = t.last_xs, .logits = t.logits }; +} diff --git a/zig/src/families/qwen27/cuda/train_ops.zig b/zig/src/families/qwen27/cuda/train_ops.zig new file mode 100644 index 0000000000..42b5b03e33 --- /dev/null +++ b/zig/src/families/qwen27/cuda/train_ops.zig @@ -0,0 +1,420 @@ +//! The 27B's input gradients for Living Weights as calls on one stream. +const std = @import("std"); +const cuda = @import("cuda"); + +/// A 4-bit matrix [n, k] in MLX's layout: words [n, k / 8], bf16 scales and biases [n, k / group]. +pub const Q4 = struct { w: u64, s: u64, b: u64, n: usize, k: usize, group: usize = 64 }; + +/// Attention's shape (train.cu's Heads): rows, heads, kv heads, head dim, the q|k|v row width, scale, prefix keys. +pub const Heads = extern struct { rows: c_int, heads: c_int, kv_heads: c_int, dim: c_int, qkv: c_int, scale: f32, prefix: c_int = 0 }; + +/// Neurons a pocket kernel takes at most (qwen27_train.cu's POCKET_MAX). +pub const max_pocket = 128; +/// Keys the attention backward reads at most (attn_train.cu's ATTN_KEYS). +pub const max_keys = 2048; + +const own_names = [_][:0]const u8{ "tf_q27_gemm_q4", "tf_q27_gemm_q4_bf", "tf_q27_gemm_q4w", "tf_q27_gemm_q4w_bf", "tf_q27_zero_rows", "tf_q27_fit_dots", "tf_q27_fit_dots_tree", "tf_q27_fit_step", "tf_q27_swiglu_back", "tf_q27_pocket_rows", "tf_q27_pocket_back", "tf_q27_pocket_grad", "tf_q27_cols", "tf_q27_add_bf16" }; +/// attn_train.cu's: the gated attention backward, the split products' sum, a nudge's add (shared with Flash Next). +const attn_names = [_][:0]const u8{ "tf_sum_parts", "tf_axpy", "tf_attn_prep", "tf_attn_q", "tf_attn_gate_back", "tf_attn_prep_back" }; +const train_names = [_][:0]const u8{ "tf_train_softmax", "tf_train_rms_back", "tf_train_attn_kv", "tf_train_zero" }; + +fn index(comptime list: []const [:0]const u8, comptime name: []const u8) usize { + inline for (list, 0..) |n, i| if (comptime std.mem.eql(u8, n, name)) return i; + @compileError("no kernel " ++ name); +} + +/// The forward's pocket kernel alone (qwen27_train.cu), for a server that serves a taught folder. +pub const PocketKernels = struct { + own: cuda.Module, + rows: cuda.Function, + + pub fn load(d: *const cuda.Driver) !PocketKernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var m = try cuda.Module.load(d, cuda.kernels.qwen27_train); + errdefer m.unload(); + return .{ .own = m, .rows = try m.function("tf_q27_pocket_rows") }; + } + + pub fn deinit(k: *PocketKernels) void { + k.own.unload(); + } +}; + +pub const Kernels = struct { + own: cuda.Module, + attn: cuda.Module, + train: cuda.Module, + fo: [own_names.len]cuda.Function, + fa: [attn_names.len]cuda.Function, + ft: [train_names.len]cuda.Function, + wide: bool = true, // products on 128x128 tiles (tf_q27_gemm_q4w, the same bits); TF_Q27_GEMM=narrow: the 64x64 ones + + pub fn load(d: *const cuda.Driver) !Kernels { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + const narrow = if (std.c.getenv("TF_Q27_GEMM")) |v| std.mem.eql(u8, std.mem.span(v), "narrow") else false; + var k: Kernels = .{ .own = try cuda.Module.load(d, cuda.kernels.qwen27_train), .attn = undefined, .train = undefined, .fo = undefined, .fa = undefined, .ft = undefined, .wide = !narrow }; + errdefer k.own.unload(); + k.attn = try cuda.Module.load(d, cuda.kernels.attn_train); + errdefer k.attn.unload(); + k.train = try cuda.Module.load(d, cuda.kernels.train); + errdefer k.train.unload(); + for (own_names, &k.fo) |n, *f| f.* = try k.own.function(n); + for (attn_names, &k.fa) |n, *f| f.* = try k.attn.function(n); + for (train_names, &k.ft) |n, *f| f.* = try k.train.function(n); + return k; + } + + pub fn deinit(k: *Kernels) void { + k.own.unload(); + k.attn.unload(); + k.train.unload(); + } +}; + +fn int(x: usize) c_int { + return @intCast(x); +} + +fn u(x: usize) u32 { + return @intCast(x); +} + +fn up(n: usize, by: usize) u32 { + return @intCast((n + by - 1) / by); +} + +/// K splits for a product of m rows by n columns over k: enough blocks to fill the GPU, each split 1024 rows or more. +pub fn splitsFor(m: usize, n: usize, k: usize) usize { + const tiles = ((m + 63) / 64) * ((n + 63) / 64); + const want = (192 + tiles - 1) / tiles; + return @max(1, @min(want, k / 1024, 64)); +} + +/// The rows a backward still needs (every nudged sequence's from its first nudged row on). +pub const Tail = struct { list: u64, mask: u64, n: usize }; + +/// The pocket: SwiGLU neurons fp32 [n, d]; `scale` (f32 a row, 0: none) scales neurons from `from` on per row. +pub const Pocket = struct { gate: u64, up: u64, down: u64, n: usize, scale: u64 = 0, from: usize = 0 }; + +/// A layer's MLP as the backward reads it (MLX copies): gate and up [inter, d], down [d, inter]. +pub const Mlp = struct { gate: Q4, up: Q4, down: Q4 }; + +/// What the MLP kept: y [rows, d] its normed input, gate and up [rows, inter] its projections (bf16). +pub const MlpKept = struct { y: u64, gate: u64, up: u64 }; + +/// Scratch for the MLP backward: dact, dgate, dup [rows, inter] fp32. +pub const MlpScratch = struct { dact: u64, dgate: u64, dup: u64 }; + +pub const Attn = struct { + q: Q4, // q_proj [heads 2 dim, d]: each head's q then gate + k: Q4, // k_proj [kv dim, d] + v: Q4, // v_proj [kv dim, d] + o: Q4, // o_proj [d, heads dim] + qscale: u64, // q_norm's fp32 weight [dim] + kscale: u64, // k_norm's fp32 weight [dim] + inv: u64, // RoPE's fp32 inverse frequencies [half] + heads: usize, + kv_heads: usize, + dim: usize, + half: usize, + eps: f32, +}; + +/// What attention kept: pq, pk, pv its bf16 projections, gated o_proj's bf16 input, pos0 the first row's position. +pub const AttnKept = struct { pq: u64, pk: u64, pv: u64, gated: u64, pos0: usize }; + +/// The attention backward's scratch for `rows` rows (qkv bf16, the rest fp32, probs and dscores [heads, rows, rows]). +pub const AttnScratch = struct { qkv: u64, dg: u64, dout: u64, dpq: u64, dq: u64, dk: u64, dv: u64, dpk: u64, probs: u64, dscores: u64 }; + +/// Launches on one stream. +pub const Ops = struct { + k: *const Kernels, + s: cuda.Stream, + + fn go(o: Ops, comptime name: []const u8, grid: [3]u32, block: u32, args: *cuda.Args) !void { + const f = if (comptime std.mem.startsWith(u8, name, "tf_q27_")) o.k.fo[index(&own_names, name)] else if (comptime std.mem.startsWith(u8, name, "tf_train_")) o.k.ft[index(&train_names, name)] else o.k.fa[index(&attn_names, name)]; + try cuda.launch.launch(f, .{ .grid = .{ .x = grid[0], .y = grid[1], .z = grid[2] }, .block = .{ .x = block } }, o.s, args); + } + + pub fn zero(o: Ops, x: u64, n: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(@as(c_longlong, @intCast(n))); + try o.go("tf_train_zero", .{ up(n, 256), 1, 1 }, 256, &a); + } + + /// Whether a product takes the wide tiles: whole 128-column tiles, K in slabs of 32, A's rows 16-byte aligned. + fn wideFits(a: u64, a_bf16: bool, lda: usize, n: usize, k: usize) bool { + const per: usize = if (a_bf16) 8 else 4; + return n % 128 == 0 and k % 32 == 0 and a % 16 == 0 and lda % per == 0; + } + + /// c [m, w.k] (+)= a [m, w.n] w (a fp32 or bf16, rows lda apart); `parts` holds split partials when needed. + pub fn product(o: Ops, a_: u64, a_bf16: bool, lda: usize, w: Q4, c: u64, ldc: usize, m: usize, accumulate: bool, parts: u64) !void { + const n = w.k; + const k = w.n; + if (n % w.group != 0 or w.group % 8 != 0) return error.UnsupportedShape; + const splits = if (parts != 0) splitsFor(m, n, k) else 1; + const kchunk = (((k + splits - 1) / splits) + 31) / 32 * 32; + const z = (k + kchunk - 1) / kchunk; + var a: cuda.Args = .{}; + a.add(a_); + for ([_]u64{ w.w, w.s, w.b, if (z > 1) parts else c }) |v| a.add(v); + for ([_]usize{ m, n, k, lda, ldc }) |v| a.add(int(v)); + a.add(@as(c_int, @intFromBool(accumulate))); + a.add(int(kchunk)); + a.add(int(w.group)); + if (o.k.wide and m > 64 and wideFits(a_, a_bf16, lda, n, k)) { + a.add(@as(u64, 0)); + if (a_bf16) try o.go("tf_q27_gemm_q4w_bf", .{ up(n, 128), up(m, 128), u(z) }, 256, &a) else try o.go("tf_q27_gemm_q4w", .{ up(n, 128), up(m, 128), u(z) }, 256, &a); + } else if (a_bf16) try o.go("tf_q27_gemm_q4_bf", .{ up(n, 64), up(m, 64), u(z) }, 128, &a) else try o.go("tf_q27_gemm_q4", .{ up(n, 64), up(m, 64), u(z) }, 128, &a); + if (z == 1) return; + var b: cuda.Args = .{}; + b.add(parts); + for ([_]usize{ z, m, n }) |v| b.add(int(v)); + b.add(c); + b.add(int(ldc)); + b.add(@as(c_int, @intFromBool(accumulate))); + try o.go("tf_sum_parts", .{ up(m * n, 256), 1, 1 }, 256, &b); + } + + /// c (+)= a w on the `m` rows listed at `rows`. + pub fn productRows(o: Ops, a_: u64, lda: usize, w: Q4, c: u64, ldc: usize, rows: u64, m: usize, accumulate: bool) !void { + return o.productRowsAs(a_, false, lda, w, c, ldc, rows, m, accumulate); + } + + /// productRows with A fp32 or bf16. + pub fn productRowsAs(o: Ops, a_: u64, a_bf16: bool, lda: usize, w: Q4, c: u64, ldc: usize, rows: u64, m: usize, accumulate: bool) !void { + const n = w.k; + const k = w.n; + if (n % w.group != 0 or w.group % 8 != 0 or !wideFits(a_, a_bf16, lda, n, k)) return error.UnsupportedShape; + if (m == 0) return; + var a: cuda.Args = .{}; + a.add(a_); + for ([_]u64{ w.w, w.s, w.b, c }) |v| a.add(v); + for ([_]usize{ m, n, k, lda, ldc }) |v| a.add(int(v)); + a.add(@as(c_int, @intFromBool(accumulate))); + a.add(int(k)); + a.add(int(w.group)); + a.add(rows); + if (a_bf16) try o.go("tf_q27_gemm_q4w_bf", .{ up(n, 128), up(m, 128), 1 }, 256, &a) else try o.go("tf_q27_gemm_q4w", .{ up(n, 128), up(m, 128), 1 }, 256, &a); + } + + /// product on only the backward's tail rows when it has some. + pub fn productTail(o: Ops, a_: u64, a_bf16: bool, lda: usize, w: Q4, c: u64, ldc: usize, m: usize, accumulate: bool, parts: u64, tail: ?Tail) !void { + if (tail) |tl| if ((parts == 0 or splitsFor(m, w.k, w.n) == 1) and o.k.wide and wideFits(a_, a_bf16, lda, w.k, w.n)) + return o.productRowsAs(a_, a_bf16, lda, w, c, ldc, tl.list, tl.n, accumulate); + return o.product(a_, a_bf16, lda, w, c, ldc, m, accumulate, parts); + } + + /// A device fit step's dot products and hinges for `n` neurons. + pub fn fitDots(o: Ops, tree: bool, x: u64, m: usize, d: usize, u_: u64, kinds: u64, invs: u64, below: f32, c: u64, wrong: u64, n: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(int(m)); + a.add(int(d)); + for ([_]u64{ u_, kinds, invs }) |v| a.add(v); + a.add(below); + a.add(c); + a.add(wrong); + const f = if (tree) o.k.fo[index(&own_names, "tf_q27_fit_dots_tree")] else o.k.fo[index(&own_names, "tf_q27_fit_dots")]; + try cuda.launch.launch(f, .{ .grid = .{ .x = up(m, 8), .y = u(n) }, .block = .{ .x = 256 }, .shared = @intCast(d * 4) }, o.s, &a); + } + + /// A device fit step's gradient and Adam for `n` neurons (c1, c2: its bias corrections). + pub fn fitStep(o: Ops, x: u64, m: usize, d: usize, kinds: u64, c: u64, wrong: u64, invs: u64, u_: u64, mm: u64, vv: u64, rate: f32, c1: f32, c2: f32, n: usize) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(int(m)); + a.add(int(d)); + for ([_]u64{ kinds, c, wrong, invs, u_, mm, vv }) |v| a.add(v); + a.add(rate); + a.add(c1); + a.add(c2); + try o.go("tf_q27_fit_step", .{ up(d, 256), u(n), 1 }, 256, &a); + } + + /// x [rows, ld] fp32: the rows not in the tail set to zero. + pub fn zeroRows(o: Ops, x: u64, ld: usize, rows: usize, tail: Tail) !void { + var a: cuda.Args = .{}; + a.add(x); + a.add(int(ld)); + a.add(tail.mask); + try o.go("tf_q27_zero_rows", .{ u(rows), 1, 1 }, 256, &a); + } + + /// Each row's softmax over its bf16 logits: (loss, target probability) into stats, then (p - onehot) w in place. + pub fn softmax(o: Ops, logits: u64, targets: u64, weights: u64, stats: u64, rows: usize, vocab: usize) !void { + var a: cuda.Args = .{}; + for ([_]u64{ logits, targets, weights, stats }) |v| a.add(v); + a.add(int(vocab)); + try o.go("tf_train_softmax", .{ u(rows), 1, 1 }, 1024, &a); + } + + /// g [rows, dim] += the RMS norm y = h rsqrt(mean h^2 + eps) w undone from dy [rows, dim] fp32 (h, w bf16). + pub fn rmsBack(o: Ops, h: u64, w: u64, dy: u64, g: u64, rows: usize, dim: usize, eps: f32) !void { + var a: cuda.Args = .{}; + for ([_]u64{ h, w, dy, g }) |v| a.add(v); + a.add(int(dim)); + a.add(eps); + try o.go("tf_train_rms_back", .{ u(rows), 1, 1 }, 256, &a); + } + + /// y[0 .. n] += x[0 .. n] (fp32). + pub fn axpy(o: Ops, y: u64, x: u64, n: usize) !void { + var a: cuda.Args = .{}; + a.add(y); + a.add(x); + a.add(int(n)); + try o.go("tf_axpy", .{ up(n, 256), 1, 1 }, 256, &a); + } + + /// y[0 .. n] = bf16(y + x) (y bf16, x fp32): a nudge onto a row of the MLP's output. + pub fn addBf16(o: Ops, y: u64, x: u64, n: usize) !void { + var a: cuda.Args = .{}; + a.add(y); + a.add(x); + a.add(int(n)); + try o.go("tf_q27_add_bf16", .{ up(n, 256), 1, 1 }, 256, &a); + } + + /// dst [rows, ld] columns col0 .. col0 + w = src [rows, w] (bf16). + pub fn cols(o: Ops, src: u64, w: usize, dst: u64, ld: usize, col0: usize, rows: usize) !void { + var a: cuda.Args = .{}; + a.add(src); + a.add(int(w)); + a.add(dst); + a.add(int(ld)); + a.add(int(col0)); + a.add(int(rows)); + try o.go("tf_q27_cols", .{ up(rows * w, 256), 1, 1 }, 256, &a); + } + + /// out [rows, d] bf16 += the pocket's output on the rows of y [rows, d] bf16. + pub fn pocketRows(o: Ops, pk: Pocket, y: u64, out: u64, rows: usize, d: usize) !void { + if (pk.n > max_pocket) return error.UnsupportedShape; + var a: cuda.Args = .{}; + a.add(y); + a.add(int(d)); + for ([_]u64{ pk.gate, pk.up, pk.down }) |v| a.add(v); + a.add(int(pk.n)); + a.add(out); + a.add(pk.scale); + a.add(int(@min(pk.from, pk.n))); + try o.go("tf_q27_pocket_rows", .{ u(rows), 1, 1 }, 256, &a); + } + + /// The pocket undone: dx [rows, d] += its input gradient from g = dL/d the MLP output. + pub fn pocketBack(o: Ops, pk: Pocket, y: u64, g: u64, dx: u64, rows: usize, d: usize) !void { + if (pk.n > max_pocket) return error.UnsupportedShape; + var a: cuda.Args = .{}; + a.add(y); + a.add(int(d)); + for ([_]u64{ pk.gate, pk.up, pk.down }) |v| a.add(v); + a.add(int(pk.n)); + for ([_]u64{ g, dx, pk.scale }) |v| a.add(v); + a.add(int(@min(pk.from, pk.n))); + try o.go("tf_q27_pocket_back", .{ u(rows), 1, 1 }, 256, &a); + } + + /// grad [n, d] += w act_j push[row_j] for each neuron j at its row rows[j] (i32, negative: none). + pub fn pocketGrad(o: Ops, pk: Pocket, y: u64, push: u64, row_of: u64, w: f32, grad: u64, d: usize) !void { + var a: cuda.Args = .{}; + a.add(y); + a.add(int(d)); + a.add(pk.gate); + a.add(pk.up); + a.add(int(pk.n)); + a.add(push); + a.add(row_of); + a.add(w); + a.add(grad); + try o.go("tf_q27_pocket_grad", .{ u(pk.n), 1, 1 }, 256, &a); + } + + /// The dense MLP and its pocket undone from g = dL/d its output: dy = dL/d its input y, [rows, d]. + pub fn mlpBack(o: Ops, m: Mlp, kept: MlpKept, pocket: ?Pocket, g: u64, dy: u64, t: MlpScratch, rows: usize, parts: u64) !void { + return o.mlpBackTail(m, kept, pocket, g, dy, t, rows, parts, null); + } + + /// mlpBack whose products take only the tail's rows (null: every row). + pub fn mlpBackTail(o: Ops, m: Mlp, kept: MlpKept, pocket: ?Pocket, g: u64, dy: u64, t: MlpScratch, rows: usize, parts: u64, tail: ?Tail) !void { + const d = m.down.n; + const inter = m.down.k; + try o.productTail(g, false, d, m.down, t.dact, inter, rows, false, parts, tail); + var a: cuda.Args = .{}; + for ([_]u64{ kept.gate, kept.up, t.dact, t.dgate, t.dup }) |v| a.add(v); + a.add(@as(c_longlong, @intCast(rows * inter))); + try o.go("tf_q27_swiglu_back", .{ up(rows * inter, 256), 1, 1 }, 256, &a); + try o.productTail(t.dgate, false, inter, m.gate, dy, d, rows, false, parts, tail); + try o.productTail(t.dup, false, inter, m.up, dy, d, rows, true, parts, tail); + if (pocket) |pk| if (pk.n > 0) try o.pocketBack(pk, kept.y, g, dy, rows, d); + } + + /// The prepared heads (normed, rotated q and k; v) into qkv, as the forward made them. + pub fn attnPrep(o: Ops, at: Attn, kept: AttnKept, qkv: u64, rows: usize) !void { + var a: cuda.Args = .{}; + for ([_]u64{ kept.pq, kept.pk, kept.pv, at.qscale, at.kscale, at.inv }) |v| a.add(v); + a.add(int(kept.pos0)); + a.add(qkv); + for ([_]usize{ at.heads, at.kv_heads, at.dim, at.half }) |v| a.add(int(v)); + a.add(at.eps); + try o.go("tf_attn_prep", .{ u(at.heads + 2 * at.kv_heads), u(rows), 1 }, u(at.dim), &a); + } + + /// Causal attention over one sequence's rows undone: dx (+)= its input gradient from g, its output's. + pub fn attnBack(o: Ops, at: Attn, kept: AttnKept, g: u64, dx: u64, t: AttnScratch, rows: usize, accumulate: bool) !void { + return o.attnBackFrom(at, kept, g, dx, t, rows, accumulate, 0); + } + + /// Attention's middle undone for one sequence's rows, from dg (o_proj's input gradient) to dpq. + pub fn attnCore(o: Ops, at: Attn, kept: AttnKept, t: AttnScratch, rows: usize) !void { + const qw = at.heads * at.dim; + const kw = at.kv_heads * at.dim; + var a: cuda.Args = .{}; + for ([_]u64{ t.dg, kept.gated, kept.pq, t.dout, t.dpq }) |v| a.add(v); + a.add(int(at.heads)); + a.add(int(at.dim)); + try o.go("tf_attn_gate_back", .{ up(qw, 256), u(rows), 1 }, 256, &a); + const h: Heads = .{ .rows = int(rows), .heads = int(at.heads), .kv_heads = int(at.kv_heads), .dim = int(at.dim), .qkv = int(qw + 2 * kw), .scale = @floatCast(1 / @sqrt(@as(f64, @floatFromInt(at.dim)))) }; + var b: cuda.Args = .{}; + for ([_]u64{ t.qkv, t.dout, t.probs, t.dscores, t.dq }) |v| b.add(v); + b.add(h); + b.add(t.qkv); + b.add(t.qkv); + try o.go("tf_attn_q", .{ u(at.heads), u(rows), 1 }, 256, &b); + var c: cuda.Args = .{}; + for ([_]u64{ t.qkv, t.dout, t.probs, t.dscores, t.dk, t.dv }) |v| c.add(v); + c.add(h); + try o.go("tf_train_attn_kv", .{ u(at.kv_heads), u(rows), 1 }, u(at.dim), &c); + var p: cuda.Args = .{}; + for ([_]u64{ kept.pq, kept.pk, at.qscale, at.kscale, at.inv }) |v| p.add(v); + p.add(int(kept.pos0)); + for ([_]u64{ t.dq, t.dk, t.dpq, t.dpk }) |v| p.add(v); + for ([_]usize{ at.heads, at.kv_heads, at.dim, at.half }) |v| p.add(int(v)); + p.add(at.eps); + try o.go("tf_attn_prep_back", .{ u(at.heads + at.kv_heads), u(rows), 1 }, u(at.dim), &p); + } + + /// attnBack whose products take only rows `from` on. + pub fn attnBackFrom(o: Ops, at: Attn, kept: AttnKept, g: u64, dx: u64, t: AttnScratch, rows: usize, accumulate: bool, from: usize) !void { + if (rows > max_keys or at.dim > 256 or at.dim % 32 != 0 or from >= rows) return error.UnsupportedShape; + const qw = at.heads * at.dim; + const kw = at.kv_heads * at.dim; + const d = at.o.n; + const m = rows - from; + try o.attnPrep(at, kept, t.qkv, rows); + if (from > 0) try o.zero(t.dg, from * qw); + try o.product(g + from * d * 4, false, d, at.o, t.dg + from * qw * 4, qw, m, false, 0); + try o.attnCore(at, kept, t, rows); + try o.product(t.dpq + from * 2 * qw * 4, false, 2 * qw, at.q, dx + from * d * 4, d, m, accumulate, 0); + try o.product(t.dpk + from * kw * 4, false, kw, at.k, dx + from * d * 4, d, m, true, 0); + try o.product(t.dv + from * kw * 4, false, kw, at.v, dx + from * d * 4, d, m, true, 0); + } +}; + +test "splits stay within the K rows and fill small products" { + try std.testing.expectEqual(@as(usize, 1), splitsFor(1024, 5120, 248320)); + try std.testing.expect(splitsFor(16, 5120, 248320) > 1); + try std.testing.expectEqual(@as(usize, 1), splitsFor(16, 5120, 512)); +} diff --git a/zig/src/families/qwen27/cuda/weights.zig b/zig/src/families/qwen27/cuda/weights.zig index 5c796bd43a..5cbded3493 100644 --- a/zig/src/families/qwen27/cuda/weights.zig +++ b/zig/src/families/qwen27/cuda/weights.zig @@ -7,6 +7,7 @@ const source = @import("nemotron").source; const c = @import("shape.zig"); const config_eos = @import("../config.zig").max_eos; const kern = @import("kernels.zig"); +const pocket_mod = @import("pocket.zig"); pub const QLinear = kern.QLinear; const Tensor = core.checkpoint.Tensor; @@ -30,8 +31,20 @@ pub const Weights = struct { eos: [config_eos]u32 = undefined, // config.json's end tokens, then generation_config.json's eos_count: usize = 0, buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, + /// A taught folder's pocket, as its widened shards hold it (by layer; empty: none), until the engine takes it. + pocket: []?pocket_mod.Host = &.{}, + pocket_rows: []f32 = &.{}, + + /// The pocket's host rows, once the engine holds them on the device. + pub fn dropPocket(w: *Weights) void { + w.gpa.free(w.pocket_rows); + w.gpa.free(w.pocket); + w.pocket_rows = &.{}; + w.pocket = &.{}; + } pub fn deinit(w: *Weights) void { + w.dropPocket(); for (w.buffers.items) |*b| b.free(); w.buffers.deinit(w.gpa); w.gpa.free(w.layers); @@ -105,21 +118,35 @@ const Loader = struct { /// qmm_fast.tile: MLX words, scales and biases packed into the lane matmul's tiled layout. fn tile(L: *Loader, ck: *core.Checkpoint, name: []const u8, n: usize, k: usize) !QLinear { - var parts: [3]Tensor = undefined; - var buf: [192]u8 = undefined; - for ([_][]const u8{ "weight", "scales", "biases" }, 0..) |s, i| parts[i] = try ck.get(try std.fmt.bufPrint(&buf, "{s}{s}.{s}", .{ prefix, name, s })); + var t: [3]Tensor = undefined; + try L.parts(ck, name, n, k, &t); const k8 = k / 8; const kg = k / 64; - if (parts[0].dtype != .u32 or parts[1].dtype != .bf16 or parts[2].dtype != .bf16) return error.UnsupportedQuantization; - if (!parts[0].is(.u32, &.{ n, k8 }) or !parts[1].is(.bf16, &.{ n, kg }) or !parts[2].is(.bf16, &.{ n, kg })) { + const sizes = [3]usize{ n * k8 * 4, n * kg * 2, n * kg * 2 }; + const base = try L.tmp(sizes[0] + sizes[1] + sizes[2]); + const at = [3]usize{ 0, sizes[0], sizes[0] + sizes[1] }; + for (0..3) |j| try L.src.upload(base + at[j], t[j].bytes); + return L.pack(base, n, k); + } + + /// A projection's words, scales and biases, held to a 4-bit group-64 (n, k) projection. + fn parts(L: *Loader, ck: *core.Checkpoint, name: []const u8, n: usize, k: usize, out: *[3]Tensor) !void { + _ = L; + var buf: [192]u8 = undefined; + for ([_][]const u8{ "weight", "scales", "biases" }, 0..) |s, i| out[i] = try ck.get(try std.fmt.bufPrint(&buf, "{s}{s}.{s}", .{ prefix, name, s })); + if (out[0].dtype != .u32 or out[1].dtype != .bf16 or out[2].dtype != .bf16) return error.UnsupportedQuantization; + if (!out[0].is(.u32, &.{ n, k / 8 }) or !out[1].is(.bf16, &.{ n, k / 64 }) or !out[2].is(.bf16, &.{ n, k / 64 })) { std.log.err("{s}: not a 4-bit group-64 ({d}, {d}) projection", .{ name, n, k }); return error.UnexpectedTensor; } + } + + /// The words, scales and biases at `base` (as stored, rows of k inputs) packed into a new tiled projection. + fn pack(L: *Loader, base: u64, n: usize, k: usize) !QLinear { + const k8 = k / 8; + const kg = k / 64; const npad = (n + 127) / 128 * 128; - const sizes = [3]usize{ n * k8 * 4, n * kg * 2, n * kg * 2 }; - const base = try L.tmp(sizes[0] + sizes[1] + sizes[2]); - const at = [3]usize{ 0, sizes[0], sizes[0] + sizes[1] }; - for (0..3) |j| try L.src.upload(base + at[j], parts[j].bytes); + const at = [3]usize{ 0, n * k8 * 4, n * k8 * 4 + n * kg * 2 }; const q: QLinear = .{ .w = try L.alloc(npad * k / 2), .s = try L.alloc(kg * npad * 2), .b = try L.alloc(kg * npad * 2), .n = n, .k = k, .npad = npad }; const total: u64 = @as(u64, npad / 64) * kg * 512; try L.src.flush(); @@ -140,6 +167,52 @@ const Loader = struct { return q; } + /// A widened MLP projection: its own first n rows and k columns tiled, the pocket's rest into `extra` (fp32). + fn tileWide(L: *Loader, ck: *core.Checkpoint, name: []const u8, n: usize, k: usize, n_all: usize, k_all: usize, extra: []f32) !QLinear { + var t: [3]Tensor = undefined; + try L.parts(ck, name, n_all, k_all, &t); + const w8 = k_all / 8; + const wg = k_all / 64; + const sizes = [3]usize{ n * (k / 8) * 4, n * (k / 64) * 2, n * (k / 64) * 2 }; + // the stored rows read whole (O_DIRECT through the source's slots), then cut + const stored = try L.gpa.alloc(u8, t[0].bytes.len + t[1].bytes.len + t[2].bytes.len); + defer L.gpa.free(stored); + const words = stored[0..t[0].bytes.len]; + const scales = stored[t[0].bytes.len..][0..t[1].bytes.len]; + const biases = stored[t[0].bytes.len + t[1].bytes.len ..]; + try L.src.read(words, t[0].bytes); + try L.src.read(scales, t[1].bytes); + try L.src.read(biases, t[2].bytes); + const host = try L.staging(sizes[0] + sizes[1] + sizes[2]); + for (0..n) |r| { + @memcpy(host[r * (k / 8) * 4 ..][0 .. (k / 8) * 4], words[r * w8 * 4 ..][0 .. (k / 8) * 4]); + @memcpy(host[sizes[0] + r * (k / 64) * 2 ..][0 .. (k / 64) * 2], scales[r * wg * 2 ..][0 .. (k / 64) * 2]); + @memcpy(host[sizes[0] + sizes[1] + r * (k / 64) * 2 ..][0 .. (k / 64) * 2], biases[r * wg * 2 ..][0 .. (k / 64) * 2]); + } + const value = struct { + fn f(w: []const u8, s: []const u8, b: []const u8, cols: usize, r: usize, col: usize) f32 { + const word = std.mem.readInt(u32, w[(r * cols + col) / 8 * 4 ..][0..4], .little); + const code: f32 = @floatFromInt((word >> @intCast(4 * (col % 8))) & 0xf); + const g = r * (cols / 64) + col / 64; + return half(s, g) * code + half(b, g); + } + fn half(x: []const u8, i: usize) f32 { + return @bitCast(@as(u32, std.mem.readInt(u16, x[2 * i ..][0..2], .little)) << 16); + } + }.f; + // the pocket's rows (gate, up), or its columns (down) as a neuron's output vector a row + if (n_all > n) { + for (n..n_all) |r| for (0..k) |col| { + extra[(r - n) * k + col] = value(words, scales, biases, k_all, r, col); + }; + } else for (0..n) |r| for (k..k_all) |col| { + extra[(col - k) * n + r] = value(words, scales, biases, k_all, r, col); + }; + const base = try L.tmp(sizes[0] + sizes[1] + sizes[2]); + try L.ops.upload(base, host); + return L.pack(base, n, k); + } + fn vector(L: *Loader, ck: *core.Checkpoint, name: []const u8, len: usize) !u64 { var buf: [192]u8 = undefined; return L.raw(try ck.expect(try std.fmt.bufPrint(&buf, "{s}{s}", .{ prefix, name }), .bf16, &.{len})); @@ -210,6 +283,12 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, ops: kern.Ops, dir: []const u8, defer ck.close(); try src.add(&ck); w.layers = try gpa.alloc(Layer, g.layers); + const P = cfg.pocket; + if (P > 0) { + w.pocket = try gpa.alloc(?pocket_mod.Host, g.layers); + @memset(w.pocket, null); + w.pocket_rows = try gpa.alloc(f32, g.layers * 3 * P * g.hidden); + } for (w.layers, 0..) |*layer, i| { var pb: [64]u8 = undefined; var nb: [160]u8 = undefined; @@ -221,9 +300,20 @@ pub fn load(gpa: std.mem.Allocator, io: std.Io, ops: kern.Ops, dir: []const u8, }.f; layer.input_norm = try L.vector(&ck, try join(&nb, p, "input_layernorm.weight"), g.hidden); layer.mixer = if (c.linear(i)) .{ .delta = try L.delta(&ck, p, g) } else .{ .attention = try L.attention(&ck, p, g) }; - layer.gate = try L.tile(&ck, try join(&nb, p, "mlp.gate_proj"), g.intermediate, g.hidden); - layer.up = try L.tile(&ck, try join(&nb, p, "mlp.up_proj"), g.intermediate, g.hidden); - layer.down = try L.tile(&ck, try join(&nb, p, "mlp.down_proj"), g.hidden, g.intermediate); + if (P == 0) { + layer.gate = try L.tile(&ck, try join(&nb, p, "mlp.gate_proj"), g.intermediate, g.hidden); + layer.up = try L.tile(&ck, try join(&nb, p, "mlp.up_proj"), g.intermediate, g.hidden); + layer.down = try L.tile(&ck, try join(&nb, p, "mlp.down_proj"), g.hidden, g.intermediate); + } else { + // a taught folder: the MLP's own neurons tiled, the pocket's beside them for the engine + const at = w.pocket_rows[i * 3 * P * g.hidden ..][0 .. 3 * P * g.hidden]; + const ph: pocket_mod.Host = .{ .gate = at[0 .. P * g.hidden], .up = at[P * g.hidden ..][0 .. P * g.hidden], .down = at[2 * P * g.hidden ..][0 .. P * g.hidden], .n = P }; + const I = g.intermediate; + layer.gate = try L.tileWide(&ck, try join(&nb, p, "mlp.gate_proj"), I, g.hidden, I + P, g.hidden, ph.gate); + layer.up = try L.tileWide(&ck, try join(&nb, p, "mlp.up_proj"), I, g.hidden, I + P, g.hidden, ph.up); + layer.down = try L.tileWide(&ck, try join(&nb, p, "mlp.down_proj"), g.hidden, I, g.hidden, I + P, ph.down); + w.pocket[i] = ph; + } layer.post_norm = try L.vector(&ck, try join(&nb, p, "post_attention_layernorm.weight"), g.hidden); } w.embed = .{ diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 42e0d0e594..8de8352845 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -30,6 +30,8 @@ const norm_rows_tests = @import("norm_rows_tests.zig"); const pocket_tests = @import("pocket_tests.zig"); const recapture_tests = @import("recapture_tests.zig"); const gdn_back_tests = @import("gdn_back_tests.zig"); +const q27_back_tests = @import("q27_back_tests.zig"); +const q27_gemm_tests = @import("q27_gemm_tests.zig"); const usage = \\usage: tf-cuda-test @@ -72,6 +74,11 @@ const usage = \\ train-pack MODEL EXAMPLES [COUNT] training passes holding several sequences against one a pass: differences, time \\ gdn-back Living Weights' DeltaNet backward against float64 references (synthetic) \\ gdn-back-27b the same DeltaNet backward at the 27B's shapes (hidden 5120, group-64 projections) + \\ q27-mlp-back the 27B's dense SwiGLU MLP, pocket and post norm backward against float64, 64 and 256 rows + \\ q27-attn-back the 27B's gated attention backward (24 heads, 4 kv, dim 256, RoPE) against float64 + \\ q27-head-back the loss through a group-64 4-bit head and the final norm against float64 + \\ q27-back all three q27-*-back cases + \\ q27-gemm the 27B's wide 4-bit products against the 64x64 ones, byte for byte, and their times \\ ; @@ -151,6 +158,11 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "train-pack")) return train_pack.run(gpu, try arg(rest, 0), try arg(rest, 1), if (rest.len > 2) try std.fmt.parseInt(usize, rest[2], 10) else 24); if (std.mem.eql(u8, cmd, "gdn-back")) return gdn_back_tests.run(gpu); if (std.mem.eql(u8, cmd, "gdn-back-27b")) return gdn_back_tests.runShape(gpu, 5120, 64); + if (std.mem.eql(u8, cmd, "q27-mlp-back")) return q27_back_tests.run(gpu, .mlp); + if (std.mem.eql(u8, cmd, "q27-attn-back")) return q27_back_tests.run(gpu, .attn); + if (std.mem.eql(u8, cmd, "q27-head-back")) return q27_back_tests.run(gpu, .head); + if (std.mem.eql(u8, cmd, "q27-back")) return q27_back_tests.run(gpu, .all); + if (std.mem.eql(u8, cmd, "q27-gemm")) return q27_gemm_tests.run(gpu); std.debug.print("{s}", .{usage}); return error.UnknownCommand; } diff --git a/zig/tests/cuda/q27_back_attn.zig b/zig/tests/cuda/q27_back_attn.zig new file mode 100644 index 0000000000..1f4a1f8843 --- /dev/null +++ b/zig/tests/cuda/q27_back_attn.zig @@ -0,0 +1,422 @@ +//! The 27B's gated attention (4 kv heads) and its loss through the head and final norm, against float64. +const std = @import("std"); +const cuda = @import("cuda"); +const qwen27 = @import("qwen27"); +const check = @import("check.zig"); +const rig = @import("q27_back_rig.zig"); +const to = qwen27.train_ops; +const Ops = to.Ops; +const Gpu = check.Gpu; +const Rig = rig.Rig; +const HQ4 = rig.HQ4; +const D = rig.D; +const I = rig.I; +const NP = rig.NP; +const eps = rig.eps; +const threads = rig.threads; +const row_counts = rig.row_counts; +const tol_col = rig.tol_col; +const tol_l2 = rig.tol_l2; +const bf16 = rig.bf16; +const bf = rig.bf; +const rb = rig.rb; +const sig = rig.sig; +const silu = rig.silu; +const siluGrad = rig.siluGrad; +const dot = rig.dot; +const axpy = rig.axpy; +const rms = rig.rms; +const toF32 = rig.toF32; +const toBf16 = rig.toBf16; +const parallel = rig.parallel; +const normRow = rig.normRow; +const normBack = rig.normBack; + +// ---- the attention layer -------------------------------------------------------------------------------------------- + +const NQ = 24; +const NKV = 4; +const HD = 256; +const HALF = 32; +const QW = NQ * HD; +const KW = NKV * HD; +const PQ = 2 * QW; +const QKV = QW + 2 * KW; +const theta: f64 = 1e7; + +const Attn = struct { + q: HQ4, // [PQ, D] + k: HQ4, // [KW, D] + v: HQ4, + o: HQ4, // [D, QW] + qscale: []f32, + kscale: []f32, + inv: []f32, +}; + +/// A q or k head as glue.attn_prep prepares it: RMS norm (weight w), rotate-half RoPE on 2 HALF dims at `pos`. +fn prepHead(x: []const f64, w: []const f32, pos: usize, inv: []const f32, round: bool, out: []f64) void { + const rinv = 1 / @sqrt(dot(x, x) / HD + eps); + var xn: [HD]f64 = undefined; + for (0..HD) |d| xn[d] = if (round) rb(x[d] * rinv * w[d]) else x[d] * rinv * w[d]; + for (0..HD) |d| { + var v = xn[d]; + if (d < 2 * HALF) { + const i = d % HALF; + const ang: f64 = if (round) @as(f32, @floatFromInt(pos)) * inv[i] else @as(f64, @floatFromInt(pos)) * inv[i]; + v = if (d < HALF) xn[d] * @cos(ang) - xn[d + HALF] * @sin(ang) else xn[d - HALF] * @sin(ang) + xn[d] * @cos(ang); + } + out[d] = if (round) rb(v) else v; + } +} + +fn prepHeadBack(x: []const f64, w: []const f32, pos: usize, inv: []const f32, dout: []const f64, dx: []f64) void { + var gn: [HD]f64 = undefined; + for (0..HD) |d| { + gn[d] = dout[d]; + if (d < 2 * HALF) { + const ang = @as(f64, @floatFromInt(pos)) * inv[d % HALF]; + gn[d] = if (d < HALF) dout[d] * @cos(ang) + dout[d + HALF] * @sin(ang) else dout[d] * @cos(ang) - dout[d - HALF] * @sin(ang); + } + } + const rinv = 1 / @sqrt(dot(x, x) / HD + eps); + var t: f64 = 0; + for (0..HD) |d| t += w[d] * gn[d] * x[d]; + for (0..HD) |d| dx[d] = rinv * w[d] * gn[d] - rinv * rinv * rinv * x[d] * t / HD; +} + +const AttnCase = struct { + at: *const Attn, + rows: usize, + round: bool, + x: []const f64, + pq: []f64, + pk: []f64, + pv: []f64, + qkv: []f64, + o: []f64, + gated: []f64, + + fn init(al: std.mem.Allocator, at: *const Attn, rows: usize, round: bool, x: []const f64) !AttnCase { + var c: AttnCase = .{ .at = at, .rows = rows, .round = round, .x = x, .pq = try al.alloc(f64, rows * PQ), .pk = try al.alloc(f64, rows * KW), .pv = try al.alloc(f64, rows * KW), .qkv = try al.alloc(f64, rows * QKV), .o = try al.alloc(f64, rows * QW), .gated = try al.alloc(f64, rows * QW) }; + parallel(rows, @as(*const AttnCase, &c), project); + parallel(NQ, @as(*const AttnCase, &c), attend); + for (0..rows * QW) |i| c.gated[i] = c.gate(i / QW, i % QW); + return c; + } + + fn gate(c: *const AttnCase, r: usize, col: usize) f64 { + const v = c.o[r * QW + col] * sig(c.pq[r * PQ + (col / HD) * 2 * HD + HD + col % HD]); + return if (c.round) rb(v) else v; + } + + fn project(c: *const AttnCase, r: usize) void { + c.projectRow(r); + } + + fn rnd(c: *const AttnCase, v: f64) f64 { + return if (c.round) rb(v) else v; + } + + fn projectRow(c: *const AttnCase, r: usize) void { + const x = c.x[r * D ..][0..D]; + for (0..PQ) |i| c.pq[r * PQ + i] = c.rnd(dot(c.at.q.row(i), x)); + for (0..KW) |i| { + c.pk[r * KW + i] = c.rnd(dot(c.at.k.row(i), x)); + c.pv[r * KW + i] = c.rnd(dot(c.at.v.row(i), x)); + } + for (0..NQ) |h| prepHead(c.pq[r * PQ + h * 2 * HD ..][0..HD], c.at.qscale, r, c.at.inv, c.round, c.qkv[r * QKV + h * HD ..][0..HD]); + for (0..NKV) |h| { + prepHead(c.pk[r * KW + h * HD ..][0..HD], c.at.kscale, r, c.at.inv, c.round, c.qkv[r * QKV + QW + h * HD ..][0..HD]); + @memcpy(c.qkv[r * QKV + QW + KW + h * HD ..][0..HD], c.pv[r * KW + h * HD ..][0..HD]); + } + } + + fn attend(c: *const AttnCase, h: usize) void { + for (0..c.rows) |i| c.attendRow(h, i); + } + + fn attendRow(c: *const AttnCase, h: usize, i: usize) void { + const kv = h / (NQ / NKV); + const q = c.qkv[i * QKV + h * HD ..][0..HD]; + var p: [2048]f64 = undefined; + var top: f64 = -std.math.inf(f64); + for (0..i + 1) |j| { + p[j] = dot(q, c.qkv[j * QKV + QW + kv * HD ..][0..HD]) / 16; + top = @max(top, p[j]); + } + var total: f64 = 0; + for (0..i + 1) |j| { + p[j] = @exp(p[j] - top); + total += p[j]; + } + const o = c.o[i * QW + h * HD ..][0..HD]; + @memset(o, 0); + for (0..i + 1) |j| axpy(o, p[j] / total, c.qkv[j * QKV + QW + KW + kv * HD ..][0..HD]); + } +}; + +const AttnRef = struct { + c: *const AttnCase, + g: []const f64, + dg: []f64, + dout: []f64, + dpq: []f64, + dq: []f64, + dkh: []f64, + dvh: []f64, + dk: []f64, + dv: []f64, + dpk: []f64, + dx: []f64, + + fn init(al: std.mem.Allocator, c: *const AttnCase, g: []const f64) !AttnRef { + const R = c.rows; + var a: AttnRef = .{ .c = c, .g = g, .dg = try al.alloc(f64, R * QW), .dout = try al.alloc(f64, R * QW), .dpq = try al.alloc(f64, R * PQ), .dq = try al.alloc(f64, R * QW), .dkh = try al.alloc(f64, NQ * R * HD), .dvh = try al.alloc(f64, NQ * R * HD), .dk = try al.alloc(f64, R * KW), .dv = try al.alloc(f64, R * KW), .dpk = try al.alloc(f64, R * KW), .dx = try al.alloc(f64, R * D) }; + @memset(a.dg, 0); + @memset(a.dkh, 0); + @memset(a.dvh, 0); + @memset(a.dk, 0); + @memset(a.dv, 0); + parallel(R, @as(*const AttnRef, &a), gateRow); + parallel(NQ, @as(*const AttnRef, &a), head); + for (0..NQ) |h| { + const kv = h / (NQ / NKV); + for (0..R) |j| { + axpy(a.dk[j * KW + kv * HD ..][0..HD], 1, a.dkh[(h * R + j) * HD ..][0..HD]); + axpy(a.dv[j * KW + kv * HD ..][0..HD], 1, a.dvh[(h * R + j) * HD ..][0..HD]); + } + } + parallel(R, @as(*const AttnRef, &a), inputRow); + return a; + } + + fn gateRow(a: *const AttnRef, r: usize) void { + const c = a.c; + const dg = a.dg[r * QW ..][0..QW]; + for (0..D) |d| axpy(dg, a.g[r * D + d], c.at.o.row(d)); + for (0..QW) |col| { + const at = r * PQ + (col / HD) * 2 * HD + HD + col % HD; + const sg = sig(c.pq[at]); + a.dout[r * QW + col] = dg[col] * sg; + a.dpq[at] = dg[col] * c.gated[r * QW + col] * (1 - sg); + } + } + + fn head(a: *const AttnRef, h: usize) void { + const c = a.c; + const R = c.rows; + const kv = h / (NQ / NKV); + var p: [2048]f64 = undefined; + var dp: [2048]f64 = undefined; + for (0..R) |i| { + const q = c.qkv[i * QKV + h * HD ..][0..HD]; + const go = a.dout[i * QW + h * HD ..][0..HD]; + var top: f64 = -std.math.inf(f64); + for (0..i + 1) |j| { + p[j] = dot(q, c.qkv[j * QKV + QW + kv * HD ..][0..HD]) / 16; + dp[j] = dot(go, c.qkv[j * QKV + QW + KW + kv * HD ..][0..HD]); + top = @max(top, p[j]); + } + var total: f64 = 0; + for (0..i + 1) |j| { + p[j] = @exp(p[j] - top); + total += p[j]; + } + var mix: f64 = 0; + for (0..i + 1) |j| { + p[j] /= total; + mix += p[j] * dp[j]; + } + const dq = a.dq[i * QW + h * HD ..][0..HD]; + @memset(dq, 0); + for (0..i + 1) |j| { + const ds = p[j] * (dp[j] - mix); + axpy(dq, ds / 16, c.qkv[j * QKV + QW + kv * HD ..][0..HD]); + axpy(a.dkh[(h * R + j) * HD ..][0..HD], ds / 16, q); + axpy(a.dvh[(h * R + j) * HD ..][0..HD], p[j], go); + } + } + } + + fn inputRow(a: *const AttnRef, r: usize) void { + const c = a.c; + for (0..NQ) |h| prepHeadBack(c.pq[r * PQ + h * 2 * HD ..][0..HD], c.at.qscale, r, c.at.inv, a.dq[r * QW + h * HD ..][0..HD], a.dpq[r * PQ + h * 2 * HD ..][0..HD]); + for (0..NKV) |h| prepHeadBack(c.pk[r * KW + h * HD ..][0..HD], c.at.kscale, r, c.at.inv, a.dk[r * KW + h * HD ..][0..HD], a.dpk[r * KW + h * HD ..][0..HD]); + const dx = a.dx[r * D ..][0..D]; + @memset(dx, 0); + for (0..PQ) |i| axpy(dx, a.dpq[r * PQ + i], c.at.q.row(i)); + for (0..KW) |i| { + axpy(dx, a.dpk[r * KW + i], c.at.k.row(i)); + axpy(dx, a.dv[r * KW + i], c.at.v.row(i)); + } + } +}; + +fn attnLoss(c: *AttnCase, dg: []const f64, from: usize) f64 { + c.projectRow(from); + var l: f64 = 0; + for (from..c.rows) |i| { + for (0..NQ) |h| c.attendRow(h, i); + for (0..QW) |col| l += dg[i * QW + col] * c.gate(i, col); + } + return l; +} + +pub fn attnTest(r: *Rig, o: Ops) !void { + const amp = @sqrt(3.0 / @as(f64, D)); + const at: Attn = blk: { + const qs = try r.a.alloc(f32, HD); + const ks = try r.a.alloc(f32, HD); + for (qs, ks) |*a, *b| { + a.* = @floatCast(rb(1 + r.uni(-0.3, 0.3))); + b.* = @floatCast(rb(1 + r.uni(-0.3, 0.3))); + } + const inv = try r.a.alloc(f32, HALF); + for (inv, 0..) |*v, i| v.* = @floatCast(std.math.pow(f64, theta, -@as(f64, @floatFromInt(i)) / HALF)); + break :blk .{ .q = try r.q4(PQ, D, 2 * amp), .k = try r.q4(KW, D, 2 * amp), .v = try r.q4(KW, D, amp), .o = try r.q4(D, QW, @sqrt(3.0 / @as(f64, QW))), .qscale = qs, .kscale = ks, .inv = inv }; + }; + const R = row_counts[row_counts.len - 1]; + const x = try r.f64s(R * D, -1, 1, true); + const g = try r.f64s(R * D, -1, 1, false); + for (g) |*v| v.* = @as(f32, @floatCast(v.*)); + { + var c = try AttnCase.init(r.a, &at, 48, false, x[0 .. 48 * D]); + const ref = try AttnRef.init(r.a, &c, g[0 .. 48 * D]); + const xm = try r.a.dupe(f64, x[0 .. 48 * D]); + c.x = xm; + var num: std.ArrayList(f64) = .empty; + var want: std.ArrayList(f64) = .empty; + const step = 1e-4; + for ([_]usize{ 3, 40 }) |row| for ([_]usize{ 11, 2345, 5118 }) |i| { + const v = xm[row * D + i]; + xm[row * D + i] = v + step; + const lp = attnLoss(&c, ref.dg, row); + xm[row * D + i] = v - step; + const lm = attnLoss(&c, ref.dg, row); + xm[row * D + i] = v; + _ = attnLoss(&c, ref.dg, row); + try num.append(r.a, (lp - lm) / (2 * step)); + try want.append(r.a, ref.dx[row * D + i]); + }; + r.fd("attn dx", num.items, want.items, rms(ref.dx)); + } + const da: to.Attn = .{ .q = try at.q.dev(r), .k = try at.k.dev(r), .v = try at.v.dev(r), .o = try at.o.dev(r), .qscale = try r.dev(f32, at.qscale), .kscale = try r.dev(f32, at.kscale), .inv = try r.dev(f32, at.inv), .heads = NQ, .kv_heads = NKV, .dim = HD, .half = HALF, .eps = @floatCast(eps) }; + for (row_counts) |rows| { + var c = try AttnCase.init(r.a, &at, rows, true, x[0 .. rows * D]); + const kept: to.AttnKept = .{ .pq = try r.dev(u16, try toBf16(r.a, c.pq)), .pk = try r.dev(u16, try toBf16(r.a, c.pk)), .pv = try r.dev(u16, try toBf16(r.a, c.pv)), .gated = try r.dev(u16, try toBf16(r.a, c.gated)), .pos0 = 0 }; + const gd = try r.dev(f32, try toF32(r.a, g[0 .. rows * D])); + const dx = try r.zeros(rows * D * 4); + const t: to.AttnScratch = .{ .qkv = try r.zeros(rows * QKV * 2), .dg = try r.zeros(rows * QW * 4), .dout = try r.zeros(rows * QW * 4), .dpq = try r.zeros(rows * PQ * 4), .dq = try r.zeros(rows * QW * 4), .dk = try r.zeros(rows * KW * 4), .dv = try r.zeros(rows * KW * 4), .dpk = try r.zeros(rows * KW * 4), .probs = try r.zeros(NQ * rows * rows * 4), .dscores = try r.zeros(NQ * rows * rows * 4) }; + try o.attnBack(da, kept, gd, dx, t, rows, false); + // the reference from the GPU's prepared heads (the same bf16 inputs) + const qkv = try r.back(u16, t.qkv, rows * QKV); + var most: f64 = 0; + for (qkv, c.qkv) |got, want| most = @max(most, @abs(bf(got) - want) / @max(1, @abs(want))); + const prep_ok = most <= 1.0 / 32.0; + r.checks += 1; + if (!prep_ok) r.bad += 1; + std.debug.print("RESULT attn {d} rows prepared heads: the largest difference {e:.2} of max(1, |value|){s}\n", .{ rows, most, if (prep_ok) "" else " <- FAIL" }); + for (qkv, c.qkv) |got, *want| want.* = bf(got); + const ref = try AttnRef.init(r.a, &c, g[0 .. rows * D]); + var buf: [96]u8 = undefined; + r.compare(try std.fmt.bufPrint(&buf, "attn {d} rows dpq (q and gate)", .{rows}), try r.back(f32, t.dpq, rows * PQ), ref.dpq, PQ, tol_col, tol_l2); + r.compare(try std.fmt.bufPrint(&buf, "attn {d} rows dpk", .{rows}), try r.back(f32, t.dpk, rows * KW), ref.dpk, KW, tol_col, tol_l2); + r.compare(try std.fmt.bufPrint(&buf, "attn {d} rows dv", .{rows}), try r.back(f32, t.dv, rows * KW), ref.dv, KW, tol_col, tol_l2); + r.compare(try std.fmt.bufPrint(&buf, "attn {d} rows dx", .{rows}), try r.back(f32, dx, rows * D), ref.dx, D, tol_col, tol_l2); + } + r.release(); +} + +// ---- the head and the final norm ------------------------------------------------------------------------------------ + +const V = 32768; + +const HeadCtx = struct { w: *const HQ4, logits: []const u16, targets: []const u32, weights: []const f32, rows: usize, top: []const f64, total: []const f64, acc: [][]f64 }; + +fn headChunk(c: *const HeadCtx, i: usize) void { + const chunk = (V + threads - 1) / threads; + const acc = c.acc[i]; + @memset(acc, 0); + var v = i * chunk; + while (v < @min(V, (i + 1) * chunk)) : (v += 1) { + for (0..c.rows) |r| { + const p = @exp(bf(c.logits[r * V + v]) - c.top[r]) / c.total[r]; + const dl = rb((p - @as(f64, if (c.targets[r] == v) 1 else 0)) * c.weights[r]); + axpy(acc[r * D ..][0..D], dl, c.w.row(v)); + } + } +} + +pub fn headTest(r: *Rig, o: Ops) !void { + const R = row_counts[row_counts.len - 1]; + const head = try r.q4(V, D, @sqrt(3.0 / @as(f64, D))); + const logits = try r.a.alloc(u16, R * V); + for (logits) |*l| l.* = bf16(r.uni(-3, 3)); + const targets = try r.a.alloc(u32, R); + const weights = try r.a.alloc(f32, R); + for (targets, weights, 0..) |*t, *w, i| { + t.* = r.rng.uintLessThan(u32, V); + w.* = if (i % 7 == 3) 0 else @floatCast(1.0 / @as(f64, @floatFromInt(R)) * r.uni(0.5, 1.5)); + logits[i * V + t.*] = bf16(r.uni(2, 6)); + } + const top = try r.a.alloc(f64, R); + const total = try r.a.alloc(f64, R); + for (0..R) |i| { + top[i] = -std.math.inf(f64); + for (logits[i * V ..][0..V]) |l| top[i] = @max(top[i], bf(l)); + total[i] = 0; + for (logits[i * V ..][0..V]) |l| total[i] += @exp(bf(l) - top[i]); + } + const accs = try r.a.alloc([]f64, threads); + for (accs) |*a| a.* = try r.a.alloc(f64, R * D); + parallel(threads, &HeadCtx{ .w = &head, .logits = logits, .targets = targets, .weights = weights, .rows = R, .top = top, .total = total, .acc = accs }, headChunk); + const dlast = try r.a.alloc(f64, R * D); + @memset(dlast, 0); + for (accs) |a| axpy(dlast, 1, a); + // the final norm after it: dh from the head's gradient at the normed rows + const hrows = try r.f64s(R * D, -2, 2, true); + const norm = try r.a.alloc(f64, D); + for (norm) |*v| v.* = rb(1 + r.uni(-0.3, 0.3)); + const dh = try r.a.alloc(f64, R * D); + for (0..R) |i| normBack(hrows[i * D ..][0..D], norm, dlast[i * D ..][0..D], dh[i * D ..][0..D]); + { + // the norm's backward against central differences of g . norm(h) + var num: [6]f64 = undefined; + var want: [6]f64 = undefined; + var k: usize = 0; + for ([_]usize{ 1, 77 }) |row| for ([_]usize{ 0, 2500, 5119 }) |i| { + const hr = try r.a.dupe(f64, hrows[row * D ..][0..D]); + var y: [D]f64 = undefined; + const v = hr[i]; + hr[i] = v + 1e-5; + normRow(hr, norm, false, &y); + const lp = dot(&y, dlast[row * D ..][0..D]); + hr[i] = v - 1e-5; + normRow(hr, norm, false, &y); + const lm = dot(&y, dlast[row * D ..][0..D]); + num[k] = (lp - lm) / 2e-5; + want[k] = dh[row * D + i]; + k += 1; + }; + r.fd("final norm dh", &num, &want, rms(dh)); + } + const dhead = try head.dev(r); + const norm_d = try r.dev(u16, try toBf16(r.a, norm)); + for (row_counts) |rows| { + const ld = try r.dev(u16, logits[0 .. rows * V]); + const td = try r.dev(u32, targets[0..rows]); + const wd = try r.dev(f32, weights[0..rows]); + const stats = try r.zeros(rows * 8); + const dl = try r.zeros(rows * D * 4); + const parts = try r.zeros(to.splitsFor(rows, D, V) * rows * D * 4); + const g = try r.zeros(rows * D * 4); + try o.softmax(ld, td, wd, stats, rows, V); + try o.product(ld, true, V, dhead, dl, D, rows, false, parts); + try o.rmsBack(try r.dev(u16, try toBf16(r.a, hrows[0 .. rows * D])), norm_d, dl, g, rows, D, @floatCast(eps)); + var buf: [96]u8 = undefined; + r.compare(try std.fmt.bufPrint(&buf, "head {d} rows dlast (head back)", .{rows}), try r.back(f32, dl, rows * D), dlast[0 .. rows * D], D, tol_col, tol_l2); + r.compare(try std.fmt.bufPrint(&buf, "head {d} rows dh (final norm)", .{rows}), try r.back(f32, g, rows * D), dh[0 .. rows * D], D, tol_col, tol_l2); + } + r.release(); +} diff --git a/zig/tests/cuda/q27_back_rig.zig b/zig/tests/cuda/q27_back_rig.zig new file mode 100644 index 0000000000..8d1411891b --- /dev/null +++ b/zig/tests/cuda/q27_back_rig.zig @@ -0,0 +1,235 @@ +//! Shared pieces of the 27B's backward checks: bf16 numbers, a host 4-bit matrix, the rig and float64 helpers. +const std = @import("std"); +const cuda = @import("cuda"); +const qwen27 = @import("qwen27"); +const check = @import("check.zig"); +const Gpu = check.Gpu; +const to = qwen27.train_ops; + +pub const D = 5120; +pub const I = 17408; +pub const G = 64; +pub const NP = 16; // pocket neurons +pub const eps: f64 = 1e-6; +pub const threads = 16; +pub const row_counts = [_]usize{ 64, 256 }; + +pub const tol_col = 3e-2; +pub const tol_l2 = 1e-2; +pub const tol_fd = 1e-5; + +pub fn bf16(x: f64) u16 { + const f: f32 = @floatCast(x); + const v: u32 = @bitCast(f); + return @truncate((v + 0x7fff + ((v >> 16) & 1)) >> 16); +} + +pub fn bf(x: u16) f64 { + return @as(f32, @bitCast(@as(u32, x) << 16)); +} + +pub fn rb(x: f64) f64 { + return bf(bf16(x)); +} + +pub fn sig(x: f64) f64 { + return 1 / (1 + @exp(-x)); +} + +pub fn silu(x: f64) f64 { + return x * sig(x); +} + +pub fn siluGrad(x: f64) f64 { + const s = sig(x); + return s * (1 + x * (1 - s)); +} + +pub fn dot(a: []const f64, b: []const f64) f64 { + const Vec = @Vector(8, f64); + var acc: Vec = @splat(0); + var i: usize = 0; + while (i + 8 <= a.len) : (i += 8) acc += @as(Vec, a[i..][0..8].*) * @as(Vec, b[i..][0..8].*); + var s = @reduce(.Add, acc); + while (i < a.len) : (i += 1) s += a[i] * b[i]; + return s; +} + +pub fn axpy(y: []f64, c: f64, x: []const f64) void { + const Vec = @Vector(8, f64); + const cv: Vec = @splat(c); + var i: usize = 0; + while (i + 8 <= y.len) : (i += 8) y[i..][0..8].* = @as(Vec, y[i..][0..8].*) + cv * @as(Vec, x[i..][0..8].*); + while (i < y.len) : (i += 1) y[i] += c * x[i]; +} + +/// A 4-bit [n, k] matrix in MLX's layout on the host, a bf16 scale and bias every G of a row; rows kept dequantized. +pub const HQ4 = struct { + n: usize, + k: usize, + words: []u32, + sc: []u16, + bi: []u16, + vals: []f64, // [n, k] the dequantized values + + pub fn row(m: *const HQ4, i: usize) []const f64 { + return m.vals[i * m.k ..][0..m.k]; + } + + pub fn dev(m: *const HQ4, r: *Rig) !to.Q4 { + return .{ .w = try r.dev(u32, m.words), .s = try r.dev(u16, m.sc), .b = try r.dev(u16, m.bi), .n = m.n, .k = m.k, .group = G }; + } +}; + +pub const Rig = struct { + gpu: Gpu, + a: std.mem.Allocator, + s: cuda.Stream, + rng: std.Random, + bufs: std.ArrayList(cuda.DeviceBuffer) = .empty, + bad: usize = 0, + checks: usize = 0, + + pub fn dev(r: *Rig, comptime T: type, host: []const T) !u64 { + const b = try cuda.DeviceBuffer.fromHost(r.gpu.d, std.mem.sliceAsBytes(host)); + try r.bufs.append(r.gpu.gpa, b); + return b.ptr; + } + + pub fn zeros(r: *Rig, n: usize) !u64 { + const b = try cuda.DeviceBuffer.alloc(r.gpu.d, @max(n, 16)); + try r.bufs.append(r.gpu.gpa, b); + try b.fill8(0, r.s.handle); + return b.ptr; + } + + pub fn back(r: *Rig, comptime T: type, ptr: u64, n: usize) ![]T { + try r.s.synchronize(); + const out = try r.a.alloc(T, n); + const b: cuda.DeviceBuffer = .{ .d = r.gpu.d, .ptr = ptr, .len = n * @sizeOf(T) }; + try b.download(0, std.mem.sliceAsBytes(out)); + return out; + } + + pub fn release(r: *Rig) void { + for (r.bufs.items) |*b| b.free(); + r.bufs.clearRetainingCapacity(); + } + + pub fn uni(r: *Rig, lo: f64, hi: f64) f64 { + return lo + r.rng.float(f64) * (hi - lo); + } + + /// A random 4-bit matrix with values in about [-amp, amp]: codes uniform, scales and biases jittered. + pub fn q4(r: *Rig, n: usize, k: usize, amp: f64) !HQ4 { + const m: HQ4 = .{ .n = n, .k = k, .words = try r.a.alloc(u32, n * k / 8), .sc = try r.a.alloc(u16, n * k / G), .bi = try r.a.alloc(u16, n * k / G), .vals = try r.a.alloc(f64, n * k) }; + r.rng.bytes(std.mem.sliceAsBytes(m.words)); + for (m.sc, m.bi) |*s, *b| { + const sv = 2 * amp / 15 * r.uni(0.6, 1.4); + s.* = bf16(sv); + b.* = bf16(-7.5 * sv * r.uni(0.85, 1.15)); + } + for (0..n * k) |i| { + const q: f64 = @floatFromInt((m.words[i / 8] >> @intCast(4 * (i % 8))) & 0xf); + m.vals[i] = bf(m.sc[i / G]) * q + bf(m.bi[i / G]); + } + return m; + } + + pub fn f64s(r: *Rig, n: usize, lo: f64, hi: f64, round: bool) ![]f64 { + const out = try r.a.alloc(f64, n); + for (out) |*v| v.* = if (round) rb(r.uni(lo, hi)) else r.uni(lo, hi); + return out; + } + + /// `got` against `want` [rows, cols]: the worst column's relative difference and the relative L2 error. + pub fn compare(r: *Rig, name: []const u8, got: []const f32, want: []const f64, cols: usize, tc: f64, tl: f64) void { + const rows = want.len / cols; + var top: f64 = 0; + for (want) |w| top = @max(top, @abs(w)); + var worst: f64 = 0; + var at: usize = 0; + var dd: f64 = 0; + var ww: f64 = 0; + for (0..cols) |c| { + var num: f64 = 0; + var den: f64 = 0; + for (0..rows) |i| { + const w = want[i * cols + c]; + const diff = @as(f64, got[i * cols + c]) - w; + num = if (std.math.isNan(diff)) std.math.inf(f64) else @max(num, @abs(diff)); + den = @max(den, @abs(w)); + dd += diff * diff; + ww += w * w; + } + const e = num / @max(den, 1e-3 * top, 1e-300); + if (e > worst) { + worst = e; + at = c; + } + } + const l2 = @sqrt(dd / @max(ww, 1e-300)); + const ok = worst <= tc and l2 <= tl; + r.checks += 1; + if (!ok) r.bad += 1; + std.debug.print("RESULT {s}: worst column {e:.2} (column {d} of {d}), relative L2 {e:.2}, largest |ref| {e:.2}{s}\n", .{ name, worst, at, cols, l2, top, if (ok) "" else " <- FAIL" }); + } + + /// Central differences against a reference gradient's coordinates. + pub fn fd(r: *Rig, name: []const u8, num: []const f64, ref: []const f64, scale: f64) void { + var worst: f64 = 0; + for (num, ref) |n, g| { + const e = @abs(n - g) / @max(@abs(g), 0.05 * scale, 1e-300); + worst = if (std.math.isNan(e)) std.math.inf(f64) else @max(worst, e); + } + const ok = worst <= tol_fd; + r.checks += 1; + if (!ok) r.bad += 1; + std.debug.print("RESULT fd {s}: float64 reference against central differences at {d} coordinates, worst relative {e:.2}{s}\n", .{ name, num.len, worst, if (ok) "" else " <- FAIL" }); + } +}; + +pub fn rms(xs: []const f64) f64 { + return @sqrt(dot(xs, xs) / @as(f64, @floatFromInt(@max(xs.len, 1)))); +} + +pub fn toF32(a: std.mem.Allocator, xs: []const f64) ![]f32 { + const out = try a.alloc(f32, xs.len); + for (out, xs) |*o, x| o.* = @floatCast(x); + return out; +} + +pub fn toBf16(a: std.mem.Allocator, xs: []const f64) ![]u16 { + const out = try a.alloc(u16, xs.len); + for (out, xs) |*o, x| o.* = bf16(x); + return out; +} + +/// f(ctx, i) for i below n, on `threads` threads. +pub fn parallel(n: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), usize) void) void { + const C = @TypeOf(ctx); + const Run = struct { + fn run(c: C, first: usize, count: usize) void { + var i = first; + while (i < count) : (i += threads) f(c, i); + } + }; + var ts: [threads]?std.Thread = @splat(null); + for (&ts, 0..) |*t, i| t.* = std.Thread.spawn(.{}, Run.run, .{ ctx, i, n }) catch null; + for (ts, 0..) |t, i| if (t) |th| th.join() else Run.run(ctx, i, n); +} + +/// y = h rinv w, the RMS norm (rounded to bf16 when `round`). +pub fn normRow(h: []const f64, w: []const f64, round: bool, y: []f64) void { + const rinv = 1 / @sqrt(dot(h, h) / @as(f64, @floatFromInt(h.len)) + eps); + for (y, h, w) |*o, x, s| o.* = if (round) rb(x * rinv * s) else x * rinv * s; +} + +/// The RMS norm undone: dh = rinv w dy - rinv^3 h (w dy . h) / n. +pub fn normBack(h: []const f64, w: []const f64, dy: []const f64, dh: []f64) void { + const n: f64 = @floatFromInt(h.len); + const rinv = 1 / @sqrt(dot(h, h) / n + eps); + var t: f64 = 0; + for (h, w, dy) |x, s, d| t += s * d * x; + for (dh, h, w, dy) |*o, x, s, d| o.* = rinv * s * d - rinv * rinv * rinv * x * t / n; +} diff --git a/zig/tests/cuda/q27_back_tests.zig b/zig/tests/cuda/q27_back_tests.zig new file mode 100644 index 0000000000..f7abfdb61d --- /dev/null +++ b/zig/tests/cuda/q27_back_tests.zig @@ -0,0 +1,227 @@ +//! The 27B's input-gradient kernels against float64 (q27-mlp-back, q27-attn-back, q27-head-back), 64 and 256 rows. +const std = @import("std"); +const cuda = @import("cuda"); +const qwen27 = @import("qwen27"); +const check = @import("check.zig"); +const rig = @import("q27_back_rig.zig"); +const attn = @import("q27_back_attn.zig"); +const to = qwen27.train_ops; +const Ops = to.Ops; +const Gpu = check.Gpu; +const Rig = rig.Rig; +const HQ4 = rig.HQ4; +const D = rig.D; +const I = rig.I; +const NP = rig.NP; +const eps = rig.eps; +const threads = rig.threads; +const row_counts = rig.row_counts; +const tol_col = rig.tol_col; +const tol_l2 = rig.tol_l2; +const bf16 = rig.bf16; +const bf = rig.bf; +const rb = rig.rb; +const sig = rig.sig; +const silu = rig.silu; +const siluGrad = rig.siluGrad; +const dot = rig.dot; +const axpy = rig.axpy; +const rms = rig.rms; +const toF32 = rig.toF32; +const toBf16 = rig.toBf16; +const parallel = rig.parallel; +const normRow = rig.normRow; +const normBack = rig.normBack; + +// ---- the dense MLP and its pocket ----------------------------------------------------------------------------------- + +const Mlp = struct { + gate: HQ4, // [I, D] + up: HQ4, + down: HQ4, // [D, I] + norm: []f64, // [D] bf16 values + pg: []f64, // pocket gate rows [NP, D] (fp32 values) + pu: []f64, + pd: []f64, +}; + +/// A case's forward: y the normed rows, gate and up the projections, act, out = down act + the pocket's. +const MlpCase = struct { + m: *const Mlp, + rows: usize, + round: bool, + h: []const f64, + y: []f64, + gate: []f64, + up: []f64, + g: []const f64, + dy: []f64, + dh: []f64, + + fn init(al: std.mem.Allocator, m: *const Mlp, rows: usize, round: bool, h: []const f64, g: []const f64) !MlpCase { + var c: MlpCase = .{ .m = m, .rows = rows, .round = round, .h = h, .g = g, .y = try al.alloc(f64, rows * D), .gate = try al.alloc(f64, rows * I), .up = try al.alloc(f64, rows * I), .dy = try al.alloc(f64, rows * D), .dh = try al.alloc(f64, rows * D) }; + parallel(rows, @as(*const MlpCase, &c), forwardRow); + parallel(rows, @as(*const MlpCase, &c), backRow); + return c; + } + + fn forwardRow(c: *const MlpCase, r: usize) void { + const y = c.y[r * D ..][0..D]; + normRow(c.h[r * D ..][0..D], c.m.norm, c.round, y); + for (0..I) |i| { + const a = dot(c.m.gate.row(i), y); + const b = dot(c.m.up.row(i), y); + c.gate[r * I + i] = if (c.round) rb(a) else a; + c.up[r * I + i] = if (c.round) rb(b) else b; + } + } + + /// dy = gate^T dgate + up^T dup + the pocket's, then dh through the norm, from g at this point of the forward. + fn backRow(c: *const MlpCase, r: usize) void { + const g = c.g[r * D ..][0..D]; + const y = c.y[r * D ..][0..D]; + const dy = c.dy[r * D ..][0..D]; + @memset(dy, 0); + var dact: [I]f64 = undefined; + @memset(&dact, 0); + for (0..D) |o| axpy(&dact, g[o], c.m.down.row(o)); + for (0..I) |i| { + const gv = c.gate[r * I + i]; + const uv = c.up[r * I + i]; + axpy(dy, dact[i] * uv * siluGrad(gv), c.m.gate.row(i)); + axpy(dy, dact[i] * silu(gv), c.m.up.row(i)); + } + for (0..NP) |j| { + const zg = dot(c.m.pg[j * D ..][0..D], y); + const zu = dot(c.m.pu[j * D ..][0..D], y); + const e = dot(c.m.pd[j * D ..][0..D], g); + axpy(dy, e * siluGrad(zg) * zu, c.m.pg[j * D ..][0..D]); + axpy(dy, e * silu(zg), c.m.pu[j * D ..][0..D]); + } + normBack(c.h[r * D ..][0..D], c.m.norm, dy, c.dh[r * D ..][0..D]); + } +}; + +/// g . out(row r of h) in float64, the pocket included: the part of the loss row r moves. +fn mlpLoss(m: *const Mlp, h: []const f64, g: []const f64) f64 { + var y: [D]f64 = undefined; + normRow(h, m.norm, false, &y); + var gd: [I]f64 = undefined; + @memset(&gd, 0); + for (0..D) |o| axpy(&gd, g[o], m.down.row(o)); + var l: f64 = 0; + for (0..I) |i| l += gd[i] * silu(dot(m.gate.row(i), &y)) * dot(m.up.row(i), &y); + for (0..NP) |j| l += dot(m.pd[j * D ..][0..D], g) * silu(dot(m.pg[j * D ..][0..D], &y)) * dot(m.pu[j * D ..][0..D], &y); + return l; +} + +fn mlpTest(r: *Rig, o: Ops) !void { + const amp = @sqrt(3.0 / @as(f64, D)); + const m: Mlp = blk: { + const norm = try r.a.alloc(f64, D); + for (norm) |*v| v.* = rb(1 + r.uni(-0.3, 0.3)); + const pg = try r.f64s(NP * D, -2 * amp, 2 * amp, false); + const pu = try r.f64s(NP * D, -2 * amp, 2 * amp, false); + const pd = try r.f64s(NP * D, -0.05, 0.05, false); + for (pg, pu, pd) |*a, *b, *c| { + a.* = @as(f32, @floatCast(a.*)); + b.* = @as(f32, @floatCast(b.*)); + c.* = @as(f32, @floatCast(c.*)); + } + break :blk .{ .gate = try r.q4(I, D, 2 * amp), .up = try r.q4(I, D, 2 * amp), .down = try r.q4(D, I, @sqrt(3.0 / @as(f64, I))), .norm = norm, .pg = pg, .pu = pu, .pd = pd }; + }; + const R = row_counts[row_counts.len - 1]; + const h = try r.f64s(R * D, -2, 2, true); + const g = try r.f64s(R * D, -1, 1, false); + for (g) |*v| v.* = @as(f32, @floatCast(v.*)); + { + // the float64 reference against central differences of the loss in h (rows 2 and 5) + const c = try MlpCase.init(r.a, &m, 8, false, h[0 .. 8 * D], g[0 .. 8 * D]); + var num: std.ArrayList(f64) = .empty; + var want: std.ArrayList(f64) = .empty; + const step = 1e-5; + for ([_]usize{ 2, 5 }) |row| for ([_]usize{ 7, 2049, 5119 }) |i| { + const hr = try r.a.dupe(f64, h[row * D ..][0..D]); + const v = hr[i]; + hr[i] = v + step; + const lp = mlpLoss(&m, hr, g[row * D ..][0..D]); + hr[i] = v - step; + const lm = mlpLoss(&m, hr, g[row * D ..][0..D]); + try num.append(r.a, (lp - lm) / (2 * step)); + try want.append(r.a, c.dh[row * D + i]); + }; + r.fd("mlp dh", num.items, want.items, rms(c.dh)); + } + const dm: to.Mlp = .{ .gate = try m.gate.dev(r), .up = try m.up.dev(r), .down = try m.down.dev(r) }; + const pk: to.Pocket = .{ .gate = try r.dev(f32, try toF32(r.a, m.pg)), .up = try r.dev(f32, try toF32(r.a, m.pu)), .down = try r.dev(f32, try toF32(r.a, m.pd)), .n = NP }; + const norm_d = try r.dev(u16, try toBf16(r.a, m.norm)); + for (row_counts) |rows| { + const c = try MlpCase.init(r.a, &m, rows, true, h[0 .. rows * D], g[0 .. rows * D]); + const kept: to.MlpKept = .{ .y = try r.dev(u16, try toBf16(r.a, c.y)), .gate = try r.dev(u16, try toBf16(r.a, c.gate)), .up = try r.dev(u16, try toBf16(r.a, c.up)) }; + const hd = try r.dev(u16, try toBf16(r.a, h[0 .. rows * D])); + const gd = try r.dev(f32, try toF32(r.a, g[0 .. rows * D])); + const t: to.MlpScratch = .{ .dact = try r.zeros(rows * I * 4), .dgate = try r.zeros(rows * I * 4), .dup = try r.zeros(rows * I * 4) }; + const parts = try r.zeros(@max(to.splitsFor(rows, D, I), to.splitsFor(rows, I, D)) * rows * I * 4); + const dy = try r.zeros(rows * D * 4); + const dh = try r.zeros(rows * D * 4); + try o.mlpBack(dm, kept, pk, gd, dy, t, rows, parts); + try o.rmsBack(hd, norm_d, dy, dh, rows, D, @floatCast(eps)); + var buf: [96]u8 = undefined; + r.compare(try std.fmt.bufPrint(&buf, "mlp {d} rows dy (MLP and pocket)", .{rows}), try r.back(f32, dy, rows * D), c.dy, D, tol_col, tol_l2); + r.compare(try std.fmt.bufPrint(&buf, "mlp {d} rows dh (through the post norm)", .{rows}), try r.back(f32, dh, rows * D), c.dh, D, tol_col, tol_l2); + // the pocket's own rows forward, and its output vectors' gradient at a row each + const zero_out = try r.zeros(rows * D * 2); + try o.pocketRows(pk, kept.y, zero_out, rows, D); + const want_out = try r.a.alloc(f64, rows * D); + for (0..rows) |i| { + const y = c.y[i * D ..][0..D]; + const row = want_out[i * D ..][0..D]; + @memset(row, 0); + for (0..NP) |j| axpy(row, silu(dot(m.pg[j * D ..][0..D], y)) * dot(m.pu[j * D ..][0..D], y), m.pd[j * D ..][0..D]); + } + const got_b = try r.back(u16, zero_out, rows * D); + const got = try r.a.alloc(f32, rows * D); + for (got, got_b) |*x, b| x.* = @floatCast(bf(b)); + r.compare(try std.fmt.bufPrint(&buf, "mlp {d} rows pocket output (bf16)", .{rows}), got, want_out, D, tol_col, tol_l2); + const row_of = try r.a.alloc(i32, NP); + for (row_of, 0..) |*x, j| x.* = if (j == 3) -1 else @intCast((j * 7) % rows); + const grad = try r.zeros(NP * D * 4); + try o.pocketGrad(pk, kept.y, gd, try r.dev(i32, row_of), 0.5, grad, D); + const want_g = try r.a.alloc(f64, NP * D); + @memset(want_g, 0); + for (0..NP) |j| if (row_of[j] >= 0) { + const rr: usize = @intCast(row_of[j]); + const y = c.y[rr * D ..][0..D]; + axpy(want_g[j * D ..][0..D], 0.5 * silu(dot(m.pg[j * D ..][0..D], y)) * dot(m.pu[j * D ..][0..D], y), g[rr * D ..][0..D]); + }; + r.compare(try std.fmt.bufPrint(&buf, "mlp {d} rows pocket output gradient", .{rows}), try r.back(f32, grad, NP * D), want_g, D, 1e-4, 1e-5); + } + r.release(); +} + +// ---- entry ---------------------------------------------------------------------------------------------------------- + +pub const Case = enum { mlp, attn, head, all }; + +pub fn run(gpu: Gpu, case: Case) !void { + var arena: std.heap.ArenaAllocator = .init(gpu.gpa); + defer arena.deinit(); + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var prng = std.Random.DefaultPrng.init(0x5eed_27b0); + var r: Rig = .{ .gpu = gpu, .a = arena.allocator(), .s = s, .rng = prng.random() }; + defer { + r.release(); + r.bufs.deinit(gpu.gpa); + } + var k = try to.Kernels.load(gpu.d); + defer k.deinit(); + const o: Ops = .{ .k = &k, .s = s }; + const t0 = check.now(gpu.io); + if (case == .mlp or case == .all) try mlpTest(&r, o); + if (case == .attn or case == .all) try attn.attnTest(&r, o); + if (case == .head or case == .all) try attn.headTest(&r, o); + const secs = @as(f64, @floatFromInt(check.now(gpu.io) - t0)) / 1e9; + try check.expect(r.bad == 0, "q27-back {t}: {d} of {d} checks outside tolerance", .{ case, r.bad, r.checks }); + check.pass("q27-back {t}: {d} checks within tolerance ({d:.1} s with the float64 references)", .{ case, r.checks, secs }); +} diff --git a/zig/tests/cuda/q27_gemm_tests.zig b/zig/tests/cuda/q27_gemm_tests.zig new file mode 100644 index 0000000000..2d4d95929e --- /dev/null +++ b/zig/tests/cuda/q27_gemm_tests.zig @@ -0,0 +1,143 @@ +//! q27-gemm: the wide 4-bit products (tf_q27_gemm_q4w) against the 64x64 ones, byte for byte. +const std = @import("std"); +const cuda = @import("cuda"); +const qwen27 = @import("qwen27"); +const check = @import("check.zig"); +const rig = @import("q27_back_rig.zig"); +const to = qwen27.train_ops; +const Ops = to.Ops; +const Gpu = check.Gpu; +const Rig = rig.Rig; + +const Shape = struct { n_out: usize, k_in: usize }; // the forward linear's [out, in]: the product is [m, out] -> [m, in] + +const shapes = [_]Shape{ + .{ .n_out = 17408, .k_in = 5120 }, // gate, up + .{ .n_out = 5120, .k_in = 17408 }, // down + .{ .n_out = 12288, .k_in = 5120 }, // attention q (q and gate) + .{ .n_out = 1024, .k_in = 5120 }, // k, v + .{ .n_out = 5120, .k_in = 6144 }, // o, DeltaNet's out +}; +const row_counts = [_]usize{ 1, 61, 130, 984 }; + +fn product(r: *Rig, o: Ops, wide: bool, a: u64, bf: bool, lda: usize, w: to.Q4, c: u64, m: usize, acc: bool, parts: u64) ![]u32 { + @constCast(o.k).wide = wide; + try o.product(a, bf, lda, w, c, w.k, m, acc, parts); + return r.back(u32, c, m * w.k); +} + +pub fn run(gpu: Gpu) !void { + var arena: std.heap.ArenaAllocator = .init(gpu.gpa); + defer arena.deinit(); + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var prng = std.Random.DefaultPrng.init(0x9e3_27b); + var r: Rig = .{ .gpu = gpu, .a = arena.allocator(), .s = s, .rng = prng.random() }; + defer { + r.release(); + r.bufs.deinit(gpu.gpa); + } + var k = try to.Kernels.load(gpu.d); + defer k.deinit(); + const o: Ops = .{ .k = &k, .s = s }; + var cases: usize = 0; + for (shapes) |sh| { + const hq = try r.q4(sh.n_out, sh.k_in, 0.05); + const w = try hq.dev(&r); + const maxm = row_counts[row_counts.len - 1]; + const a32 = try r.a.alloc(f32, maxm * sh.n_out); + for (a32) |*x| x.* = @floatCast(r.uni(-1, 1) * @exp(r.uni(-6, 2))); + const a16 = try r.a.alloc(u16, maxm * sh.n_out); + for (a16, a32) |*y, x| y.* = rig.bf16(x); + const da32 = try r.dev(f32, a32); + const da16 = try r.dev(u16, a16); + const init = try r.a.alloc(f32, maxm * sh.k_in); + for (init) |*x| x.* = @floatCast(r.uni(-1, 1)); + const c = try r.dev(f32, init); + const parts = try r.zeros(64 * maxm * sh.k_in * 4); + for (row_counts) |m| for ([_]bool{ false, true }) |bf| for ([_]bool{ false, true }) |acc| for ([_]bool{ false, true }) |split| { + var got: [2][]u32 = undefined; + for ([_]bool{ false, true }, 0..) |wide, i| { + const bytes = std.mem.sliceAsBytes(init[0 .. m * sh.k_in]); + try (cuda.DeviceBuffer{ .d = gpu.d, .ptr = c, .len = bytes.len }).upload(0, bytes); + got[i] = try product(&r, o, wide, if (bf) da16 else da32, bf, sh.n_out, w, c, m, acc, if (split) parts else 0); + } + try check.sameBytes("q27-gemm", std.mem.sliceAsBytes(got[1]), std.mem.sliceAsBytes(got[0])); + cases += 1; + }; + // a row list: every third row of 984, against the same rows of the whole product + { + const m = maxm; + var list: std.ArrayList(i32) = .empty; + var i: usize = 0; + while (i < m) : (i += 3) try list.append(r.a, @intCast(i)); + const rows = try r.dev(i32, list.items); + const zero = try r.a.alloc(f32, m * sh.k_in); + @memset(zero, 0); + const bytes = std.mem.sliceAsBytes(zero); + const cb: cuda.DeviceBuffer = .{ .d = gpu.d, .ptr = c, .len = bytes.len }; + try cb.upload(0, bytes); + k.wide = true; + try o.productRows(da32, sh.n_out, w, c, sh.k_in, rows, list.items.len, false); + const part = try r.back(u32, c, m * sh.k_in); + try cb.upload(0, bytes); + try o.product(da32, false, sh.n_out, w, c, sh.k_in, m, false, 0); + const whole = try r.back(u32, c, m * sh.k_in); + for (0..m) |row| { + const got = part[row * sh.k_in ..][0..sh.k_in]; + if (row % 3 == 0) { + try check.sameBytes("q27-gemm rows", std.mem.sliceAsBytes(got), std.mem.sliceAsBytes(whole[row * sh.k_in ..][0..sh.k_in])); + } else for (got) |x| try check.expect(x == 0, "q27-gemm rows: row {d} not in the list was written", .{row}); + } + cases += 1; + } + // times at 984 rows, fp32 A, no split + var times: [2]f64 = undefined; + for ([_]bool{ false, true }, 0..) |wide, i| { + k.wide = wide; + try o.product(da32, false, sh.n_out, w, c, sh.k_in, maxm, false, 0); + try s.synchronize(); + const t0 = check.now(gpu.io); + for (0..10) |_| try o.product(da32, false, sh.n_out, w, c, sh.k_in, maxm, false, 0); + try s.synchronize(); + times[i] = @as(f64, @floatFromInt(check.now(gpu.io) - t0)) / 1e10; + } + const flops = 2.0 * @as(f64, @floatFromInt(maxm * sh.n_out * sh.k_in)); + std.debug.print("RESULT q27-gemm [{d}, {d}] x 4-bit [{d}, {d}]: 64x64 {d:.2} ms ({d:.1} TFLOPS), wide {d:.2} ms ({d:.1} TFLOPS)\n", .{ maxm, sh.n_out, sh.n_out, sh.k_in, times[0] * 1e3, flops / times[0] / 1e12, times[1] * 1e3, flops / times[1] / 1e12 }); + r.release(); + } + // the DeltaNet backward's projections: gdn_train's narrow, dequantization and GEMM against the wide product + const gt = cuda.gdn_train; + var gk = try gt.Kernels.load(gpu.d); + defer gk.deinit(); + const go: gt.Ops = .{ .k = &gk, .s = s }; + for ([_]Shape{ .{ .n_out = 16480, .k_in = 5120 }, .{ .n_out = 5120, .k_in = 6144 } }) |sh| { + const hq = try r.q4(sh.n_out, sh.k_in, 0.05); + const w = try hq.dev(&r); + const maxm = row_counts[row_counts.len - 1]; + const a32 = try r.a.alloc(f32, maxm * sh.n_out); + for (a32) |*x| x.* = @floatCast(r.uni(-1, 1) * @exp(r.uni(-6, 2))); + const da32 = try r.dev(f32, a32); + const init = try r.a.alloc(f32, maxm * sh.k_in); + for (init) |*x| x.* = @floatCast(r.uni(-1, 1)); + const c = try r.dev(f32, init); + var sc: gt.Scratch = undefined; + sc.xb = try r.zeros(maxm * @max(sh.n_out, sh.k_in) * 2); + sc.wt = try r.zeros(sh.n_out * sh.k_in * 2); + const bytes = std.mem.sliceAsBytes(init); + const cb: cuda.DeviceBuffer = .{ .d = gpu.d, .ptr = c, .len = bytes.len }; + for (row_counts) |m| for ([_]bool{ false, true }) |acc| { + try cb.upload(0, bytes); + try go.product(da32, .{ .w = w.w, .s = w.s, .b = w.b, .n = w.n, .k = w.k, .group = w.group }, c, m, sc, acc); + const want = try r.back(u32, c, m * sh.k_in); + try cb.upload(0, bytes); + k.wide = true; + try o.product(da32, false, sh.n_out, w, c, sh.k_in, m, acc, 0); + const got = try r.back(u32, c, m * sh.k_in); + try check.sameBytes("q27-gemm DeltaNet projection", std.mem.sliceAsBytes(got), std.mem.sliceAsBytes(want)); + cases += 1; + }; + r.release(); + } + check.pass("q27-gemm: {d} cases byte for byte (wide tiles against 64x64 and against the DeltaNet's dequantized GEMM, gathered rows against whole)", .{cases}); +}