Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat(core): weight formats behind one interface, MLX affine 2- to 8-b…
…it and dense, with tensor-parallel cuts

core/quant reads a checkpoint's MLX affine projections (bits 2, 3, 4, 5, 6 and 8, any group) or dense ones,
detects the format from the tensors, cuts a projection by output rows, by a rank's whole input groups or into
its two K halves, splits an expert stack across ranks, and hands a backend the upload. Every cut keeps the
codes and group tables byte for byte: a test quantizes with affine4_host and checks each cut dequantizes to the
same bits as the rows and columns it covers, and it fails when a cut is off by one group.
  • Loading branch information
BlivionIaG committed Oct 10, 2026
commit 2f9ba43b618e3f87b330c3953feeacb8ebc66094
68 changes: 68 additions & 0 deletions zig/src/core/quant/convert.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
//! Host-side element conversions the Python loader does with torch: `.float()` and bf16 rounding.

const std = @import("std");
const st = @import("../safetensors.zig");

const Tensor = st.Tensor;
const DType = st.DType;

pub const Error = error{ UnexpectedTensor, UnsupportedQuantization } || std.mem.Allocator.Error;

/// One element as fp32 (bf16 and fp16 widen exactly).
pub fn load(dtype: DType, bytes: []const u8, i: usize) f32 {
return switch (dtype) {
.f32 => @bitCast(std.mem.readInt(u32, bytes[4 * i ..][0..4], .little)),
.bf16 => @bitCast(@as(u32, std.mem.readInt(u16, bytes[2 * i ..][0..2], .little)) << 16),
.f16 => @floatCast(@as(f16, @bitCast(std.mem.readInt(u16, bytes[2 * i ..][0..2], .little)))),
else => unreachable,
};
}

pub fn isFloat(dtype: DType) bool {
return switch (dtype) {
.f16, .bf16, .f32, .f64 => true,
else => false,
};
}

/// The group-table dtypes the kernels read as stored.
pub fn tableDtype(dtype: DType) bool {
return dtype == .f32 or dtype == .bf16 or dtype == .f16;
}

/// torch's fp32 -> bf16: round to nearest even, NaN stays a NaN.
pub fn bf16(x: f32) u16 {
const bits: u32 = @bitCast(x);
if (std.math.isNan(x)) return @intCast((bits >> 16) | 0x40);
return @intCast((bits + 0x7FFF + ((bits >> 16) & 1)) >> 16);
}

/// Writes `src` as little-endian fp32 into `dst` (4 bytes an element).
pub fn widenInto(dst: []u8, src: Tensor) Error!void {
const n = src.numel();
if (dst.len != n * 4) return error.UnexpectedTensor;
switch (src.dtype) {
.f32, .bf16, .f16 => for (0..n) |i| std.mem.writeInt(u32, dst[4 * i ..][0..4], @bitCast(load(src.dtype, src.bytes, i)), .little),
.f64 => for (0..n) |i| {
const v: f64 = @bitCast(std.mem.readInt(u64, src.bytes[8 * i ..][0..8], .little));
std.mem.writeInt(u32, dst[4 * i ..][0..4], @bitCast(@as(f32, @floatCast(v))), .little);
},
else => return error.UnexpectedTensor,
}
}

/// `.float().contiguous()` of a floating tensor into memory of `a` (an fp32 tensor is shared, not copied).
pub fn float32(a: std.mem.Allocator, src: Tensor) Error!Tensor {
if (src.dtype == .f32) return src;
const out = try a.alloc(u8, src.numel() * 4);
try widenInto(out, src);
return .{ .dtype = .f32, .rank = src.rank, .shape = src.shape, .bytes = out };
}

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, 0x3F807FFF))));
try std.testing.expectEqual(@as(u16, 0x3F82), bf16(@bitCast(@as(u32, 0x3F818000))));
try std.testing.expectEqual(@as(u16, 0x3F80), bf16(@bitCast(@as(u32, 0x3F808000))));
try std.testing.expect(std.math.isNan(@as(f32, @bitCast(@as(u32, bf16(std.math.nan(f32))) << 16))));
}
107 changes: 107 additions & 0 deletions zig/src/core/quant/dense.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
//! Weights kept in float: fp32 [N, K], the unquantized projections a conversion leaves (an MTP head's fc).

const std = @import("std");
const types = @import("types.zig");
const slice = @import("slice.zig");
const convert = @import("convert.zig");

const Tensor = types.Tensor;
const Allocator = std.mem.Allocator;
const join = types.join;

pub const id: types.Format = .dense;
pub const decoder: types.Decoder = .dense;

/// A float weight is not named by the config: nothing here declares it.
pub const Config = void;

pub fn detect(a: Allocator, src: types.Sources) Allocator.Error!?Config {
_ = a;
_ = src;
return null;
}

pub const Host = struct { weight: Tensor };

/// Whether `key` holds a float matrix with no table of scales beside it.
pub fn matches(t: anytype, key: []const u8) bool {
var buf: [256]u8 = undefined;
const w = t.get(join(&buf, &.{ key, ".weight" })) catch return false;
return convert.isFloat(w.dtype) and w.rank == 2 and !t.has(join(&buf, &.{ key, ".scales" }));
}

/// The float weight widened to fp32.
pub fn read(a: Allocator, t: anytype, key: []const u8) !Host {
var buf: [256]u8 = undefined;
return .{ .weight = try convert.float32(a, try t.get(join(&buf, &.{ key, ".weight" }))) };
}

pub fn rows(h: Host) usize {
return h.weight.shape[0];
}

pub fn bytes(h: Host) usize {
return h.weight.bytes.len;
}

/// Both halves along K, copied.
pub fn halves(a: Allocator, p: Host) ![2]Host {
const half = p.weight.shape[1] / 2;
return .{
.{ .weight = try slice.takeCols(a, p.weight, 0, half) },
.{ .weight = try slice.takeCols(a, p.weight, half, p.weight.shape[1]) },
};
}

pub fn sliceRows(a: Allocator, p: Host, spans: []const slice.Span) slice.Error!Host {
return .{ .weight = try slice.takeRows(a, p.weight, spans) };
}

pub fn sliceCols(a: Allocator, p: Host, r: slice.Rank, what: []const u8) slice.Error!Host {
const width = try slice.even(p.weight.shape[1], r.world, what);
return .{ .weight = try slice.takeCols(a, p.weight, r.rank * width, (r.rank + 1) * width) };
}

pub fn sliceStack(a: Allocator, p: Host, r: slice.Rank, part: usize) slice.Error!Host {
return .{ .weight = try slice.takeExperts(a, p.weight, r, part) };
}

pub const Device = struct { weight: types.Buf };

pub fn upload(u: types.Uploader, h: Host) !Device {
return .{ .weight = try u.tensor(h.weight) };
}

/// What the kernels read: the fp32 weight's address.
pub const Matrix = struct { weight: u64 };

pub const View = struct { n: u32, k: u32, matrix: Matrix };

pub fn view(d: Device, stacked: bool) error{UnsupportedTables}!View {
const lead: usize = @intFromBool(stacked);
return .{ .n = @intCast(d.weight.dim(lead)), .k = @intCast(d.weight.dim(lead + 1)), .matrix = .{ .weight = d.weight.ptr } };
}

pub fn elements(h: Host) usize {
return h.weight.numel();
}

/// The weight as fp64, row by row.
pub fn reference(h: Host, out: []f64) error{UnexpectedTensor}!void {
if (out.len != h.weight.numel()) return error.UnexpectedTensor;
for (out, 0..) |*o, i| o.* = convert.load(.f32, h.weight.bytes, i);
}

test "a float weight halves along K and cuts its rows" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var data = [_]f32{ 1, 2, 3, 4, 5, 6, 7, 8 };
const h: Host = .{ .weight = .{ .dtype = .f32, .rank = 2, .shape = .{ 2, 4, 1, 1, 1 }, .bytes = std.mem.sliceAsBytes(&data) } };
const pair = try halves(a, h);
try std.testing.expectEqualSlices(f32, &.{ 3, 4, 7, 8 }, @alignCast(std.mem.bytesAsSlice(f32, pair[1].weight.bytes)));
const low = try sliceRows(a, h, &.{.{ .from = 1, .to = 2 }});
var out: [4]f64 = undefined;
try reference(low, &out);
try std.testing.expectEqualSlices(f64, &.{ 5, 6, 7, 8 }, &out);
}
70 changes: 70 additions & 0 deletions zig/src/core/quant/exact_test.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
//! Every cut of an MLX affine projection dequantizes to the same bits as the uncut rows and columns it covers.
const std = @import("std");
const mlx = @import("mlx.zig");
const slice = @import("slice.zig");
const ref = @import("../affine4_host.zig");
const Tensor = @import("types.zig").Tensor;

const n = 8;
const k = 512;
const groups = k / ref.group;

fn tensor(dtype: anytype, rows: usize, cols: usize, bytes: []u8) Tensor {
return .{ .dtype = dtype, .rank = 2, .shape = .{ rows, cols, 1, 1, 1 }, .bytes = bytes };
}

/// The cut's values, row-major, by the reference dequantizer.
fn values(a: std.mem.Allocator, h: mlx.Host) ![]f32 {
const out = try a.alloc(f32, h.words.shape[0] * h.scales.shape[1] * h.group);
ref.dequantize(try aligned(a, u32, h.words.bytes), try aligned(a, u16, h.scales.bytes), try aligned(a, u16, h.biases.bytes), out);
return out;
}

/// A cut's bytes as typed elements (a cut is a byte slice of any alignment).
fn aligned(a: std.mem.Allocator, comptime T: type, bytes: []const u8) ![]T {
const out = try a.alloc(T, bytes.len / @sizeOf(T));
@memcpy(std.mem.sliceAsBytes(out), bytes);
return out;
}

fn expectCut(full: []const f32, cut: []const f32, rows: []const usize, col0: usize, cols: usize) !void {
try std.testing.expectEqual(rows.len * cols, cut.len);
for (rows, 0..) |row, r| for (0..cols) |c| {
const want: u32 = @bitCast(full[row * k + col0 + c]);
const got: u32 = @bitCast(cut[r * cols + c]);
try std.testing.expectEqual(want, got);
};
}

test "row spans, rank column groups and K halves keep every dequantized bit" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var prng = std.Random.DefaultPrng.init(0x7f0d);
const x = try a.alloc(f32, n * k);
for (x) |*v| v.* = prng.random().floatNorm(f32) * 0.05;
const words = try a.alloc(u32, n * k / 8);
const scales = try a.alloc(u16, n * groups);
const biases = try a.alloc(u16, n * groups);
ref.quantize(x, words, scales, biases);
const h: mlx.Host = .{
.words = tensor(.i32, n, k / 8, std.mem.sliceAsBytes(words)),
.scales = tensor(.bf16, n, groups, std.mem.sliceAsBytes(scales)),
.biases = tensor(.bf16, n, groups, std.mem.sliceAsBytes(biases)),
.bits = 4,
.group = ref.group,
};
const full = try values(a, h);
const all = [_]usize{ 0, 1, 2, 3, 4, 5, 6, 7 };

const spans = [_]slice.Span{ .{ .from = 1, .to = 3 }, .{ .from = 5, .to = 8 } };
try expectCut(full, try values(a, try mlx.sliceRows(a, h, &spans)), &.{ 1, 2, 5, 6, 7 }, 0, k);

for ([_]usize{ 1, 2, 4, 8 }) |world| for (0..world) |rank| {
const cut = try mlx.sliceCols(a, h, .{ .rank = rank, .world = world }, "exact");
try expectCut(full, try values(a, cut), &all, rank * k / world, k / world);
};

const pair = try mlx.halves(a, h);
for (pair, 0..) |half, i| try expectCut(full, try values(a, half), &all, i * k / 2, k / 2);
}
Loading