Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions zig/src/families/deepseek_v41/block.zig
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ pub const Widths = struct {

/// Run-time sizes fixed at load (scratch and pools), and the L2 prefetch settings.
pub const Options = struct {
/// how the checkpoint stores its projections (config.json): the emitter's projection bodies follow it
format: @import("config.zig").Format = .exl3,
/// TF_DSV41_IMAGES=native: this prefill segment holds image positions, so Engram fuses with a keep vector
image_keep: bool = false,
/// TF_DSV41_BIAS_VL: the segment's image rows (MoE call apart, gate.bias_vl); 0: none; < 0: the buffer plan's
Expand Down
2 changes: 1 addition & 1 deletion zig/src/families/deepseek_v41/block_admission.zig
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub fn nativePrefill(c: *const Config, world: u32) !void {

pub fn options(c: *const Config, o: anytype, layers: []const u32, n: i64) !void {
const rank = if (@hasField(@TypeOf(o), "rank")) o.rank else 0;
const part = @import("partition.zig").share(c.expert_width, rank, o.world) catch return error.InvalidBlock;
const part = @import("partition.zig").expertShare(c, rank, o.world) catch return error.InvalidBlock;
if (o.expert_rows < 0 or o.dspark_rows < 0 or o.branch_rows < 0 or o.prefill_rows < 0 or o.image_rows < -1) return error.InvalidBlock;
for (layers) |l| {
if (l >= c.allLayers()) return error.InvalidBlock;
Expand Down
2 changes: 1 addition & 1 deletion zig/src/families/deepseek_v41/block_moe.zig
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ pub fn moe(e: *E, L: u32) !void {
const ex = e.cfg.expertsOf(L);
const slots: i64 = ex.topk + 1;
const Et: i64 = ex.count + 1;
const I: i64 = (try @import("partition.zig").share(e.cfg.expert_width, e.o.rank, e.o.world)).len;
const I: i64 = (try @import("partition.zig").expertShare(e.cfg, e.o.rank, e.o.world)).len;
const P = n * slots;
const rows: i64 = if (backbone) e.o.expert_rows else e.o.dspark_rows;
const sc: []const u8 = if (backbone) "s.ex" else "s.dx";
Expand Down
2 changes: 1 addition & 1 deletion zig/src/families/deepseek_v41/block_prefetch.zig
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub fn l2pfSources(e: *Emitter, L: u32, site: L2Site) ![]const L2Src {
},
.f => {
const D: i64 = e.cfg.hidden;
const I: i64 = (try @import("partition.zig").share(e.cfg.expert_width, e.o.rank, e.o.world)).len;
const I: i64 = (try @import("partition.zig").expertShare(e.cfg, e.o.rank, e.o.world)).len;
const ex = e.cfg.expertsOf(L);
const sh = try e.fmt("L{d}.moe.shared.0.w1", .{L});
const k2: u64 = try e.w.k2(sh);
Expand Down
2 changes: 1 addition & 1 deletion zig/src/families/deepseek_v41/block_prefill_moe.zig
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub fn moeRows(s: *Seg, L: u32, n: i64, x: Arg, comptime bias: []const u8, part:
const topk: i64 = ex.topk;
const slots: i64 = topk + 1;
const Et: i64 = ex.count;
const I: i64 = (try @import("partition.zig").share(e.cfg.expert_width, e.o.rank, e.o.world)).len;
const I: i64 = (try @import("partition.zig").expertShare(e.cfg, e.o.rank, e.o.world)).len;
const P = n * topk;
const pick = try e.buf("L.pick", .{}, .i32, &.{ n, slots });
const wts = try e.buf("L.wts", .{}, .f32, &.{ n, slots });
Expand Down
6 changes: 3 additions & 3 deletions zig/src/families/deepseek_v41/cuda_weights.zig
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,8 @@ pub fn load(w: *Weights, d: *const cuda.Driver, io: std.Io, cfg: *const @import(
@import("core").checkpoint.cache.files(io, pack.dir, pack.files.items);
}
fn admitGroup(pack: *const @import("pack.zig").Pack, io: std.Io, group: @import("plan.zig").GroupPlan) !void {
try admitWidth(try pack.codebook(io, group.prefix), group.part.group.k2());
if (std.mem.indexOfScalar(u32, &cuda.qlinear.block.dense.linear_k2s, group.part.group.k2()) == null)
try admitWidth(try pack.codebook(io, group.prefix), group.form.exl3.part.group.k2());
if (std.mem.indexOfScalar(u32, &cuda.qlinear.block.dense.linear_k2s, group.form.exl3.part.group.k2()) == null)
return error.UnsupportedCudaWidth;
}

Expand All @@ -157,7 +157,7 @@ pub fn admitPlan(io: std.Io, cfg: *const @import("config.zig").Config, pack: *co
if (plan.leftovers.len != 0 or pack.missing != 0) return error.UnclaimedTensor;
for (plan.layers) |layer| {
for (layer.groups) |group| try admitGroup(pack, io, group);
for (layer.experts) |projection| for (projection.prefixes, projection.parts) |prefix, part| {
for (layer.experts) |projection| for (projection.form.exl3.prefixes, projection.form.exl3.parts) |prefix, part| {
try admitWidth(try pack.codebook(io, prefix), part.group.k2());
try admitExpertWidths(part.group.k2(), part.group.k2());
};
Expand Down
2 changes: 1 addition & 1 deletion zig/src/families/deepseek_v41/forms.zig
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ fn buildArena(a: std.mem.Allocator, s: *const Source, role: []const u8) !?[]cons
const lp = for (s.plan.layers) |*l| {
if (l.index == L) break l;
} else return error.LayerNotPlanned;
const lay = &lp.experts[proj].layout;
const lay = &lp.experts[proj].form.exl3.layout;
const E = lay.words.len;
const shared = try std.fmt.allocPrint(a, "{s}.moe.shared.0.{s}", .{ layer, w });
if (std.mem.startsWith(u8, what, "k2")) {
Expand Down
4 changes: 2 additions & 2 deletions zig/src/families/deepseek_v41/gate_forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub fn widths(a: std.mem.Allocator, w: *const load.Weights, p: *const plan.Plan)
for (p.layers) |*l| {
var r: [2][2]u32 = .{ .{ 99, 0 }, .{ 99, 0 } };
for ([_]usize{ 0, 2, 1 }, [_]usize{ 0, 0, 1 }) |proj, slot| {
for (l.experts[proj].layout.words) |words| {
for (l.experts[proj].form.exl3.layout.words) |words| {
r[slot][0] = @min(r[slot][0], words / 8);
r[slot][1] = @max(r[slot][1], words / 8);
}
Expand All @@ -39,7 +39,7 @@ pub fn widths(a: std.mem.Allocator, w: *const load.Weights, p: *const plan.Plan)
try out.experts.put(a, l.index, r);
// x3gm's widths present: the routed experts' gate (w1) and down (w2) K2s, the shared expert not among them
var gm: [2]u32 = .{ 0, 0 };
for (0..2) |proj| for (l.experts[proj].layout.words) |words| {
for (0..2) |proj| for (l.experts[proj].form.exl3.layout.words) |words| {
gm[proj] |= @as(u32, 1) << @intCast(words / 8);
};
try out.gm.put(a, l.index, gm);
Expand Down
32 changes: 16 additions & 16 deletions zig/src/families/deepseek_v41/host_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -172,18 +172,18 @@ test "a synthetic pack: both ranks plan every block, the parts tile the full ten
try testing.expectEqual(@as(usize, 10), r0.layers.len);
const l2 = &r0.layers[2];
try testing.expectEqual(config.Mode.full, l2.mode);
try testing.expect(l2.experts[1].layout.kind == .ragged and l2.experts[0].layout.kind == .ragged and l2.experts[2].layout.kind == .stack);
try testing.expect(l2.experts[1].form.exl3.layout.kind == .ragged and l2.experts[0].form.exl3.layout.kind == .ragged and l2.experts[2].form.exl3.layout.kind == .stack);
try testing.expectEqual(@as(u32, 1), l2.gate_up_mismatch);
try testing.expectEqual(@as(u32, 2), l2.experts[1].layout.widths());
try testing.expect(r0.layers[3].experts[1].layout.kind == .stack);
try testing.expectEqual(@as(usize, 4), r0.layers[8].experts[0].layout.count());
try testing.expectEqual(@as(u32, 2), l2.experts[1].form.exl3.layout.widths());
try testing.expect(r0.layers[3].experts[1].form.exl3.layout.kind == .stack);
try testing.expectEqual(@as(usize, 4), r0.layers[8].experts[0].form.exl3.layout.count());
// every split part on the two ranks adds up to the stored tensor
for (r0.layers, r1.layers) |x, y| for (x.groups, y.groups) |g0, g1| {
if (g0.split == .whole) {
try testing.expectEqual(g0.full.trellisBytes(), g0.part.trellis.bytes());
} else try testing.expectEqual(g0.full.trellisBytes(), g0.part.trellis.bytes() + g1.part.trellis.bytes());
try testing.expectEqual(g0.form.exl3.full.trellisBytes(), g0.form.exl3.part.trellis.bytes());
} else try testing.expectEqual(g0.form.exl3.full.trellisBytes(), g0.form.exl3.part.trellis.bytes() + g1.form.exl3.part.trellis.bytes());
};
try testing.expectEqual(r0.head.?.full.trellisBytes(), r0.head.?.part.trellis.bytes() + r1.head.?.part.trellis.bytes());
try testing.expectEqual(r0.head.?.form.exl3.full.trellisBytes(), r0.head.?.form.exl3.part.trellis.bytes() + r1.head.?.form.exl3.part.trellis.bytes());
try testing.expectEqualStrings("mtp.1.main_proj", r0.dspark.?.main_proj.prefix);
try testing.expect(r0.dspark.?.confidence != null);
try testing.expectEqual(r0.bytes(), r1.bytes());
Expand Down Expand Up @@ -343,8 +343,8 @@ test "real pack headers (TF_DSV41_HEADERS: model.safetensors.index.json and <sha
std.debug.print("full headers rank {d}: {d} tensors, {d} layers, {d} bytes, zero leftovers\n", .{ rank, p.names.count(), pl.layers.len, pl.bytes() });
}
for (pl.layers) |*l| {
const h = l.experts[1].layout.histogram();
std.debug.print("rank {d} {s} {t}: down {t} K2 4/6/8 = {d}/{d}/{d}, gate/up mismatches {d}, experts {d} B, block {d} B\n", .{ rank, l.prefix, l.mode, l.experts[1].layout.kind, h[4], h[6], h[8], l.gate_up_mismatch, l.expertBytes(), l.bytes() });
const h = l.experts[1].form.exl3.layout.histogram();
std.debug.print("rank {d} {s} {t}: down {t} K2 4/6/8 = {d}/{d}/{d}, gate/up mismatches {d}, experts {d} B, block {d} B\n", .{ rank, l.prefix, l.mode, l.experts[1].form.exl3.layout.kind, h[4], h[6], h[8], l.gate_up_mismatch, l.expertBytes(), l.bytes() });
}
}
}
Expand Down Expand Up @@ -384,22 +384,22 @@ test "cold native headers preserve expert identity across three width classes on
defer r1.deinit();
for (r0.layers, r1.layers) |l0, l1| {
for (l0.experts, l1.experts) |e0, e1| {
try testing.expect(e0.layout.kind == .ragged and e1.layout.kind == .ragged);
try testing.expectEqual(@as(u32, 3), e0.layout.widths());
try testing.expectEqualSlices(u16, e0.layout.words, e1.layout.words);
try testing.expectEqualSlices(u64, e0.layout.offsets, e1.layout.offsets);
try testing.expect(e0.form.exl3.layout.kind == .ragged and e1.form.exl3.layout.kind == .ragged);
try testing.expectEqual(@as(u32, 3), e0.form.exl3.layout.widths());
try testing.expectEqualSlices(u16, e0.form.exl3.layout.words, e1.form.exl3.layout.words);
try testing.expectEqualSlices(u64, e0.form.exl3.layout.offsets, e1.form.exl3.layout.offsets);
var offset: u64 = 0;
for (e0.parts, e1.parts, e0.prefixes, e1.prefixes, 0..) |p0, p1, n0, n1, id| {
for (e0.form.exl3.parts, e1.form.exl3.parts, e0.form.exl3.prefixes, e1.form.exl3.prefixes, 0..) |p0, p1, n0, n1, id| {
try testing.expectEqualStrings(n0, n1);
var name: [128]u8 = undefined;
try testing.expectEqualStrings(try @import("names.zig").expertName(l0.prefix, @intCast(id), e0.proj, &name), n0);
try testing.expectEqual(@as(u32, @intCast(widths[id % widths.len])), p0.group.words);
try testing.expectEqual(offset, e0.layout.byteOffset(id));
try testing.expectEqual(offset, e0.form.exl3.layout.byteOffset(id));
const stored = pack.names.get(try std.fmt.bufPrint(&name, "{s}.trellis", .{n0})).?;
try testing.expectEqual(stored.nbytes, p0.trellis.bytes() + p1.trellis.bytes());
offset += p0.trellis.bytes();
}
try testing.expectEqual(offset, e0.layout.trellisBytes());
try testing.expectEqual(offset, e0.form.exl3.layout.trellisBytes());
}
}
try testing.expectEqual(@as(usize, 0), r0.leftovers.len);
Expand Down
2 changes: 1 addition & 1 deletion zig/src/families/deepseek_v41/load_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ test "production loader refuses unsupported expert route before allocating an im
var prefixes = [_][]const u8{"p"};
var words = [_]u16{112};
var offsets = [_]u64{0};
const expert: plans.ExpertsPlan = .{ .proj = .w1, .parts = &parts, .prefixes = &prefixes, .layout = .{ .kind = .stack, .k_tiles = 8, .n_tiles = 8, .words = &words, .offsets = &offsets, .elements = 7168 } };
const expert: plans.ExpertsPlan = .{ .proj = .w1, .form = .{ .exl3 = .{ .parts = &parts, .prefixes = &prefixes, .layout = .{ .kind = .stack, .k_tiles = 8, .n_tiles = 8, .words = &words, .offsets = &offsets, .elements = 7168 } } } };
var layers = [_]plans.LayerPlan{.{ .index = 0, .prefix = "layers.0", .mode = .full, .groups = &.{}, .natives = &.{}, .experts = @splat(expert), .gate_up_mismatch = 0 }};
const plan: plans.Plan = .{ .arena = undefined, .rank = 0, .world = 1, .layers = &layers, .top = &.{}, .head = null, .dspark = null, .leftovers = &.{} };
var fail = std.testing.FailingAllocator.init(a, .{ .fail_index = 0 });
Expand Down
4 changes: 2 additions & 2 deletions zig/src/families/deepseek_v41/named.zig
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ pub const Builder = struct {
fn group(b: *Builder, base: []const u8, g: plan.GroupPlan) !void {
var img: stage.GroupImage = if (b.metadata_only) .{ .trellis = &.{}, .suh = &.{}, .svh = &.{} } else try stage.group(b.gpa, b.io, b.pack, g);
defer img.deinit(b.gpa);
const p = g.part.group;
const p = g.form.exl3.part.group;
var nb: [160]u8 = undefined;
try b.put(try std.fmt.bufPrint(&nb, "{s}.trellis", .{base}), .i16, &.{ p.k_tiles, p.n_tiles, p.words }, try b.copy(img.trellis));
try b.put(try std.fmt.bufPrint(&nb, "{s}.suh", .{base}), .f16, &.{p.k()}, try b.copy(img.suh));
Expand All @@ -137,7 +137,7 @@ pub const Builder = struct {
fn experts(b: *Builder, base: []const u8, x: *const plan.ExpertsPlan) !void {
var img: stage.ExpertsImage = if (b.metadata_only) .{ .trellis = &.{}, .suh = &.{}, .svh = &.{}, .k2 = &.{}, .offsets = &.{} } else try stage.experts(b.gpa, b.io, b.pack, x);
defer img.deinit(b.gpa);
const l = &x.layout;
const l = &x.form.exl3.layout;
const e = l.count();
var nb: [160]u8 = undefined;
if (l.kind == .stack) {
Expand Down
25 changes: 22 additions & 3 deletions zig/src/families/deepseek_v41/partition.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,31 @@ const exl3 = @import("core").exl3_layout;

pub const Share = struct { lo: u32, len: u32 };

/// A rank's whole 128-column blocks of `width`, the remainder to the low ranks.
pub fn share(width: u32, rank: usize, world: usize) !Share {
if (world == 0 or rank >= world or width % 128 != 0 or width / 128 < world) return error.SplitNotOnBlocks;
const blocks: usize = width / 128;
return shareOn(width, 128, rank, world);
}

/// A rank's whole `unit`-column blocks of `width`, the remainder to the low ranks.
pub fn shareOn(width: u32, unit: u32, rank: usize, world: usize) !Share {
if (world == 0 or unit == 0 or rank >= world or width % unit != 0 or width / unit < world) return error.SplitNotOnBlocks;
const blocks: usize = width / unit;
const base = blocks / world;
const extra = blocks % world;
return .{ .lo = @intCast((rank * base + @min(rank, extra)) * 128), .len = @intCast((base + @intFromBool(rank < extra)) * 128) };
return .{ .lo = @intCast((rank * base + @min(rank, extra)) * unit), .len = @intCast((base + @intFromBool(rank < extra)) * unit) };
}

/// The expert-width block a format's kernels split on: EXL3 tiles are 128 wide, the release's MMA blocks 64.
pub fn expertUnit(format: @import("config.zig").Format) u32 {
return switch (format) {
.exl3 => 128,
.release_fp8 => 64,
};
}

/// A rank's share of the routed and shared experts' width for the checkpoint's format.
pub fn expertShare(c: *const @import("config.zig").Config, rank: usize, world: usize) !Share {
return shareOn(c.expert_width, expertUnit(c.format), rank, world);
}

/// A rank's whole output groups by canon's rule: heads, `wq_b` columns and `wo_b` rows all follow them.
Expand Down
Loading
Loading