EXLR8: load owned profiles, qheal side data and dense width or split selections

This commit is contained in:
ashhart
2026-12-06 12:29:13 +00:00
parent 7142db5f21
commit 8f2d272d55
12 changed files with 471 additions and 16 deletions
+28 -15
View File
@@ -81,22 +81,30 @@ pub fn parts(f: Format) []const []const u8 {
};
}
pub const files = @import("exlr8_dense_files.zig");
pub const decode = @import("exlr8_dense_decode.zig").decode;
pub const Matrix = struct {
record: Record,
data: [3]st.Tensor,
checksum: ?st.Tensor,
book: codec.Trellis.Book = .mcg,
base_verified: bool = false,
/// M.record and its data tensors, every shape checked against the record.
pub fn get(f: *const st.File, name: []const u8) !Matrix {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
return fromView(try meta.View.parse(arena.allocator(), f.map.memory), arena.allocator(), name);
const view = try meta.View.parse(arena.allocator(), f.map.memory);
if (view.meta.contains("rows")) return (try files.Split.fromView(view, arena.allocator(), name)).matrix;
return fromView(view, arena.allocator(), name);
}
pub fn fromView(view: meta.View, arena: std.mem.Allocator, name: []const u8) !Matrix {
var buf: [512]u8 = undefined;
const rec = try descriptions.parse(view, arena, name, view.get(try std.fmt.bufPrint(&buf, "{s}.record", .{name})) orelse return error.MissingExlr8Tensor);
return fromRecord(view, arena, name, rec);
}
pub fn fromRecord(view: meta.View, arena: std.mem.Allocator, name: []const u8, rec: Record) !Matrix {
var buf: [512]u8 = undefined;
var m: Matrix = .{ .record = rec, .data = undefined, .checksum = view.get(try std.fmt.bufPrint(&buf, "{s}.checksum", .{name})) };
for (parts(rec.format), 0..) |part, i| {
const full = try std.fmt.bufPrint(&buf, "{s}.{s}", .{ name, part });
@@ -227,6 +235,7 @@ pub const Matrix = struct {
/// Every stored block checksum against xxhash64 of the bytes the format names; false on the first mismatch.
pub fn verify(m: Matrix) !bool {
if (m.base_verified) return true;
const c = m.checksum orelse return error.NoExlr8Checksums;
const r = m.record;
for (0..r.blocks()) |b| {
@@ -277,21 +286,25 @@ fn rowBytes(t: st.Tensor, row: usize, n: usize) []const u8 {
pub fn plainNames(gpa: std.mem.Allocator, f: *const st.File) ![][]const u8 {
var out: std.ArrayList([]const u8) = .empty;
errdefer out.deinit(gpa);
next: for (f.names.keys()) |k| {
if (std.mem.startsWith(u8, k, "__pad.")) continue;
const dot = std.mem.lastIndexOfScalar(u8, k, '.') orelse {
try out.append(gpa, k);
continue;
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit();
const allocator = arena.allocator();
const view = try meta.View.parse(allocator, f.map.memory);
var excluded: std.StringHashMapUnmanaged(void) = .empty;
var buf: [512]u8 = undefined;
for (f.names.keys()) |key| if (std.mem.endsWith(u8, key, ".record")) {
const base = key[0 .. key.len - 7];
const matrix = if (view.meta.contains("rows")) (try files.Split.fromView(view, allocator, base)).matrix else try Matrix.fromView(view, allocator, base);
try excluded.put(allocator, key, {});
try excluded.put(allocator, try allocator.dupe(u8, try std.fmt.bufPrint(&buf, "{s}.checksum", .{base})), {});
for (parts(matrix.record.format), 0..) |_, i| for (f.names.keys()) |name| {
const tensor = f.get(name).?;
if (tensor.bytes.ptr == matrix.data[i].bytes.ptr and tensor.bytes.len == matrix.data[i].bytes.len)
try excluded.put(allocator, name, {});
};
var buf: [256]u8 = undefined;
const rec = f.get(std.fmt.bufPrint(&buf, "{s}.record", .{k[0..dot]}) catch return error.BadExlr8Name);
if (rec) |r| {
const fmt = (Record.parse(r) catch return error.BadExlr8Record).format;
const suffix = k[dot + 1 ..];
if (std.mem.eql(u8, suffix, "record") or std.mem.eql(u8, suffix, "checksum")) continue :next;
for (parts(fmt)) |p| if (std.mem.eql(u8, suffix, p)) continue :next;
}
try out.append(gpa, k);
};
for (f.names.keys()) |key| {
if (!std.mem.startsWith(u8, key, "__pad.") and !excluded.contains(key)) try out.append(gpa, key);
}
return out.toOwnedSlice(gpa);
}
+58
View File
@@ -0,0 +1,58 @@
//! Width-selected dense matrices and row ranges of large split matrices retain the full record shape.
const std = @import("std");
const d = @import("exlr8_dense.zig");
const meta = @import("exlr8_metadata.zig");
const profiles = @import("exlr8_profiles.zig");
pub fn selected(view: meta.View, arena: std.mem.Allocator, name: []const u8, document: profiles.Document, layer: usize) !d.Matrix {
var buf: [512]u8 = undefined;
if (view.get(try std.fmt.bufPrint(&buf, "{s}.record", .{name})) != null) {
if (document.denseWidth(layer, name)) |_| return error.UnexpectedExlr8DenseWidth else |err| {
if (err != error.MissingExlr8DenseWidth and err != error.MissingExlr8Metadata) return err;
}
return d.Matrix.fromView(view, arena, name);
}
const width = try document.denseWidth(layer, name);
var width_name: [16]u8 = undefined;
const target = try std.fmt.allocPrint(arena, "{s}.{s}", .{ name, try (meta.Store{ .trellis = width }).name(&width_name) });
var shape: ?d.Record = null;
var found = false;
for (view.names.keys()) |key| {
if (!std.mem.startsWith(u8, key, name) or key.len <= name.len + 2 or key[name.len] != '.' or
!std.mem.endsWith(u8, key, ".record")) continue;
const base = key[0 .. key.len - 7];
const suffix = base[name.len + 1 ..];
const store = meta.Store.named(suffix) catch continue;
if (store != .trellis) return error.BadExlr8DenseWidth;
const matrix = try d.Matrix.fromView(view, arena, base);
if (matrix.record.format != .trellis or matrix.record.halfWidth() != store.trellis) return error.BadExlr8DenseWidth;
if (shape) |r| {
if (r.in != matrix.record.in or r.out != matrix.record.out or r.side != matrix.record.side or
r.channels != matrix.record.channels) return error.Exlr8DenseWidthDisagreement;
} else shape = matrix.record;
if (std.mem.eql(u8, base, target)) found = true;
}
if (!found) return error.Exlr8DenseWidthNotStored;
return d.Matrix.fromView(view, arena, target);
}
pub const Split = struct {
full: d.Record,
first: usize,
end: usize,
parts: usize,
matrix: d.Matrix,
pub fn fromView(view: meta.View, arena: std.mem.Allocator, name: []const u8) !Split {
var buf: [512]u8 = undefined;
const tensor = view.get(try std.fmt.bufPrint(&buf, "{s}.record", .{name})) orelse return error.MissingExlr8Tensor;
const full = try @import("exlr8_descriptions.zig").parse(view, arena, name, tensor);
var range = std.mem.splitScalar(u8, try meta.string(view.meta.get("rows")), '-');
const first = std.fmt.parseInt(usize, range.next() orelse return error.BadExlr8Split, 10) catch return error.BadExlr8Split;
const end = std.fmt.parseInt(usize, range.next() orelse return error.BadExlr8Split, 10) catch return error.BadExlr8Split;
const parts = std.fmt.parseInt(usize, try meta.string(view.meta.get("parts")), 10) catch return error.BadExlr8Split;
if (range.next() != null or first % 128 != 0 or first >= end or end > full.out or parts == 0) return error.BadExlr8Split;
var partial = full;
partial.out = end - first;
if (full.side == .input and (full.format == .trellis or full.format == .int4 or full.format == .int8 or full.format == .fp8_b32))
return error.Exlr8SplitNeedsRowMajorData;
return .{ .full = full, .first = first, .end = end, .parts = parts, .matrix = try d.Matrix.fromRecord(view, arena, name, partial) };
}
};
+34
View File
@@ -83,3 +83,37 @@ fn descriptions() !void {
try view.meta.put(gpa, "matrices", .{ .string = "{}" });
try std.testing.expectError(error.MissingExlr8Description, d.Matrix.fromView(view, gpa, "table"));
}
test "EXLR8 dense files: multi-width selection binds shape and split records preserve row ranges" {
if (comptime @hasDecl(d, "files")) try files() else return error.MissingExlr8DenseWidthSelection;
}
fn files() !void {
var arena = std.heap.ArenaAllocator.init(a);
defer arena.deinit();
const gpa = arena.allocator();
const rec = try f.record(gpa, .{ 6, 300, 128, 0, 0, 0, 0, 0 });
const data: [128 * 128]u16 = @splat(0x3f80);
const sum: [1]u64 = .{xxh.hash(0, std.mem.sliceAsBytes(&data))};
const view = try f.view(gpa, .{ .format = "exlr8-v4", .rows = "128-256", .parts = "3" }, &.{
.{ .name = "table.record", .dtype = "I64", .shape = &.{8}, .bytes = rec },
.{ .name = "table.bf16", .dtype = "BF16", .shape = &.{ 128, 128 }, .bytes = std.mem.sliceAsBytes(&data) },
.{ .name = "table.checksum", .dtype = "U64", .shape = &.{1}, .bytes = std.mem.sliceAsBytes(&sum) },
});
const split = try d.files.Split.fromView(view, gpa, "table");
try std.testing.expectEqual(@as(usize, 300), split.full.out);
try std.testing.expectEqual(@as(usize, 128), split.first);
try std.testing.expect(try split.matrix.verify());
const scales: [128]f16 = @splat(1);
var items: std.ArrayList(f.Item) = .empty;
for ([_]u8{ 2, 3 }) |k| {
const r = try f.record(gpa, .{ 1, 128, 128, k, 1, 128, 0, 0 });
const bytes = try gpa.alloc(u8, 2048 * @as(usize, k));
@memset(bytes, 0);
for ([_][]const u8{ "record", "trellis", "suh", "svh" }, 0..) |suffix, index| {
try items.append(gpa, .{ .name = try std.fmt.allocPrint(gpa, "m.k{d}.{s}", .{ k, suffix }), .dtype = if (index == 0) "I64" else if (index == 1) "U8" else "F16", .shape = if (index == 0) &.{8} else if (index == 1) try gpa.dupe(usize, &.{ 1, bytes.len }) else &.{128}, .bytes = if (index == 0) r else if (index == 1) bytes else std.mem.sliceAsBytes(&scales) });
}
}
const widths = try f.view(gpa, .{ .format = "exlr8-v2" }, items.items);
const document = try @import("exlr8_manifest.zig").Document.parse(gpa, "{\"format\":\"exlr8-v2-manifest\",\"name\":\"bit\",\"layers\":{},\"dense\":{\"0\":{\"m\":3}}}");
try std.testing.expectEqual(@as(u8, 3), (try d.files.selected(widths, gpa, "m", document, 0)).record.k);
try std.testing.expectError(error.MissingExlr8DenseWidth, d.files.selected(widths, gpa, "m", document, 1));
}
+3
View File
@@ -43,6 +43,7 @@ pub const Half = struct {
/// gate/up: signs.in; down: signs.out.
signs: []const i8,
checksum: u64,
base_verified: bool = false,
pub fn rows(h: Half) usize {
return if (h.proj == .down) 128 else h.dims;
@@ -60,6 +61,7 @@ pub const Half = struct {
/// xxhash64 seed 0 of the trellis bytes, the 128 channel values, then the 48 block scales.
pub fn verify(h: Half) bool {
if (h.base_verified) return true;
var x = xxh.Hasher.init(0);
x.update(h.trellis);
x.update(std.mem.sliceAsBytes(h.chan));
@@ -111,6 +113,7 @@ pub fn widthPath(gpa: std.mem.Allocator, root: []const u8, number: u16, k: u8) !
return std.fmt.allocPrint(gpa, "{s}/experts/exlr8-layer-{d:0>3}.k{d}.safetensors", .{ root, number, k });
}
pub const decodeUnit = @import("exlr8_unit_decode.zig").decode;
pub const Layer = @import("exlr8_layer.zig").Layer;
pub const Unit = @import("exlr8_layer.zig").Unit;
+22
View File
@@ -34,6 +34,13 @@ pub const Layer = struct {
l.files[slot] = st.File.open(gpa, io, path) catch |e| if (e == error.FileNotFound) null else return e;
if (l.files[slot]) |file| {
const v = try meta.View.parse(l.arena.allocator(), file.map.memory);
if (v.meta.get("layer")) |value| {
if ((std.fmt.parseInt(u16, try meta.string(value), 10) catch return error.BadExlr8Layer) != number) return error.BadExlr8Layer;
}
if (store == .trellis) if (v.meta.get("k")) |value| {
if (try meta.width(.{ .float = std.fmt.parseFloat(f64, try meta.string(value)) catch return error.BadExlr8Widths }) != store.trellis)
return error.BadExlr8Widths;
};
l.views[slot] = v;
for (0..2) |group| {
if (!(if (group == 0) l.widths[slot] else l.shared_widths[slot])) continue;
@@ -148,6 +155,20 @@ pub const Layer = struct {
}
return en;
}
/// Resolve the profile, verify immutable bytes, then substitute eligible healed side vectors.
pub fn selected(l: *const Layer, document: @import("exlr8_profiles.zig").Document, expert: usize, proj: Proj, h: usize) !Unit {
const store = try document.selected(l.number, if (expert == l.shape.experts) null else expert, switch (proj) {
.gate => .gate,
.up => .up,
.down => .down,
}, h);
var result = try l.unit(expert, proj, h, store);
if (document.payload) |payload| if (result == .trellis) {
const overlay = try @import("exlr8_qheal.zig").Overlay.init(payload);
result.trellis = try overlay.half(l.view, l.number, expert, h, store, result.trellis);
};
return result;
}
pub fn half(l: *const Layer, expert: usize, proj: Proj, h: usize, k: u8) !ex.Half {
if (k == 0 or k > 6) return error.UnsupportedExlr8Width;
return (try l.unit(expert, proj, h, .{ .trellis = 2 * k })).trellis;
@@ -221,6 +242,7 @@ pub fn inferGeometry(v: meta.View) !meta.Geometry {
const intermediate = try std.math.mul(usize, entry.shape[2], 128);
if (v.meta.contains("moe_intermediate_size") and intermediate != g.intermediate)
return error.BadExlr8Geometry;
if (v.meta.contains("n_routed_experts") and g.experts != entry.shape[0]) return error.BadExlr8Geometry;
g.experts = entry.shape[0];
g.intermediate = intermediate;
break;
+2
View File
@@ -26,6 +26,8 @@ fn qwen() !void {
const entry = try layer.entry(e, .gate, u, 4);
try std.testing.expectEqual(@as(usize, 131072), entry.len);
};
const document = try @import("exlr8_manifest.zig").Document.parse(arena.allocator(), "{\"format\":\"exlr8-v2-manifest\",\"name\":\"k4\",\"layers\":{\"0\":{\"gate\":4,\"up\":4,\"down\":4}}}");
try std.testing.expectEqual(book, (try layer.selected(document, 255, .down, 3)).trellis.book);
for ([_]ex.Proj{ .gate, .up, .down }) |p| {
const half = try layer.half(0, p, 0, 4);
try std.testing.expect(half.verify());
+2
View File
@@ -2,6 +2,8 @@
const std = @import("std");
const Io = std.Io;
pub const File = @import("exlr8_profile_file.zig").File;
pub const Overlay = @import("exlr8_qheal.zig").Overlay;
pub const Document = @import("exlr8_profiles.zig").Document;
pub const experts = 256;
+66
View File
@@ -0,0 +1,66 @@
//! One unambiguous profile file, with owned JSON or mapped safetensors lifetime and validated qheal targets.
const std = @import("std");
const Io = std.Io;
const meta = @import("exlr8_metadata.zig");
const st = @import("safetensors.zig");
const profiles = @import("exlr8_profiles.zig");
const qheal = @import("exlr8_qheal.zig");
pub const File = struct {
arena: std.heap.ArenaAllocator,
mapping: ?st.File = null,
document: profiles.Document,
pub fn open(gpa: std.mem.Allocator, io: Io, root: []const u8, name: []const u8) !File {
if (name.len == 0) return error.BadExlr8ProfileName;
for (name) |c| if (!std.ascii.isAlphanumeric(c) and c != '-' and c != '_') return error.BadExlr8ProfileName;
var arena = std.heap.ArenaAllocator.init(gpa);
errdefer arena.deinit();
const a = arena.allocator();
const json = try std.fmt.allocPrint(a, "{s}/manifests/exlr8-manifest-{s}.json", .{ root, name });
const tensor = try std.fmt.allocPrint(a, "{s}/manifests/exlr8-manifest-{s}.safetensors", .{ root, name });
const has_json = try exists(io, json);
const has_tensor = try exists(io, tensor);
if (has_json and has_tensor) return error.AmbiguousExlr8Manifest;
if (!has_json and !has_tensor) return error.FileNotFound;
var mapping: ?st.File = null;
errdefer if (mapping) |*m| m.close(io);
const document = if (has_json) try profiles.Document.parse(a, try Io.Dir.cwd().readFileAlloc(io, json, a, .limited(64 << 20))) else blk: {
mapping = try st.File.open(gpa, io, tensor);
break :blk try profiles.Document.fromView(a, try meta.View.parse(a, mapping.?.map.memory));
};
if (!std.mem.eql(u8, document.name, name)) return error.Exlr8ManifestIdentity;
if (document.payload) |payload| {
const overlay = try qheal.Overlay.init(payload);
var seen: std.StringHashMapUnmanaged(void) = .empty;
for (payload.names.keys()) |key| {
const target = try qheal.address(key);
if (target.slice or seen.contains(target.namespace)) continue;
try seen.put(a, target.namespace, {});
const path = try targetPath(a, root, target.namespace);
var base = try st.File.open(gpa, io, path);
defer base.close(io);
try overlay.validate(try meta.View.parse(a, base.map.memory), target.namespace);
}
}
return .{ .arena = arena, .mapping = mapping, .document = document };
}
pub fn deinit(f: *File, io: Io) void {
if (f.mapping) |*m| m.close(io);
f.arena.deinit();
f.* = undefined;
}
};
fn exists(io: Io, path: []const u8) !bool {
var file = Io.Dir.cwd().openFile(io, path, .{}) catch |e| if (e == error.FileNotFound) return false else return e;
file.close(io);
return true;
}
fn targetPath(a: std.mem.Allocator, root: []const u8, namespace: []const u8) ![]const u8 {
if (std.mem.eql(u8, namespace, "vocab")) return std.fmt.allocPrint(a, "{s}/dense/exlr8-vocab.safetensors", .{root});
if (std.mem.startsWith(u8, namespace, "extra.")) return std.fmt.allocPrint(a, "{s}/dense/exlr8-extra-{s}.safetensors", .{ root, namespace[6..] });
const dot = std.mem.indexOfScalar(u8, namespace, '.').?;
const layer = namespace[dot + 2 ..];
return if (std.mem.startsWith(u8, namespace, "experts."))
std.fmt.allocPrint(a, "{s}/experts/exlr8-layer-{s}.index.safetensors", .{ root, layer })
else
std.fmt.allocPrint(a, "{s}/dense/exlr8-dense-{s}.safetensors", .{ root, layer });
}
+2 -1
View File
@@ -45,6 +45,7 @@ pub const Document = struct {
if (view.meta.get("set_id")) |set| if (d.root.get("set_id")) |wanted| {
if (!std.mem.eql(u8, try meta.string(set), try meta.string(wanted))) return error.Exlr8ManifestIdentity;
};
_ = try @import("exlr8_qheal.zig").Overlay.init(view);
d.payload = view;
return d;
}
@@ -64,7 +65,7 @@ pub const Document = struct {
pub fn denseWidth(d: Document, layer: usize, name: []const u8) !u8 {
var buf: [32]u8 = undefined;
const dense = d.dense orelse return error.MissingExlr8DenseWidth;
const widths = try meta.object(dense.get(try std.fmt.bufPrint(&buf, "{d}", .{layer})));
const widths = try meta.object(dense.get(try std.fmt.bufPrint(&buf, "{d}", .{layer})) orelse return error.MissingExlr8DenseWidth);
return meta.width(widths.get(name) orelse return error.MissingExlr8DenseWidth);
}
fn at(value: Value, unit: usize) !meta.Store {
+129
View File
@@ -0,0 +1,129 @@
//! Qheal substitutes only eligible finite side data, after the original stored bytes pass their checksums.
const std = @import("std");
const meta = @import("exlr8_metadata.zig");
const st = @import("safetensors.zig");
const dense = @import("exlr8_dense.zig");
const ex = @import("exlr8_experts.zig");
pub const Overlay = struct {
view: meta.View,
pub fn init(view: meta.View) !Overlay {
for (view.names.keys()) |name| {
const target = try address(name);
if (!target.slice and !eligible(target.name, target.expert)) return error.IneligibleExlr8Overlay;
}
return .{ .view = view };
}
pub fn validate(o: Overlay, base: meta.View, namespace: []const u8) !void {
for (o.view.names.keys()) |name| {
const target = try address(name);
if (target.slice or !std.mem.eql(u8, namespace, target.namespace)) continue;
_ = try o.replace(base, namespace, target.name);
}
}
pub fn replace(o: Overlay, base: meta.View, namespace: []const u8, name: []const u8) !st.Tensor {
const original = base.get(name) orelse return error.Exlr8OverlayTargetMissing;
var buf: [1024]u8 = undefined;
const full = try std.fmt.bufPrint(&buf, "{s}.{s}", .{ namespace, name });
const replacement = o.view.get(full) orelse return original;
const target = try address(full);
if (target.slice or !eligible(name, target.expert)) return error.IneligibleExlr8Overlay;
if (original.dtype != replacement.dtype or original.rank != replacement.rank or
!std.mem.eql(usize, &original.shape, &replacement.shape)) return error.BadExlr8OverlayShape;
if (!target.expert and original.rank > 1) {
const dot = std.mem.lastIndexOfScalar(u8, name, '.') orelse return error.IneligibleExlr8Overlay;
const suffix = name[dot + 1 ..];
for ([_][]const u8{ "suh", "svh", "s4", "s8", "scale", "e8m0" }) |allowed| {
if (std.mem.eql(u8, suffix, allowed)) break;
} else return error.IneligibleExlr8Overlay;
}
try finite(replacement);
return replacement;
}
pub fn matrix(o: Overlay, base: meta.View, namespace: []const u8, m: dense.Matrix) !dense.Matrix {
if (!try m.verify()) return error.Exlr8ChecksumMismatch;
try o.validate(base, namespace);
var healed = m;
for (dense.parts(m.record.format), 0..) |_, i| {
for (base.names.keys()) |name| {
const original = base.get(name).?;
if (original.bytes.ptr == m.data[i].bytes.ptr and original.bytes.len == m.data[i].bytes.len) {
healed.data[i] = try o.replace(base, namespace, name);
break;
}
} else return error.Exlr8OverlayTargetMissing;
}
healed.base_verified = true;
try healed.check();
return healed;
}
pub fn half(o: Overlay, base: meta.View, layer: usize, expert: usize, unit: usize, store: meta.Store, h: ex.Half) !ex.Half {
if (!h.verify()) return error.Exlr8ChecksumMismatch;
var namespace_buf: [32]u8 = undefined;
const namespace = try std.fmt.bufPrint(&namespace_buf, "experts.L{d:0>3}", .{layer});
try o.validate(base, namespace);
const geometry = try @import("exlr8_layer.zig").inferGeometry(base);
const shared = expert == geometry.experts;
const e = if (shared) 0 else expert;
var key: [16]u8 = undefined;
var name: [256]u8 = undefined;
const prefix = if (shared) "shared." else "";
const channel = try o.replace(base, namespace, try std.fmt.bufPrint(&name, "{s}{s}.{s}.{s}", .{ prefix, try store.name(&key), h.proj.name(), if (h.proj == .down) "suh" else "svh" }));
const blocks = try o.replace(base, namespace, try std.fmt.bufPrint(&name, "{s}{s}.{s}.{s}", .{ prefix, try store.name(&key), h.proj.name(), if (h.proj == .down) "sv_block" else "su_block" }));
var healed = h;
const units = channel.dim(1) / 128;
healed.chan = std.mem.bytesAsSlice(f16, channel.bytes[(e * units + unit) * 256 ..][0..256]);
healed.block = std.mem.bytesAsSlice(f16, blocks.bytes[e * h.dims / 64 ..][0 .. h.dims / 64]);
healed.base_verified = true;
return healed;
}
};
pub const Address = struct { namespace: []const u8, name: []const u8, expert: bool = false, slice: bool = false };
pub fn address(name: []const u8) !Address {
var fields = std.mem.splitScalar(u8, name, '.');
const family = fields.next() orelse return error.BadExlr8OverlayNamespace;
const expert = std.mem.eql(u8, family, "experts");
if (std.mem.eql(u8, family, "vocab")) {
if (name.len <= 6) return error.BadExlr8OverlayNamespace;
return .{ .namespace = name[0..5], .name = name[6..] };
}
if (std.mem.eql(u8, family, "slices") and name.len > 7) return .{ .namespace = "slices", .name = name[7..], .slice = true };
if (!expert and !std.mem.eql(u8, family, "dense") and !std.mem.eql(u8, family, "extra")) return error.BadExlr8OverlayNamespace;
const section = fields.next() orelse return error.BadExlr8OverlayNamespace;
if (section.len == 0 or name.len <= family.len + section.len + 2) return error.BadExlr8OverlayNamespace;
if (!std.mem.eql(u8, family, "extra")) {
if (section.len != 4 or section[0] != 'L') return error.BadExlr8OverlayNamespace;
_ = std.fmt.parseInt(u16, section[1..], 10) catch return error.BadExlr8OverlayNamespace;
}
const end = family.len + 1 + section.len;
return .{ .namespace = name[0..end], .name = name[end + 1 ..], .expert = expert };
}
fn eligible(name: []const u8, expert: bool) bool {
var fields = std.mem.splitScalar(u8, name, '.');
while (fields.next()) |part| {
for ([_][]const u8{ "trellis", "rows", "q4", "q8", "fp8", "bf16", "fp32", "record", "index", "checksum", "signs", "heldout_tokens" }) |bad|
if (std.mem.eql(u8, part, bad)) return false;
if (std.mem.startsWith(u8, part, "err_")) return false;
}
const dot = std.mem.lastIndexOfScalar(u8, name, '.') orelse return !expert;
const suffix = name[dot + 1 ..];
if (expert) {
const proj_dot = std.mem.lastIndexOfScalar(u8, name[0..dot], '.') orelse return false;
const proj = name[proj_dot + 1 .. dot];
return (std.mem.eql(u8, proj, "gate") or std.mem.eql(u8, proj, "up")) and
(std.mem.eql(u8, suffix, "svh") or std.mem.eql(u8, suffix, "su_block")) or
std.mem.eql(u8, proj, "down") and (std.mem.eql(u8, suffix, "suh") or std.mem.eql(u8, suffix, "sv_block"));
}
return true;
}
pub fn finite(t: st.Tensor) !void {
for (0..t.bytes.len / t.dtype.size()) |i| {
const value: f64 = switch (t.dtype) {
.f16 => @as(f16, @bitCast(std.mem.readInt(u16, t.bytes[2 * i ..][0..2], .little))),
.bf16 => @as(f32, @bitCast(@as(u32, std.mem.readInt(u16, t.bytes[2 * i ..][0..2], .little)) << 16)),
.f32 => @as(f32, @bitCast(std.mem.readInt(u32, t.bytes[4 * i ..][0..4], .little))),
.f64 => @bitCast(std.mem.readInt(u64, t.bytes[8 * i ..][0..8], .little)),
else => continue,
};
if (!std.math.isFinite(value)) return error.NonfiniteExlr8Overlay;
}
}
+90
View File
@@ -0,0 +1,90 @@
//! Base-first overlay controls deliberately distinguish valid qheal from a checksum over already-healed values.
const std = @import("std");
const mf = @import("exlr8_manifest.zig");
const dense = @import("exlr8_dense.zig");
const f = @import("exlr8_fixture.zig");
const xxh = @import("xxhash64.zig");
const a = std.testing.allocator;
test "EXLR8 qheal: base checksum precedes substitution and a wrong overlay order is detected" {
if (comptime @hasDecl(mf, "Overlay")) try order() else return error.MissingExlr8Qheal;
}
fn order() !void {
var arena = std.heap.ArenaAllocator.init(a);
defer arena.deinit();
const gpa = arena.allocator();
const rec = try f.record(gpa, .{ 3, 1, 32, 0, 0, 0, 0, 0 });
const q: [32]u8 = @splat(0x38);
const exponent: [1]u8 = .{128};
const healed: [1]u8 = .{127};
var h = xxh.Hasher.init(0);
h.update(&q);
h.update(&exponent);
var sum: [1]u64 = .{h.final()};
const base = try f.view(gpa, .{ .format = "exlr8-v4" }, &.{
.{ .name = "m.record", .dtype = "I64", .shape = &.{8}, .bytes = rec },
.{ .name = "m.fp8", .dtype = "U8", .shape = &.{ 1, 32 }, .bytes = &q },
.{ .name = "m.e8m0", .dtype = "U8", .shape = &.{ 1, 1 }, .bytes = &exponent },
.{ .name = "m.checksum", .dtype = "U64", .shape = &.{1}, .bytes = std.mem.sliceAsBytes(&sum) },
});
const payload = try f.view(gpa, .{ .format = "exlr8-v4-manifest" }, &.{
.{ .name = "vocab.m.e8m0", .dtype = "U8", .shape = &.{ 1, 1 }, .bytes = &healed },
});
const overlay = try mf.Overlay.init(payload);
const m = try dense.Matrix.fromView(base, gpa, "m");
var values: [32]f32 = undefined;
const updated = try overlay.matrix(base, "vocab", m);
try updated.rows(0, 1, &values);
for (values) |v| try std.testing.expectEqual(@as(f32, 1), v);
try std.testing.expectEqual(@as(u8, 128), m.data[1].bytes[0]);
h = xxh.Hasher.init(0);
h.update(&q);
h.update(&healed);
sum[0] = h.final();
// Plant the hash of healed bytes into the base: a decoder that substitutes before hashing would accept it.
@memcpy(@constCast(m.checksum.?.bytes), std.mem.sliceAsBytes(&sum));
try std.testing.expectError(error.Exlr8ChecksumMismatch, overlay.matrix(base, "vocab", m));
}
test "EXLR8 qheal: protected codes, absent targets, shapes and nonfinite values refuse" {
if (comptime @hasDecl(mf, "Overlay")) try invalid() else return error.MissingExlr8QhealValidation;
}
fn invalid() !void {
var arena = std.heap.ArenaAllocator.init(a);
defer arena.deinit();
const gpa = arena.allocator();
const one: [1]f32 = .{1};
const inf: [1]f32 = .{std.math.inf(f32)};
const base = try f.view(gpa, .{ .format = "exlr8-v4" }, &.{
.{ .name = "norm.weight", .dtype = "F32", .shape = &.{1}, .bytes = std.mem.sliceAsBytes(&one) },
});
const payload = try f.view(gpa, .{ .format = "exlr8-v4-manifest" }, &.{
.{ .name = "dense.L007.norm.weight", .dtype = "F32", .shape = &.{1}, .bytes = std.mem.sliceAsBytes(&inf) },
});
const overlay = try mf.Overlay.init(payload);
try std.testing.expectError(error.NonfiniteExlr8Overlay, overlay.validate(base, "dense.L007"));
try std.testing.expectError(error.Exlr8OverlayTargetMissing, overlay.replace(base, "dense.L007", "absent"));
for ([_][]const u8{ "vocab.m.trellis.pmcgx", "vocab.m.record", "experts.L007.signs.in", "experts.L007.k2.err_gate" }) |name| {
const bad = try f.view(gpa, .{ .format = "exlr8-v4-manifest" }, &.{
.{ .name = name, .dtype = "U8", .shape = &.{1}, .bytes = &.{0} },
});
try std.testing.expectError(error.IneligibleExlr8Overlay, mf.Overlay.init(bad));
}
}
test "EXLR8 manifests: owned scalar profile and duplicate JSON/safetensors identity refusal" {
if (comptime @hasDecl(mf, "File")) try owned() else return error.MissingExlr8OwnedManifest;
}
fn owned() !void {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.createDirPath(io, "manifests");
const text = "{\"format\":\"exlr8-v2-manifest\",\"name\":\"k4\",\"layers\":{\"0\":{\"gate\":4,\"up\":4,\"down\":4}}}";
try tmp.dir.writeFile(io, .{ .sub_path = "manifests/exlr8-manifest-k4.json", .data = text });
const root = try tmp.dir.realPathFileAlloc(io, ".", a);
defer a.free(root);
var profile = try mf.File.open(a, io, root, "k4");
defer profile.deinit(io);
try std.testing.expectEqual(@as(u8, 8), (try profile.document.selected(0, 255, .gate, 3)).trellis);
try tmp.dir.writeFile(io, .{ .sub_path = "manifests/exlr8-manifest-k4.safetensors", .data = "" });
try std.testing.expectError(error.AmbiguousExlr8Manifest, mf.File.open(a, io, root, "k4"));
try std.testing.expectError(error.BadExlr8ProfileName, mf.File.open(a, io, root, "../k4"));
}
+35
View File
@@ -0,0 +1,35 @@
//! Materialize one verified expert unit in HF orientation using the same ordered FP32 reference transforms.
const std = @import("std");
const ex = @import("exlr8_experts.zig");
const codec = @import("exlr8_codec.zig");
pub fn decode(gpa: std.mem.Allocator, unit: ex.Unit, out: []f32) !void {
if (unit == .native) return unit.native.decode(out);
const h = unit.trellis;
if (!h.verify()) return error.Exlr8ChecksumMismatch;
const rows = h.rows();
const cols = h.cols();
if (out.len != try std.math.mul(usize, rows, cols)) return error.BadExlr8Rows;
const t = try h.spec();
const values = try gpa.alloc(f32, out.len);
defer gpa.free(values);
for (0..rows / 16) |ri| for (0..cols / 16) |co| {
const offset = if (h.proj == .down) (co / 8 * 64 + ri * 8 + co % 8) * t.tileBytes() else (ri * 8 + co) * t.tileBytes();
if (offset > h.trellis.len or t.tileBytes() > h.trellis.len - offset) return error.BadExlr8Tile;
try t.decode(h.trellis[offset..][0..t.tileBytes()], values[ri * 16 * cols + co * 16 ..], cols);
};
const su = try gpa.alloc(f32, rows);
defer gpa.free(su);
const sv = try gpa.alloc(f32, cols);
defer gpa.free(sv);
h.suh(su);
h.svh(sv);
var block: [128 * 128]f32 = undefined;
for (0..rows / 128) |bi| for (0..cols / 128) |bj| {
var tile: [128][128]f32 = undefined;
for (0..128) |k| @memcpy(&tile[k], values[(bi * 128 + k) * cols + bj * 128 ..][0..128]);
codec.reconstructValuesBlockF32(&tile, su[bi * 128 ..], sv[bj * 128 ..], &block);
for (0..128) |r| {
for (0..128) |c| out[(bj * 128 + c) * rows + bi * 128 + r] = block[r * 128 + c];
}
};
}