Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
b731206
feat(hip): the model-free kernels on #463's runtime: attention, Delta…
BlivionIaG Oct 10, 2026
67d9479
feat(core): weight formats behind one interface, MLX affine 2- to 8-b…
BlivionIaG Oct 10, 2026
48abd99
feat(core): a kernel registry that picks a product's tile by tuned co…
BlivionIaG Oct 10, 2026
6254228
feat(hip): the MLX affine products: dot2 tiles, the gfx11 matrix-core…
BlivionIaG Oct 10, 2026
9b6b260
docs(hip): the device bitcode of Ubuntu's packaged HIP, and no rocWMM…
BlivionIaG Oct 11, 2026
1152c67
Merge branch 'hip-kernels-ops' into hip-kernels-affine
BlivionIaG Oct 11, 2026
df83c6f
Merge branch 'hip-kernels-ops' into hip-kernels-affine
BlivionIaG Oct 11, 2026
5d05894
chore(hip): gdn_prefill.hip drops the vLLM SPDX lines it kept from th…
BlivionIaG Oct 11, 2026
a579284
Merge branch 'hip-kernels-affine' into fam-new
BlivionIaG Oct 11, 2026
e6c11fb
feat(qwen3_5): the GPU backends' checkpoint loader, on the host
BlivionIaG Oct 10, 2026
eb9bd0f
fix(qwen3_5): un-center an MTP head shipped zero-centered
BlivionIaG Oct 11, 2026
4c231bf
feat(qwen3_5): the HIP config refuses what the kernels do not compute…
BlivionIaG Oct 11, 2026
02c1dd6
Merge remote-tracking branch 'upstream/main' into fam-r2
BlivionIaG Oct 12, 2026
57fadd1
feat(hip): the runtime pieces an engine uses beyond #463's model-free…
BlivionIaG Oct 10, 2026
211ea81
feat(hip): the kernels a tensor-parallel rank and the MTP head add
BlivionIaG Oct 10, 2026
42664f9
feat(qwen3_5): the Qwen3.5 / Qwen3.6 engine on HIP, its native server…
BlivionIaG Oct 10, 2026
3d9bd2e
feat(hip): one rank source: --speed-up is refused, the HIP engine's r…
BlivionIaG Oct 10, 2026
a25c8e2
feat(qwen3_5): the HIP prompt cache serves serial requests too
BlivionIaG Oct 10, 2026
3092774
test(qwen3_5): chat with the prompt cache equals chat without it thro…
BlivionIaG Oct 10, 2026
9a4e10f
feat(qwen3_5): a prompt runs 512-row chunks while other streams decode
BlivionIaG Oct 11, 2026
3f396fc
feat(hip): RDNA4 runs on the dot2 tiles; matrix=on is refused where n…
BlivionIaG Oct 11, 2026
fc795cb
test(qwen3_5): serve_rewind.py's docstring on one line, as the lean c…
BlivionIaG Oct 11, 2026
10f67d9
refactor(qwen3_5): the engine reaches the other ranks through hip/col…
BlivionIaG Oct 11, 2026
7f5fd5b
build(hip): the HIP server's CLI module takes EXLR8's import, as main…
BlivionIaG Oct 12, 2026
1bef9ae
feat(hip): the graph cache by shape in the hip module, for every HIP …
BlivionIaG Oct 12, 2026
f2fbf5f
feat(hip): a step recorded as graphs cut at its collectives, the coll…
BlivionIaG Oct 12, 2026
195048e
feat(hip): the graph cache over any replayable step, a caller's own k…
BlivionIaG Oct 12, 2026
79ce774
feat(qwen3_5): HIP rounds record split graphs: the collectives run be…
BlivionIaG Oct 12, 2026
73e4989
perf(qwen3_5): the HIP loader drops each part's mapped pages once it …
BlivionIaG Oct 13, 2026
1ae1078
style(hip): the ops headers end without a blank line, as git diff --c…
BlivionIaG Oct 14, 2026
47612d0
Merge branch 'hip-kernels-ops' into qwen35-family (ops headers end wi…
BlivionIaG Oct 14, 2026
687c5aa
Merge branch 'qwen35-family' into qwen35-engine (ops headers end with…
BlivionIaG Oct 14, 2026
5537d6a
fix(hip): the paged prefill tile calls expf, as the flat tile does
BlivionIaG Oct 14, 2026
9178585
Merge branch 'hip-kernels-ops' into qwen35-family (the paged prefill …
BlivionIaG Oct 14, 2026
0393db4
Merge branch 'qwen35-family' into qwen35-engine (the paged prefill ti…
BlivionIaG Oct 14, 2026
d91b074
fix(hip): one fp32 DeltaNet recurrence at every length; the chunked p…
BlivionIaG Oct 14, 2026
1da7042
Merge branch 'hip-kernels-ops' into qwen35-family (one fp32 DeltaNet …
BlivionIaG Oct 14, 2026
22850d9
Merge branch 'qwen35-family' into qwen35-engine (one fp32 DeltaNet re…
BlivionIaG Oct 14, 2026
4aaeac0
refactor(hip): the policy's gdn switch goes with the chunked recurren…
BlivionIaG Oct 14, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
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 67d94795185f60f7eaaf173a62b367dddb28f17c
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