Skip to content
Merged
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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- Qwen 3.5 and 3.8 configs: one tied-head rule reads `tie_word_embeddings` from `text_config` then the root, and a checkpoint that sets neither loads untied, as transformers does (HIP had loaded it tied; Metal's 2B still requires the key); a root and `text_config` that disagree, or a value that isn't a flag, are refused with `BadTiedHead`. Flash Next, LFM2, Kolibri-1 and Qwen 3.5 read `rope_parameters`, legacy `rope_scaling` and their top-level keys through one core reader, and every config they accepted parses as before (#2714, fixes #2561, part of #2460). Thanks to @jschmied.


- CUDA: a family can declare that it keeps no prompt states, so the pool plans no prompt cache for it and `--prompt-cache-gib` is refused by name before the weights load, and that its replies carry no reasoning block, as HIP already allows; every family on main is unchanged (#2710). Thanks to @laudney.

Expand Down
8 changes: 7 additions & 1 deletion zig/build/qwen35_layers.zig
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! The std-only `qwen35_layers` and `qwen35_rules` modules for every build consumer; each file has one module owner.
//! The std-only shared modules (`qwen35_layers`, `qwen35_rules`, `rope_config`) for every build consumer.

const std = @import("std");

Expand All @@ -18,6 +18,12 @@ const shared = [_]Shared{
.step = "test-qwen35-rules",
.about = "Qwen3.5's computed-part refusals: one table, a column per backend",
},
.{
.name = "rope_config",
.path = "core/rope_config.zig",
.step = "test-rope-config",
.about = "A tower's RoPE keys: rope_parameters, the legacy rope_scaling and the top-level keys, read one way",
},
};

/// Each module's test step under `parent`, then the modules for every module the declared steps compile.
Expand Down
31 changes: 31 additions & 0 deletions zig/qwen35_rules_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,34 @@ test "qwen35 rules: every row and value through every entry point admits as main
try t.expectEqual(@as(usize, 6 * 6 * values.len), cases);
try t.expect(words > 0); // the refusals whose word the table changed (CUDA's, the 2B's, two of Metal's 27B)
}

/// `base` with `tie_word_embeddings` set (JSON) at the root and in `text_config`.
fn ties(a: std.mem.Allocator, base: []const u8, root: []const u8, tower: []const u8) ![]const u8 {
var doc = try std.json.parseFromSliceLeaky(std.json.Value, a, base, .{});
const key = "tie_word_embeddings";
try doc.object.put(a, key, try std.json.parseFromSliceLeaky(std.json.Value, a, root, .{}));
try doc.object.getPtr("text_config").?.object.put(a, key, try std.json.parseFromSliceLeaky(std.json.Value, a, tower, .{}));
return std.json.Stringify.valueAlloc(a, doc, .{});
}

test "qwen35 rules: CUDA's parse refuses a root and text_config tie that disagree, and a non-flag root" {
var arena: std.heap.ArenaAllocator = .init(t.allocator);
defer arena.deinit();
const a = arena.allocator();
const base = (try layers_host.bases(a))[1];
try t.expect(!(try cuda.parse(t.allocator, try ties(a, base, "false", "false"))).tied);
try t.expectError(error.BadTiedHead, cuda.parse(t.allocator, try ties(a, base, "true", "false")));
try t.expectError(error.BadTiedHead, cuda.parse(t.allocator, try ties(a, base, "false", "true")));
try t.expectError(error.BadTiedHead, cuda.parse(t.allocator, try ties(a, base, "\"yes\"", "false")));
}

test "qwen35 rules: Metal 27B's parse refuses a nested tie disagreement and a tie of 1 as BadTiedHead" {
var arena: std.heap.ArenaAllocator = .init(t.allocator);
defer arena.deinit();
const a = arena.allocator();
const base = (try layers_host.bases(a))[1];
_ = try metal27.parse(t.allocator, try ties(a, base, "false", "false"), null);
try t.expectError(error.BadTiedHead, metal27.parse(t.allocator, try ties(a, base, "true", "false"), null));
try t.expectError(error.BadTiedHead, metal27.parse(t.allocator, try ties(a, base, "false", "true"), null));
try t.expectError(error.BadTiedHead, metal27.parse(t.allocator, try ties(a, base, "false", "1"), null));
}
59 changes: 54 additions & 5 deletions zig/src/core/qwen35_rules.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
const std = @import("std");

/// One word per refusal, the same on every backend.
pub const Error = error{ UnsupportedActivation, UnsupportedAttentionGate, UnsupportedStateType };
pub const Error = error{ UnsupportedActivation, UnsupportedAttentionGate, UnsupportedStateType, BadTiedHead };

/// The config entry points that read the rows: CUDA, Metal's 27B (`qwen27`), Metal's 2B, HIP.
pub const Backend = enum { cuda, metal27, metal2b, hip };
Expand All @@ -25,7 +25,18 @@ pub const Want = union(enum) {
};

/// Each backend's reading of one row.
pub const Columns = struct { cuda: Read, metal27: Read, metal2b: Read, hip: Read };
pub const Columns = struct {
cuda: Read,
metal27: Read,
metal2b: Read,
hip: Read,

pub fn by(c: Columns, b: Backend) Read {
return switch (b) {
inline else => |t| @field(c, @tagName(t)),
};
}
};

/// A key, the value the kernels compute, the refusal when the tower declares another, and who reads it.
pub const Row = struct {
Expand All @@ -35,9 +46,7 @@ pub const Row = struct {
read: Columns,

pub fn by(r: Row, b: Backend) Read {
return switch (b) {
inline else => |t| @field(r.read, @tagName(t)),
};
return r.read.by(b);
}
};

Expand Down Expand Up @@ -99,6 +108,24 @@ pub fn check(tower: std.json.ObjectMap, b: Backend) Error!void {
}
}

/// `tie_word_embeddings`: the Metal 2B requires it in `text_config`; the others read it where present.
pub const tie_read: Columns = .{ .cuda = .optional, .metal27 = .optional, .metal2b = .required, .hip = .optional };

/// The head is the embedding: the tower's key, else the root's, else untied; a non-flag or a disagreement is refused.
pub fn tied(root: std.json.ObjectMap, tower: std.json.ObjectMap, b: Backend) Error!bool {
const inner = try tie(tower.get("tie_word_embeddings"), b);
const outer = try tie(root.get("tie_word_embeddings"), b);
if (inner == null and tie_read.by(b) == .required) return error.BadTiedHead;
if (inner != null and outer != null and inner.? != outer.?) return error.BadTiedHead;
return inner orelse outer orelse false;
}

fn tie(v: ?std.json.Value, b: Backend) Error!?bool {
const x = v orelse return null;
for ([_]bool{ false, true }) |f| if ((Want{ .flag = f }).holds(x, numericFlags(b))) return f;
return error.BadTiedHead;
}

fn parsed(a: std.mem.Allocator, text: []const u8) !std.json.ObjectMap {
return (try std.json.parseFromSliceLeaky(std.json.Value, a, text, .{})).object;
}
Expand Down Expand Up @@ -144,3 +171,25 @@ test "qwen35 rules: an empty tower passes where no row is required; 0 and 1 coun
const null_gate = "{\"attn_output_gate\":null}";
try std.testing.expectError(error.UnsupportedAttentionGate, check(try parsed(a, null_gate), .hip));
}

test "qwen35 rules: the tied head reads text_config, then the root, untied when absent; a disagreement is refused" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const none = try parsed(a, "{}");
const yes = try parsed(a, "{\"tie_word_embeddings\":true}");
const no = try parsed(a, "{\"tie_word_embeddings\":false}");
const one = try parsed(a, "{\"tie_word_embeddings\":1}");
for (std.enums.values(Backend)) |b| {
const needs = tie_read.by(b) == .required;
if (needs) try std.testing.expectError(error.BadTiedHead, tied(none, none, b)) else try std.testing.expect(!try tied(none, none, b));
if (needs) try std.testing.expectError(error.BadTiedHead, tied(yes, none, b)) else try std.testing.expect(try tied(yes, none, b));
try std.testing.expect(try tied(none, yes, b));
try std.testing.expect(!try tied(none, no, b));
try std.testing.expect(try tied(yes, yes, b));
try std.testing.expectError(error.BadTiedHead, tied(yes, no, b));
try std.testing.expectError(error.BadTiedHead, tied(no, yes, b));
if (numericFlags(b)) try std.testing.expect(try tied(none, one, b)) else try std.testing.expectError(error.BadTiedHead, tied(none, one, b));
try std.testing.expectError(error.BadTiedHead, tied(none, try parsed(a, "{\"tie_word_embeddings\":null}"), b));
}
}
134 changes: 134 additions & 0 deletions zig/src/core/rope_config.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
//! A tower's RoPE keys, read one way: `rope_parameters`, the legacy `rope_scaling`, and the top-level keys behind them.
const std = @import("std");
const ObjectMap = std.json.ObjectMap;

pub const Error = error{BadRopeConfig};

/// `rope_parameters`: null when absent or null; anything but an object is refused.
pub fn params(tower: ObjectMap) Error!?ObjectMap {
const v = tower.get("rope_parameters") orelse return null;
return switch (v) {
.null => null,
.object => |o| o,
else => error.BadRopeConfig,
};
}

/// The `rope_parameters` key naming a RoPE other than default (YaRN for one), or null.
pub fn typed(rope: ?ObjectMap) ?[]const u8 {
const r = rope orelse return null;
for ([_][2][]const u8{ .{ "rope_type", "rope_parameters.rope_type" }, .{ "type", "rope_parameters.type" } }) |k| if (r.get(k[0])) |v| {
if (v != .string or !std.mem.eql(u8, v.string, "default")) return k[1];
};
return null;
}

/// Whether the tower sets the legacy `rope_scaling`: transformers reads it as the config's `rope_parameters`.
pub fn legacy(tower: ObjectMap) bool {
const v = tower.get("rope_scaling") orelse return false;
return v != .null;
}

/// The key asking for scaled RoPE, in either form, or null for plain RoPE.
pub fn scaled(tower: ObjectMap, rope: ?ObjectMap) ?[]const u8 {
if (typed(rope)) |key| return key;
return if (legacy(tower)) "rope_scaling" else null;
}

/// Where `pick` looks: `rope_parameters` only, then the tower's top-level key, or the top-level key only when truthy.
pub const From = enum { params, both, truthy };

/// `key` from `rope_parameters`, else (per `from`) the tower's top-level key, else null; the caller converts it.
pub fn pick(rope: ?ObjectMap, tower: ObjectMap, key: []const u8, from: From) ?std.json.Value {
if (rope) |r| if (r.get(key)) |v| return v;
const v = switch (from) {
.params => return null,
.both, .truthy => tower.get(key) orelse return null,
};
return if (from == .truthy and !truthy(v)) null else v;
}

/// The block a scaled RoPE's parameters come from: a legacy `rope_scaling` object, else `rope_parameters`.
pub const Block = struct { map: ObjectMap, legacy: bool };

/// `rope_scaling` when it is an object, else `rope`; a `rope_scaling` neither null nor an object is refused.
pub fn block(tower: ObjectMap, rope: ObjectMap) Error!Block {
const v = tower.get("rope_scaling") orelse return .{ .map = rope, .legacy = false };
return switch (v) {
.null => .{ .map = rope, .legacy = false },
.object => |o| .{ .map = o, .legacy = true },
else => error.BadRopeConfig,
};
}

/// Python's truth of a JSON value.
fn truthy(v: std.json.Value) bool {
return switch (v) {
.null => false,
.bool => |b| b,
.integer => |i| i != 0,
.float => |f| f != 0,
.number_string, .string => |s| s.len != 0,
.array => |l| l.items.len != 0,
.object => |o| o.count() != 0,
};
}

fn parsed(a: std.mem.Allocator, text: []const u8) !ObjectMap {
return (try std.json.parseFromSliceLeaky(std.json.Value, a, text, .{})).object;
}

test "rope config: YaRN in either form is named by its key; default, absent and null are plain" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const cases = [_]struct { []const u8, ?[]const u8 }{
.{ "{}", null },
.{ "{\"rope_parameters\":null,\"rope_scaling\":null}", null },
.{ "{\"rope_parameters\":{\"rope_type\":\"default\",\"rope_theta\":1e7}}", null },
.{ "{\"rope_parameters\":{\"type\":\"default\"}}", null },
.{ "{\"rope_parameters\":{\"rope_type\":\"yarn\",\"factor\":4}}", "rope_parameters.rope_type" },
.{ "{\"rope_parameters\":{\"type\":\"yarn\"}}", "rope_parameters.type" },
.{ "{\"rope_parameters\":{\"rope_type\":4}}", "rope_parameters.rope_type" },
.{ "{\"rope_parameters\":{\"rope_type\":\"default\",\"type\":\"yarn\"}}", "rope_parameters.type" },
.{ "{\"rope_scaling\":{\"rope_type\":\"yarn\",\"factor\":4}}", "rope_scaling" },
.{ "{\"rope_scaling\":{\"type\":\"default\"}}", "rope_scaling" },
.{ "{\"rope_parameters\":{\"rope_type\":\"yarn\"},\"rope_scaling\":{\"type\":\"yarn\"}}", "rope_parameters.rope_type" },
};
for (cases) |c| {
const t = try parsed(a, c[0]);
const got = scaled(t, try params(t));
if (c[1]) |want| try std.testing.expectEqualStrings(want, got.?) else try std.testing.expectEqual(@as(?[]const u8, null), got);
}
try std.testing.expectError(error.BadRopeConfig, params(try parsed(a, "{\"rope_parameters\":4}")));
}

test "rope config: rope_parameters' key wins; the top-level key is read per From" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const both = try parsed(a, "{\"rope_theta\":5,\"rope_parameters\":{\"rope_theta\":7}}");
for (std.enums.values(From)) |f| try std.testing.expectEqual(@as(i64, 7), pick(try params(both), both, "rope_theta", f).?.integer);
const top = try parsed(a, "{\"rope_theta\":5,\"rope_parameters\":{}}");
try std.testing.expectEqual(@as(?std.json.Value, null), pick(try params(top), top, "rope_theta", .params));
try std.testing.expectEqual(@as(i64, 5), pick(try params(top), top, "rope_theta", .both).?.integer);
try std.testing.expectEqual(@as(i64, 5), pick(try params(top), top, "rope_theta", .truthy).?.integer);
const zero = try parsed(a, "{\"rope_theta\":0}");
try std.testing.expectEqual(@as(i64, 0), pick(null, zero, "rope_theta", .both).?.integer);
try std.testing.expectEqual(@as(?std.json.Value, null), pick(null, zero, "rope_theta", .truthy));
const held = try parsed(a, "{\"rope_parameters\":{\"rope_theta\":null}}");
try std.testing.expect(pick(try params(held), held, "rope_theta", .truthy).? == .null);
}

test "rope config: a legacy rope_scaling object is the block; null keeps rope_parameters; other values are refused" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const rope = try parsed(a, "{\"rope_type\":\"default\"}");
const old = try block(try parsed(a, "{\"rope_scaling\":{\"type\":\"yarn\"}}"), rope);
try std.testing.expect(old.legacy and old.map.get("type") != null);
const none = try block(try parsed(a, "{\"rope_scaling\":null}"), rope);
try std.testing.expect(!none.legacy and none.map.get("rope_type") != null);
try std.testing.expect(!(try block(try parsed(a, "{}"), rope)).legacy);
try std.testing.expectError(error.BadRopeConfig, block(try parsed(a, "{\"rope_scaling\":\"yarn\"}"), rope));
}
19 changes: 6 additions & 13 deletions zig/src/families/flashnext/config.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! FlashNext text dimensions and quantization declarations are checked before weight or cache allocation.
const std = @import("std");
const affine = @import("spec.zig");
const rope_config = @import("rope_config");

pub const Kind = enum { linear_attention, sparse_attention };
pub const Gate = enum { sigmoid, silu };
Expand Down Expand Up @@ -191,15 +192,6 @@ fn quantBlock(root: std.json.ObjectMap, text: std.json.ObjectMap) !std.json.Obje
return error.MissingAffineConfig;
}

/// The key asking for a RoPE other than plain (`--context` sets Metal's YaRN factor, never the config), or null.
fn scaledRope(text: std.json.ObjectMap, rope: std.json.ObjectMap) ?[]const u8 {
for ([_][2][]const u8{ .{ "rope_type", "rope_parameters.rope_type" }, .{ "type", "rope_parameters.type" } }) |k| if (rope.get(k[0])) |v| {
if (v != .string or !std.mem.eql(u8, v.string, "default")) return k[1];
};
if (text.get("rope_scaling")) |v| if (v != .null) return "rope_scaling";
return null;
}

pub fn parse(gpa: std.mem.Allocator, bytes: []const u8) !Config {
var parsed = try std.json.parseFromSlice(std.json.Value, gpa, bytes, .{});
errdefer parsed.deinit();
Expand All @@ -209,15 +201,16 @@ pub fn parse(gpa: std.mem.Allocator, bytes: []const u8) !Config {
if (tag != .string or !std.mem.eql(u8, tag.string, "qwen4_exp")) return error.NotFlashNext;
const quant = try quantBlock(root, text);
if (quant.get("quant_method")) |v| if (v != .null and (v != .string or (!std.mem.eql(u8, v.string, "mlx") and !std.mem.eql(u8, v.string, "affine")))) return error.UnsupportedAffineMode;
const rope = if (text.get("rope_parameters")) |v| if (v == .null) std.json.ObjectMap.empty else try object(v) else std.json.ObjectMap.empty;
if (scaledRope(text, rope)) |key| {
const rope = (rope_config.params(text) catch return error.InvalidFlashConfig) orelse std.json.ObjectMap.empty;
// `--context` sets Metal's YaRN factor, never the config
if (rope_config.scaled(text, rope)) |key| {
std.log.warn("Flash Next config.json: {s} asks for scaled RoPE (YaRN); this reader runs plain RoPE", .{key});
return error.UnsupportedFlashRope;
}
const hidden = try required(text, "hidden_size");
const heads = try required(text, "num_attention_heads");
const head_dim = if (text.get("head_dim")) |v| if (v == .null or (v == .integer and v.integer == 0)) hidden / heads else try integer(v) else hidden / heads;
const partial = try number(rope.get("partial_rotary_factor") orelse text.get("partial_rotary_factor") orelse .{ .float = 0.25 });
const partial = try number(rope_config.pick(rope, text, "partial_rotary_factor", .both) orelse .{ .float = 0.25 });
if (partial < 0 or partial > 1 or head_dim == 0) return error.UnsupportedFlashRope;
const gate: std.json.Value = text.get("output_gate_type") orelse .{ .string = "sigmoid" };
if (gate != .string) return error.UnsupportedFlashGate;
Expand All @@ -233,7 +226,7 @@ pub fn parse(gpa: std.mem.Allocator, bytes: []const u8) !Config {
.kv_heads = try required(text, "num_key_value_heads"),
.head_dim = head_dim,
.rotary_dim = @intFromFloat(@as(f64, @floatFromInt(head_dim)) * partial),
.rope_theta = try number(rope.get("rope_theta") orelse .{ .float = 10_000_000 }),
.rope_theta = try number(rope_config.pick(rope, text, "rope_theta", .params) orelse .{ .float = 10_000_000 }),
.key_heads = try required(text, "linear_num_key_heads"),
.value_heads = try required(text, "linear_num_value_heads"),
.key_dim = try required(text, "linear_key_head_dim"),
Expand Down
Loading
Loading