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

## Unreleased

- Inkling 2 CUDA attention contract tests now plant non-finite values at masked keys and record the known NaN finding for all four launches (#6255).

- fix(mlx_tf): refuse mis-shaped request bodies instead of panicking (#6510). Thanks to @joshuaswarren.

- Update Inkling 2 Small test fixtures to revision 885d78bf with log_scaling_n_floor 8192 (#6215).

- XPU Qwen3.8-27B: `/v1/completions` prompts now keep their last 64-row start in the prompt cache, as chat turns and the CUDA and HIP stores already do, so a repeated or extended completion resumes instead of prefilling from token 0, with the same tokens as a fresh pass (#6211).
- CI: the nightly macOS deferred leg now runs seven Mac host steps that no leg ran, plus mlx_tf's own unit tests as `test-mlx-tf-unit`; mlx_tf's build configures again after its `test-filter` option was declared twice (#6525).

Expand Down
2 changes: 1 addition & 1 deletion THIRD_PARTY_NOTICES.md
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,7 @@ and ZWJ/ZWNJ conjuncts after it are TensorFold's own.
## Inkling 2 Small test fixtures

`zig/src/families/inkling2/fixtures/` holds files and values taken from Thinking Machines' Inkling 2 Small release at
revision `2ad1157016e1aac77b6ff1b770e7c05229403134`, under the Apache License 2.0 stated on its model card (see
revision `885d78bfca61a7e9a498e33cfa7ad35850533b8c`, under the Apache License 2.0 stated on its model card (see
[the license text](LICENSES/Apache-2.0.txt)): `config.json`, `chat_template.jinja`, `mini_tokenizer.json` (its
`tokenizer.json` cut to the added tokens, the byte alphabet and the first 1,500 merges) and the prompts and ids in
`prompt_cases.json` and `mini_cases.json`, which the Hugging Face transformers and tokenizers libraries produced from
Expand Down
6 changes: 6 additions & 0 deletions docs/kernel-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,12 @@ for a row whose tile or block reads a non-finite value at a key masked for that
`gemma_decode_attention` for a decode row whose 32-key step reads one: P = 0 times Inf inside the P x V mma, where
float64 leaves the masked key out. These were seen on the M5, where their cases run. Each kernel has an entry of its own
that plants such a value and carries the finding, so its other entries keep a clean gate 1.
Inkling 2's CUDA attention (#4125: `tf_ink2_attn`, `tf_ink2_attn_fold`, the split launch and `tf_ink2_attn_prompt`)
gives NaN the same way for a row whose block loads a non-finite value at a key that row masks, a later row's key or, on
a sliding layer, a key below its window, inside the key range its merge reads: the NaN lands in the row's outputs at
that value's column and at no other, where float64 leaves the key out (P = 0 times Inf inside the P x V mma). Seen on a
GB10. Each launch has an entry of its own that plants such values and carries the finding, so its other entries keep a
clean gate 1.
Hy4-flash's `tf_hy4_attend_chunks` and `tf_hy4_attend_scored` give NaN for a row and head whose 512-key chunk starts
with a -Inf score, where float64 leaves that key out: the running max is still -Inf there, so the first rescale is
exp(-Inf - -Inf). Its `tf_hy4_attend_nax` gives NaN for a row whose 32-key tile reads a non-finite value at a key it
Expand Down
10 changes: 10 additions & 0 deletions engines/mlx_tf/build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,19 @@ pub fn build(b: *std.Build) void {
const config_parse_step = b.step("test-config-parse-host", "Check config.json arch selection and model_type refusal without Metal");
config_parse_step.dependOn(&b.addRunArtifact(config_parse_test).step);

const request_shape_test = b.addTest(.{ .root_module = b.createModule(.{
.root_source_file = b.path("src/server_request_shape_test.zig"),
.target = b.graph.host,
.optimize = .Debug,
.link_libc = true,
}), .filters = &.{} });
const request_shape_step = b.step("test-request-shape-host", "Check HTTP request-shape refusals without Metal");
request_shape_step.dependOn(&b.addRunArtifact(request_shape_test).step);

const test_step = b.step("test", "Run unit tests");
test_step.dependOn(vision_step);
test_step.dependOn(config_parse_step);
test_step.dependOn(request_shape_step);
const ergo_ref = b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{
.root_source_file = b.path("src/ergo_ref_test.zig"),
.target = b.graph.host,
Expand Down
16 changes: 14 additions & 2 deletions engines/mlx_tf/src/server_completion.zig
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,26 @@ const sendError = server.sendError;
const sendJson = server.sendJson;
const writeAll = server.writeAll;
const qwen4 = @import("server_qwen4.zig");
const shape = @import("server_request_shape.zig");

pub const handleCompletion = Methods.handleCompletion;

pub const Methods = struct {
pub fn handleCompletion(self: *ServerEngine, fd: c_int, body: []const u8, is_chat: bool) !void {
const parsed = try std.json.parseFromSlice(std.json.Value, self.a, body, .{});
const parsed = std.json.parseFromSlice(std.json.Value, self.a, body, .{}) catch {
sendError(fd, 400, "invalid_request_error", "invalid JSON body");
return;
};
defer parsed.deinit();
if (parsed.value != .object) {
sendError(fd, 400, "invalid_request_error", "JSON body must be an object");
return;
}
const obj = parsed.value.object;
if (shape.checkCompletion(obj, is_chat)) |msg| {
sendError(fd, 400, "invalid_request_error", msg);
return;
}
if (self.qwen4) |q| {
if (qwen4.check(obj, self.model_name, is_chat)) |refusal|
return sendError(fd, refusal.status, if (refusal.status == 404) "model_not_found" else "invalid_request_error", refusal.message);
Expand All @@ -47,7 +59,7 @@ pub const Methods = struct {
const sampling = samp_mod.SamplingParams{
.temperature = getJsonF32(obj, "temperature", 0.0),
.top_p = getJsonF32(obj, "top_p", 1.0),
.top_k = @intCast(getJsonUsize(obj, "top_k", 0)),
.top_k = shape.getJsonU32(obj, "top_k", 0),
.min_p = getJsonF32(obj, "min_p", 0.0),
.seed = @intCast(getJsonUsize(obj, "seed", 42)),
.repetition_penalty = if (rep_pen > 0.0) rep_pen else 1.0,
Expand Down
71 changes: 71 additions & 0 deletions engines/mlx_tf/src/server_request_shape.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
//! Request-shape gates for the HTTP handlers: everything the completion and
//! stream-parallel paths dereference is checked here, before any union-field access —
//! the same posture server_qwen4.zig's `check` gives the Qwen4 route, and the same 400s
//! vulkan_tf's request layer serves. Presence checks stay in the handlers where they
//! already are; these only refuse shapes that would panic downstream.
const std = @import("std");

/// A message to send back as `400 invalid_request_error`, or null when the shape is fine.
pub const Refusal = []const u8;

/// u32 sampling fields clamp instead of panicking on wider JSON integers (vulkan parity).
pub fn getJsonU32(obj: std.json.ObjectMap, key: []const u8, fallback: u32) u32 {
const v = obj.get(key) orelse return fallback;
return switch (v) {
.integer => |i| if (i < 0) fallback else std.math.cast(u32, i) orelse std.math.maxInt(u32),
else => fallback,
};
}

/// Every message must be an object carrying a string `role`; content stays free-form.
fn checkMessages(val: std.json.Value, missing_array: Refusal, not_object: Refusal, no_role: Refusal, bad_role: Refusal) ?Refusal {
if (val != .array) return missing_array;
for (val.array.items) |item| {
if (item != .object) return not_object;
const role = item.object.get("role") orelse return no_role;
if (role != .string) return bad_role;
}
return null;
}

/// What /v1/chat/completions and /v1/completions dereference: `messages` (chat) and
/// `prompt` (completion), checked only when present — absence keeps the handler's own 400.
pub fn checkCompletion(obj: std.json.ObjectMap, is_chat: bool) ?Refusal {
if (is_chat) {
if (obj.get("messages")) |mv| {
return checkMessages(mv, "messages must be an array", "each message must be an object", "message missing role", "message role must be a string");
}
return null;
}
if (obj.get("prompt")) |pv| {
if (pv != .string) return "prompt must be a string";
}
return null;
}

/// What /v1/stream-parallel dereferences: `streams` plus the shared_/delta_ prompt fields.
pub fn checkStreamParallel(obj: std.json.ObjectMap) ?Refusal {
if (obj.get("shared_messages")) |sm| {
if (checkMessages(sm, "shared_messages must be an array", "each shared message must be an object", "shared message missing role", "shared message role must be a string")) |r| return r;
}
if (obj.get("shared_prompt")) |sp| {
if (sp != .string) return "shared_prompt must be a string";
}
if (obj.get("streams")) |sv| {
if (sv != .array) return "streams must be an array";
for (sv.array.items) |item| {
if (item != .object) return "each stream must be an object";
const so = item.object;
if (so.get("id")) |idv| {
if (idv != .string) return "stream id must be a string";
}
if (so.get("delta_messages")) |dm| {
if (checkMessages(dm, "delta_messages must be an array", "each delta message must be an object", "delta message missing role", "delta message role must be a string")) |r| return r;
}
if (so.get("delta_prompt")) |dp| {
if (dp != .string) return "delta_prompt must be a string";
}
}
}
return null;
}
86 changes: 86 additions & 0 deletions engines/mlx_tf/src/server_request_shape_test.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
//! Host tests for server_request_shape.zig: the request bodies mlx_tf's HTTP handlers
//! used to dereference unchecked — non-object payloads, mis-shaped messages/prompt/
//! streams fields, and u32-wider sampling numbers — now refuse 400-shaped refusals or
//! clamp, mirroring what vulkan_tf's request layer already serves.
const std = @import("std");
const shape = @import("server_request_shape.zig");

fn checkCompletion(json: []const u8, is_chat: bool) !?shape.Refusal {
const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json, .{});
defer parsed.deinit();
if (parsed.value != .object) return "JSON body must be an object";
return shape.checkCompletion(parsed.value.object, is_chat);
}

fn checkStream(json: []const u8) !?shape.Refusal {
const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, json, .{});
defer parsed.deinit();
if (parsed.value != .object) return "JSON body must be an object";
return shape.checkStreamParallel(parsed.value.object);
}

fn expectRefusal(want: []const u8, got: ?shape.Refusal) !void {
try std.testing.expect(got != null);
try std.testing.expectEqualStrings(want, got.?);
}

test "chat: mis-shaped messages refuse instead of dereferencing" {
try expectRefusal("messages must be an array", try checkCompletion("{\"messages\":\"x\"}", true));
try expectRefusal("messages must be an array", try checkCompletion("{\"messages\":5}", true));
try expectRefusal("each message must be an object", try checkCompletion("{\"messages\":[\"x\"]}", true));
try expectRefusal("each message must be an object", try checkCompletion("{\"messages\":[5]}", true));
try expectRefusal("message missing role", try checkCompletion("{\"messages\":[{}]}", true));
try expectRefusal("message role must be a string", try checkCompletion("{\"messages\":[{\"role\":5}]}", true));
try expectRefusal("message role must be a string", try checkCompletion("{\"messages\":[{\"role\":null}]}", true));
// an absent messages field keeps the handler's own missing-messages 400
try std.testing.expect((try checkCompletion("{}", true)) == null);
// tolerated shapes stay tolerated: missing content, array content with non-text parts
try std.testing.expect((try checkCompletion("{\"messages\":[{\"role\":\"user\"}]}", true)) == null);
try std.testing.expect((try checkCompletion("{\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}]}", true)) == null);
try std.testing.expect((try checkCompletion("{\"messages\":[{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"hi\"},5]}]}", true)) == null);
}

test "completion: a non-string prompt refuses; a missing one keeps the handler's 400" {
try expectRefusal("prompt must be a string", try checkCompletion("{\"prompt\":5}", false));
try expectRefusal("prompt must be a string", try checkCompletion("{\"prompt\":[\"a\"]}", false));
try expectRefusal("prompt must be a string", try checkCompletion("{\"prompt\":null}", false));
try std.testing.expect((try checkCompletion("{\"prompt\":\"The capital\"}", false)) == null);
try std.testing.expect((try checkCompletion("{}", false)) == null);
}

test "stream-parallel: mis-shaped streams refuse instead of dereferencing" {
try expectRefusal("streams must be an array", try checkStream("{\"streams\":\"x\"}"));
try expectRefusal("streams must be an array", try checkStream("{\"streams\":5}"));
try expectRefusal("each stream must be an object", try checkStream("{\"streams\":[5]}"));
try expectRefusal("stream id must be a string", try checkStream("{\"streams\":[{\"id\":5,\"delta_prompt\":\"x\"}]}"));
try expectRefusal("delta_prompt must be a string", try checkStream("{\"streams\":[{\"delta_prompt\":5}]}"));
try expectRefusal("delta_messages must be an array", try checkStream("{\"streams\":[{\"delta_messages\":\"x\"}]}"));
try expectRefusal("each delta message must be an object", try checkStream("{\"streams\":[{\"delta_messages\":[5]}]}"));
try expectRefusal("delta message missing role", try checkStream("{\"streams\":[{\"delta_messages\":[{}]}]}"));
try expectRefusal("delta message role must be a string", try checkStream("{\"streams\":[{\"delta_messages\":[{\"role\":5}]}]}"));
// absent streams keeps the handler's own missing-streams 400
try std.testing.expect((try checkStream("{}")) == null);
try std.testing.expect((try checkStream("{\"streams\":[{\"delta_prompt\":\"hi\"}]}")) == null);
try std.testing.expect((try checkStream("{\"streams\":[{\"id\":\"s1\",\"delta_messages\":[{\"role\":\"user\",\"content\":\"hi\"}]}]}")) == null);
}

test "stream-parallel: mis-shaped shared fields refuse" {
try expectRefusal("shared_messages must be an array", try checkStream("{\"shared_messages\":\"x\",\"streams\":[{\"delta_prompt\":\"x\"}]}"));
try expectRefusal("each shared message must be an object", try checkStream("{\"shared_messages\":[5]}"));
try expectRefusal("shared message missing role", try checkStream("{\"shared_messages\":[{}]}"));
try expectRefusal("shared message role must be a string", try checkStream("{\"shared_messages\":[{\"role\":5}]}"));
try expectRefusal("shared_prompt must be a string", try checkStream("{\"shared_prompt\":5}"));
try std.testing.expect((try checkStream("{\"shared_prompt\":\"intro\",\"shared_messages\":[{\"role\":\"system\",\"content\":\"s\"}]}")) == null);
}

test "numbers wider than u32 clamp; wrong types, negatives and absence fall back" {
const a = std.testing.allocator;
const parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"top_k\":5000000000,\"seed\":42,\"sketchy\":\"x\",\"neg\":-5}", .{});
defer parsed.deinit();
const o = parsed.value.object;
try std.testing.expectEqual(std.math.maxInt(u32), shape.getJsonU32(o, "top_k", 0));
try std.testing.expectEqual(@as(u32, 42), shape.getJsonU32(o, "seed", 0));
try std.testing.expectEqual(@as(u32, 7), shape.getJsonU32(o, "sketchy", 7));
try std.testing.expectEqual(@as(u32, 3), shape.getJsonU32(o, "neg", 3));
try std.testing.expectEqual(@as(u32, 9), shape.getJsonU32(o, "absent", 9));
}
16 changes: 14 additions & 2 deletions engines/mlx_tf/src/server_stream.zig
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,26 @@ const getJsonUsize = server.getJsonUsize;
const sendError = server.sendError;
const sendJson = server.sendJson;
const writeAll = server.writeAll;
const shape = @import("server_request_shape.zig");

pub const handleStreamParallel = Methods.handleStreamParallel;

pub const Methods = struct {
pub fn handleStreamParallel(self: *ServerEngine, fd: c_int, body: []const u8) !void {
const parsed = try std.json.parseFromSlice(std.json.Value, self.a, body, .{});
const parsed = std.json.parseFromSlice(std.json.Value, self.a, body, .{}) catch {
sendError(fd, 400, "invalid_request_error", "invalid JSON body");
return;
};
defer parsed.deinit();
if (parsed.value != .object) {
sendError(fd, 400, "invalid_request_error", "JSON body must be an object");
return;
}
const obj = parsed.value.object;
if (shape.checkStreamParallel(obj)) |msg| {
sendError(fd, 400, "invalid_request_error", msg);
return;
}

const stream_sse = getJsonBool(obj, "stream", false);
const enable_thinking = getJsonBool(obj, "enable_thinking", false);
Expand Down Expand Up @@ -88,7 +100,7 @@ pub const Methods = struct {
.sampling = .{
.temperature = getJsonF32(so, "temperature", default_temp),
.top_p = getJsonF32(so, "top_p", 1.0),
.top_k = @intCast(getJsonUsize(so, "top_k", 0)),
.top_k = shape.getJsonU32(so, "top_k", 0),
.min_p = getJsonF32(so, "min_p", 0.0),
.seed = @intCast(getJsonUsize(so, "seed", 42 + i)),
},
Expand Down
1 change: 1 addition & 0 deletions lines/6509.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- mlx_tf: a malformed request body to `/v1/chat/completions`, `/v1/completions` or `/v1/stream-parallel` now gets a `400 invalid_request_error` instead of panicking the server — non-object bodies, mis-shaped `messages`/`prompt`/`streams`/`shared_*`/`delta_*` fields are refused, and `top_k` wider than u32 clamps, the way `vulkan_tf`'s request layer already behaves (#6509).
2 changes: 1 addition & 1 deletion tools/zig/inkling2_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

ROOT = Path(__file__).resolve().parents[2]
FIXTURES = ROOT / "zig/src/families/inkling2/fixtures"
RELEASE = "thinkingmachines/Inkling-2-Small@2ad1157016e1aac77b6ff1b770e7c05229403134"
RELEASE = "thinkingmachines/Inkling-2-Small@885d78bfca61a7e9a498e33cfa7ad35850533b8c"
TINY = "tiny-random/inkling-2@0a57c72e4e5b68aafe1d983dbb62980344a5fcd7"
TINY_MINI = "hf-internal-testing/tiny-inkling2-mini@ee242a48af34ff0729518f4ac28cfcb847e470ab"
MINI_RELEASE = "thinkingmachines/Inkling-2-Mini"
Expand Down
Loading
Loading