diff --git a/CHANGELOG.md b/CHANGELOG.md index 882af41cc98..fd1b3086efe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Flash Next on Metal: 6- and 8-bit row products at 2 to 4 rows take two outputs a simdgroup instead of four, so a 2,560 x 6,144 product at 2 rows takes 25% less time on an M3 Ultra; served decode is 2.4-6.0% faster with every token hash equal to main's (#2593, fixes #2553). Thanks to @abm9111. + +- Flash Next on Metal: a prompt chunk's staggered segments wait until the first queue reaches the chunk, so after idle, when macOS has unwired the model, a later segment no longer sits in a GPU wait past macOS's limit and fails the request with HTTP 500; warm, nothing waits (#2594, fixes #2552). Thanks to @abm9111. + +- Conformance: a Qwen3.8-27B Metal profile (`tools/conformance_profiles/qwen27-metal.json`, MLX 4-bit with its DFlash2 drafter), and a profile key `fresh_env` the kit sets only on the cache-off servers it starts, so the resumed gate gets a fresh side on Metal, where a stream resumes its own last chat (#2612, refs #2460). Thanks to @jschmied. + +- Sampling: Qwen 3.5's host draw over a bf16 logits row (a reply's first token and every grammar-masked row on CUDA, every draw on Metal) moves unchanged into `core/lanes` as `sampling_row`, the first step to one sampler; token ids equal main's on 64 of 64 greedy, sampled and JSON-schema requests (#2606, part of #2460). Thanks to @jschmied. + +- Internal: GLM's CUDA SwiGLU rows move into their own header (`glm_swiglu.cuh`) with a template for the clip after silu that Ling will use; GLM's machine code is the same on all five SMs (#2627, part of #850). Thanks to @ajensenwaud. + - KV pool: a pool's stores join an ordered chain of reclaim hooks, asked in join order until enough pages are free, and one lane host counts a pool, a second refused; every load keeps its one store and its calls, so nothing changes yet (#2528, part of #2444). Thanks to @jschmied. - Configuration: an empty or whitespace-only `TF_KV_SHARE` (GLM, Gemma 4, Kolibri-1, Spark2.5 and Dory), `TF_QWEN_KV_SHARE` or `TF_QWEN_KV_PAGES` now means unset instead of stopping the start, and GLM's empty or whitespace-only `TF_KV_PAGES` means `auto` instead of `on`, which paged a single GPU and was refused with `--kv-cache fp8`, as `docs/environment.md` says of every variable; so at TP=1 a blank `TF_KV_PAGES` with `TF_KV_SHARE` or `TF_GLM_KV_HOST=1` is refused by name, as an unset one is (#2629, refs #2591). Thanks to @Bizuayeu. diff --git a/tools/conformance.py b/tools/conformance.py index e9cb01cc363..409aaf73202 100644 --- a/tools/conformance.py +++ b/tools/conformance.py @@ -12,6 +12,9 @@ - resumed: a multi-turn chat on the cached server equals the same chat on a server with the prompt cache off; the fresh side must report ``cached_tokens == 0`` and every later resumed turn ``cached_tokens > 0``. A profile's ``conversation_context_items`` puts a long document in the first turn, for families that keep only long prompts. + A profile's ``fresh_env`` is set on every server started with ``--prompt-cache-gib 0``, for families whose streams + resume their own last chat without the prompt cache (``TF_QWEN27_SLOT_RESUME=0`` on Metal); with ``--fresh-url``, + start that server with it yourself. - refusals: each named request the profile lists is refused with its status and error text. ``--binary`` starts the servers itself (the cache-off one first, then the cached one), one at a time, from the @@ -30,6 +33,7 @@ import argparse import hashlib import json +import os import re import socket import subprocess @@ -345,6 +349,11 @@ def command(self, port: int) -> list: return [str(self.args.binary), "serve", str(self.args.model_dir), "--host", "127.0.0.1", "--port", str(port), "--name", self.profile["name"], "--no-update-check", "--prompt-cache-gib", str(self.cache_gib), *flags] + def env(self) -> dict: + """The inherited environment, plus the profile's ``fresh_env`` on a server that keeps no prompts.""" + extra = self.profile.get("fresh_env", {}) if self.cache_gib == 0 else {} + return {**os.environ, **{k: str(v) for k, v in extra.items()}} + def __enter__(self): if self.args.before_start: subprocess.run(self.args.before_start, shell=True, check=True, timeout=600) @@ -356,7 +365,8 @@ def __enter__(self): self.log = tempfile.NamedTemporaryFile("w+b", prefix=f"server-cache{self.cache_gib}-", suffix=".log", dir=self.logs, delete=False) print("START " + " ".join(self.cmd), flush=True) - self.process = subprocess.Popen(self.cmd, stdout=self.log, stderr=subprocess.STDOUT, start_new_session=True) + self.process = subprocess.Popen(self.cmd, stdout=self.log, stderr=subprocess.STDOUT, start_new_session=True, + env=self.env()) deadline = time.monotonic() + self.args.start_timeout while time.monotonic() < deadline: if self.process.poll() is not None: diff --git a/tools/conformance_profiles/qwen27-metal.json b/tools/conformance_profiles/qwen27-metal.json new file mode 100644 index 00000000000..64bf6ddbdc2 --- /dev/null +++ b/tools/conformance_profiles/qwen27-metal.json @@ -0,0 +1,78 @@ +{ + "name": "qwen27-metal", + "family": "qwen3_5 on Metal", + "checkpoint": "Qwen3.8-27B MLX affine 4-bit with its DFlash2 drafter; one stream at a 4096-token context is what 36 GB fits beside both", + "serve": [ + "--context", + "4096", + "--parallel", + "1", + "--no-thinking", + "--drafter", + "{drafter}" + ], + "sampled": { + "temperature": 0.8, + "top_p": 0.95, + "top_k": 20 + }, + "tokens": 64, + "seed": 7, + "levels": [ + 1, + 2, + 3 + ], + "prompt_cache_gib": 2, + "ignore_eos": true, + "prompts": { + "poem": "Write a short poem about the sea.", + "primes": "List the first twelve prime numbers, separated by commas.", + "sky": "Explain in two sentences why the sky is blue.", + "count": "Count from one to thirty in words.", + "copy": "Repeat exactly: The harbor lights came on one by one as the fishing boats returned to the quay." + }, + "long_items": 500, + "conversation": [ + "Name three rivers in Europe and one fact about each.", + "Now give the length of each river in kilometres.", + "Which of them is the longest? Answer in one sentence." + ], + "refusals": [ + { + "name": "n_two", + "body": { + "n": 2 + }, + "status": 400, + "error": "n must be 1; multiple choices are not supported" + }, + { + "name": "top_logprobs_without_logprobs", + "body": { + "top_logprobs": 3 + }, + "status": 400, + "error": "top_logprobs requires logprobs: true" + }, + { + "name": "presence_penalty_out_of_range", + "body": { + "presence_penalty": 3 + }, + "status": 400, + "error": "presence_penalty must be between -2 and 2, or null" + }, + { + "name": "reply_past_context", + "body": { + "max_tokens": 10000000 + }, + "status": 400, + "error": "This server's maximum context length is" + } + ], + "fresh_env": { + "TF_QWEN27_SLOT_RESUME": "0" + } +} diff --git a/tools/tests/test_bench_conformance.py b/tools/tests/test_bench_conformance.py index 08a157d5bcd..f1a64f6a84c 100644 --- a/tools/tests/test_bench_conformance.py +++ b/tools/tests/test_bench_conformance.py @@ -194,6 +194,13 @@ def post(self, body): self.assertTrue(sent[0][0]["content"].startswith(conformance.inventory(50))) self.assertTrue(all(m["content"] == t for m, t in zip(sent[-1][2::2], profile["conversation"][1:]))) + def test_fresh_env_reaches_only_servers_keeping_no_prompts(self): + profile = {"name": "p", "fresh_env": {"TF_QWEN27_SLOT_RESUME": 0}} + fresh, cached = (conformance.Server(None, profile, gib, Path(".")).env() for gib in (0, 2)) + self.assertEqual(fresh["TF_QWEN27_SLOT_RESUME"], "0") + self.assertEqual(cached, dict(conformance.os.environ)) + self.assertEqual(conformance.Server(None, {"name": "p"}, 0, Path(".")).env(), dict(conformance.os.environ)) + def test_profiles_parse_and_name_their_gates(self): for path in sorted(PROFILE.parent.glob("*.json")): with self.subTest(profile=path.name): @@ -202,6 +209,7 @@ def test_profiles_parse_and_name_their_gates(self): self.assertTrue(profile["refusals"]) self.assertTrue(all(r["name"] and r["error"] for r in profile["refusals"])) self.assertGreater(profile["sampled"]["temperature"], 0) + self.assertTrue(all(isinstance(v, str) for v in profile.get("fresh_env", {}).values())) if __name__ == "__main__": diff --git a/zig/build/metal_targets.zig b/zig/build/metal_targets.zig index 4e1619e4cfd..42125d6a3a4 100644 --- a/zig/build/metal_targets.zig +++ b/zig/build/metal_targets.zig @@ -338,6 +338,7 @@ pub fn metalTargets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: s .{ .name = "tf-flashnext-pack", .path = "zig/tests/flashnext_pack.zig", .about = "Flash Next's three weight packs built from a checkpoint, byte-compared with a Python dump" }, .{ .name = "tf-flashnext-think", .path = "zig/tests/flashnext_think.zig", .about = "Flash Next's verdict kernels under thinking budgets on a fake target, against the lane core's close" }, .{ .name = "tf-grid-sync-bench", .path = "zig/tests/grid_sync_bench.zig", .about = "A GPU-wide barrier in one persistent dispatch against dependent relaunches" }, + .{ .name = "tf-segments-probe", .path = "zig/tests/segments_probe.zig", .about = "A two-segment chunk behind a held first queue: the GPU watchdog without the probe, a pass with it" }, .{ .name = "tf-weight-read-check", .path = "zig/tests/weight_read_check.zig", .about = "Check native file reads and failed-read cleanup", .c_source = "zig/tests/pread_fault.c" }, .{ .name = "tf-glm-run", .path = "zig/tests/glm_run.zig", .about = "GLM-5.3-Flash greedy replies at each draft depth against depth 0 and reference tokens" }, .{ .name = "tf-glm-vision", .path = "zig/tests/glm_vision.zig", .about = "GLM-5.3-Flash's image tower on an image or a reference dump's patches, compared with the dump" }, diff --git a/zig/kernels/cuda/glm_glue_moe.cuh b/zig/kernels/cuda/glm_glue_moe.cuh index 7f2a27d6b03..682d5cf0332 100644 --- a/zig/kernels/cuda/glm_glue_moe.cuh +++ b/zig/kernels/cuda/glm_glue_moe.cuh @@ -1,60 +1,13 @@ -// GLM's MLP and MoE glue by hand: glue._swiglu, glue._topk and qmm._group_sums (the router's dot is glm_glue_router). +// GLM's MLP and MoE glue by hand: glue._topk and qmm._group_sums (SwiGLU: glm_swiglu.cuh; router dot: glm_glue_router). #pragma once #include "glm_triton.cuh" using namespace glm_triton; +#include "glm_swiglu.cuh" -namespace glm_moe { - -// A thread's S consecutive values summed from the second, then the butterfly over the 64 / S lanes of their group. -template -__device__ __forceinline__ float group64(const float* q) { - float g = q[0] + q[1]; - for (int j = 2; j < S; ++j) g = q[j] + g; - for (int o = 32 / S; o > 0; o >>= 1) g = g + __shfl_xor_sync(0xffffffffu, g, o); - return g; -} - -__device__ __forceinline__ float swiglu1(float g, float u, float limit) { - g = fminf(g, limit); - u = fminf(fmaxf(u, 0.0f - limit), limit); - const float s = rbf(div_full(g, exp_approx(0.0f - g) + 1.0f)); - return rbf(__fmul_rn(u, s)); -} - -} // namespace glm_moe - -// glue._swiglu with BLOCK 512 (128 threads, 4 values each, 64-group sums over 16 lanes), column block blockIdx.y. -extern "C" __global__ void __launch_bounds__(128) - tf_glm_swiglu_512(const __nv_bfloat16* gu, __nv_bfloat16* out, float* xs, float limit, int64_t w) { - const int64_t r = blockIdx.x, d0 = blockIdx.y * 512 + threadIdx.x * 4; - const uint2 gv = *reinterpret_cast(gu + r * 2 * w + d0); - const uint2 uv = *reinterpret_cast(gu + r * 2 * w + w + d0); - const __nv_bfloat16* gh = reinterpret_cast(&gv); - const __nv_bfloat16* uh = reinterpret_cast(&uv); - float a[4]; - uint2 ov; - __nv_bfloat16* oh = reinterpret_cast<__nv_bfloat16*>(&ov); - for (int j = 0; j < 4; ++j) { - a[j] = glm_moe::swiglu1(bf(gh[j]), bf(uh[j]), limit); - oh[j] = __float2bfloat16_rn(a[j]); - } - *reinterpret_cast(out + r * w + d0) = ov; - const float g = glm_moe::group64<4>(a); - if ((threadIdx.x & 15) == 0) xs[r * (w / 64) + d0 / 64] = g; -} - -// glue._swiglu with BLOCK 64 (the TP=3 shared expert's 704): one value a thread, the warp's butterfly, then 2 warps. -extern "C" __global__ void __launch_bounds__(64) - tf_glm_swiglu_64(const __nv_bfloat16* gu, __nv_bfloat16* out, float* xs, float limit, int64_t w) { - __shared__ float smem[2]; - const int64_t r = blockIdx.x, d = blockIdx.y * 64 + threadIdx.x; - const float a = glm_moe::swiglu1(bf(gu[r * 2 * w + d]), bf(gu[r * 2 * w + w + d]), limit); - out[r * w + d] = __float2bfloat16_rn(a); - const float g = block_sum<2>(a, smem); - if (threadIdx.x == 0) xs[r * (w / 64) + blockIdx.y] = g; -} +TF_GLM_SWIGLU_512(tf_glm_swiglu_512, false) +TF_GLM_SWIGLU_64(tf_glm_swiglu_64, false) // qmm._group_sums: row blockIdx.x's 64-input sums, 8 lanes a group of 8 consecutive inputs each, 16 groups a block. extern "C" __global__ void __launch_bounds__(128) diff --git a/zig/kernels/cuda/glm_swiglu.cuh b/zig/kernels/cuda/glm_swiglu.cuh new file mode 100644 index 00000000000..a6c60f72060 --- /dev/null +++ b/zig/kernels/cuda/glm_swiglu.cuh @@ -0,0 +1,63 @@ +// glue._swiglu's rows by hand: silu with the clamp before it (GLM) or after it (Ling), and the 64-value group sums. +#pragma once + +#include "glm_triton.cuh" + +using namespace glm_triton; + +namespace glm_moe { + +// A thread's S consecutive values summed from the second, then the butterfly over the 64 / S lanes of their group. +template +__device__ __forceinline__ float group64(const float* q) { + float g = q[0] + q[1]; + for (int j = 2; j < S; ++j) g = q[j] + g; + for (int o = 32 / S; o > 0; o >>= 1) g = g + __shfl_xor_sync(0xffffffffu, g, o); + return g; +} + +// AFTER false: GLM's silu(min(g, L)); true: Ling's min(silu(g), L), the gate clipped after silu. Both clip u. +template +__device__ __forceinline__ float swiglu1(float g, float u, float limit) { + if (!AFTER) g = fminf(g, limit); + if (AFTER) u = u > limit ? limit : (u < 0.0f - limit ? 0.0f - limit : u); // a NaN u stays NaN + else u = fminf(fmaxf(u, 0.0f - limit), limit); + float s = rbf(div_full(g, exp_approx(0.0f - g) + 1.0f)); + if (AFTER) s = s > limit ? limit : s; + return rbf(__fmul_rn(u, s)); +} + +} // namespace glm_moe + +// glue._swiglu with BLOCK 512 (128 threads, 4 values each, 64-group sums over 16 lanes), column block blockIdx.y. +#define TF_GLM_SWIGLU_512(NAME, AFTER) \ + extern "C" __global__ void __launch_bounds__(128) \ + NAME(const __nv_bfloat16* gu, __nv_bfloat16* out, float* xs, float limit, int64_t w) { \ + const int64_t r = blockIdx.x, d0 = blockIdx.y * 512 + threadIdx.x * 4; \ + const uint2 gv = *reinterpret_cast(gu + r * 2 * w + d0); \ + const uint2 uv = *reinterpret_cast(gu + r * 2 * w + w + d0); \ + const __nv_bfloat16* gh = reinterpret_cast(&gv); \ + const __nv_bfloat16* uh = reinterpret_cast(&uv); \ + float a[4]; \ + uint2 ov; \ + __nv_bfloat16* oh = reinterpret_cast<__nv_bfloat16*>(&ov); \ + for (int j = 0; j < 4; ++j) { \ + a[j] = glm_moe::swiglu1(bf(gh[j]), bf(uh[j]), limit); \ + oh[j] = __float2bfloat16_rn(a[j]); \ + } \ + *reinterpret_cast(out + r * w + d0) = ov; \ + const float g = glm_moe::group64<4>(a); \ + if ((threadIdx.x & 15) == 0) xs[r * (w / 64) + d0 / 64] = g; \ + } + +// glue._swiglu with BLOCK 64 (the TP=3 shared expert's 704): one value a thread, the warp's butterfly, then 2 warps. +#define TF_GLM_SWIGLU_64(NAME, AFTER) \ + extern "C" __global__ void __launch_bounds__(64) \ + NAME(const __nv_bfloat16* gu, __nv_bfloat16* out, float* xs, float limit, int64_t w) { \ + __shared__ float smem[2]; \ + const int64_t r = blockIdx.x, d = blockIdx.y * 64 + threadIdx.x; \ + const float a = glm_moe::swiglu1(bf(gu[r * 2 * w + d]), bf(gu[r * 2 * w + w + d]), limit); \ + out[r * w + d] = __float2bfloat16_rn(a); \ + const float g = block_sum<2>(a, smem); \ + if (threadIdx.x == 0) xs[r * (w / 64) + blockIdx.y] = g; \ + } diff --git a/zig/src/core/lanes/lanes.zig b/zig/src/core/lanes/lanes.zig index b394f681d5a..54c20aef963 100644 --- a/zig/src/core/lanes/lanes.zig +++ b/zig/src/core/lanes/lanes.zig @@ -10,6 +10,7 @@ pub const proposer = @import("proposer.zig"); pub const recall = @import("recall.zig"); pub const recall_store = @import("recall_store.zig"); pub const sampling = @import("sampling.zig"); +pub const sampling_row = @import("sampling_row.zig"); pub const fill = @import("fill.zig"); pub const prefill_widths = @import("prefill_widths.zig"); pub const solo_chunk = @import("solo_chunk.zig"); @@ -93,4 +94,5 @@ pub const learned_dirs = @import("learned_dirs.zig"); test { _ = @import("context_copy_price_test.zig"); + _ = @import("sampling_row.zig"); } diff --git a/zig/src/core/lanes/sampling_row.zig b/zig/src/core/lanes/sampling_row.zig new file mode 100644 index 00000000000..5d59279310d --- /dev/null +++ b/zig/src/core/lanes/sampling_row.zig @@ -0,0 +1,106 @@ +//! The host draw over a row of bf16 logits: greedy, the keyed fp64 sampler over the top_k, or a grammar mask's tokens. +const std = @import("std"); +const sampling = @import("sampling.zig"); +const grammar = @import("grammar.zig"); +const Sampling = sampling.Sampling; + +/// A bf16 word as the f64 the keyed sampler reads. +pub fn value(word: u16) f64 { + return @as(f32, @bitCast(@as(u32, word) << 16)); +} + +/// The unchanged top-k candidates for the shared fp64 keyed sampler; a `mask` keeps its allowed ones (-inf's draw). +pub fn draw(gpa: std.mem.Allocator, logits: []const u16, settings: ?Sampling, position: u64, mask: []const u32) !u32 { + var best: ?usize = null; + var allowed: usize = 0; + for (logits, 0..) |word, id| { + const x = value(word); + if (!std.math.isFinite(x)) return error.NonfiniteLogits; + if (mask.len > 0 and !grammar.allows(mask, id)) continue; + allowed += 1; + if (best == null or x > value(logits[best.?])) best = id; + } + if (best == null) return error.NoAllowedToken; + const s = settings orelse return @intCast(best.?); + if (s.temperature <= 0) return @intCast(best.?); + const k = if (s.top_k == 0) allowed else @min(allowed, s.top_k); + const values = try gpa.alloc(f64, k); + defer gpa.free(values); + const ids = try gpa.alloc(u64, k); + defer gpa.free(ids); + var filled: usize = 0; + for (logits, 0..) |word, id| { + if (mask.len > 0 and !grammar.allows(mask, id)) continue; + const x = value(word); + if (k == allowed) { + values[filled] = x; + ids[filled] = id; + filled += 1; + continue; + } + if (filled == k and x <= values[k - 1]) continue; + var at = @min(filled, k - 1); + while (at > 0 and x > values[at - 1]) : (at -= 1) { + values[at] = values[at - 1]; + ids[at] = ids[at - 1]; + } + values[at] = x; + ids[at] = id; + filled = @min(filled + 1, k); + } + return @intCast(try sampling.choose(gpa, values, ids, position, s)); +} + +const test_vocab = 4099; + +fn testRow(words: []u16, values: []f64, ids: []u64) void { + for (words, values, ids, 0..) |*w, *v, *id, i| { + const x: f32 = @as(f32, @floatFromInt((i * 37) % 257)) / 8.0 - 16.0; + w.* = @intCast(@as(u32, @bitCast(x)) >> 16); + v.* = value(w.*); + id.* = i; + } +} + +test "candidate selection preserves full-vocabulary keyed draws and tie order" { + const gpa = std.testing.allocator; + var words: [test_vocab]u16 = undefined; + var values: [test_vocab]f64 = undefined; + var ids: [test_vocab]u64 = undefined; + testRow(&words, &values, &ids); + for ([_]u32{ 0, 1, 20, 257, test_vocab }) |k| { + for ([_]u64{ 0, 128, 65536 }) |position| { + const s: Sampling = .{ .seed = 1234, .top_k = k, .temperature = 0.7, .top_p = 0.95, .min_p = 0.1 }; + const want = try sampling.choose(gpa, &values, &ids, position, s); + try std.testing.expectEqual(want, try draw(gpa, &words, s, position, &.{})); + } + } + const greedy = try draw(gpa, &words, .{ .seed = 7, .temperature = 0 }, 99, &.{}); + try std.testing.expectEqual(try draw(gpa, &words, null, 0, &.{}), greedy); + words[0] = 0x7fc0; + try std.testing.expectError(error.NonfiniteLogits, draw(gpa, &words, null, 0, &.{})); +} + +test "a masked draw is the full-vocabulary draw with the other tokens at -inf" { + const gpa = std.testing.allocator; + var words: [test_vocab]u16 = undefined; + var values: [test_vocab]f64 = undefined; + var ids: [test_vocab]u64 = undefined; + testRow(&words, &values, &ids); + var mask: [(test_vocab + 31) / 32]u32 = @splat(0); + for (&values, 0..) |*v, i| { + const on = i % 7 == 3 or i % 1000 == 1; + if (on) mask[i / 32] |= @as(u32, 1) << @intCast(i % 32) else v.* = -std.math.inf(f64); + } + for ([_]u32{ 0, 1, 20, 257, test_vocab }) |k| { + for ([_]u64{ 0, 128, 65536 }) |position| { + const s: Sampling = .{ .seed = 99, .top_k = k, .temperature = 0.8, .top_p = 0.9, .min_p = 0.05 }; + const want = try sampling.choose(gpa, &values, &ids, position, s); + try std.testing.expectEqual(want, try draw(gpa, &words, s, position, &mask)); + } + } + const greedy = try sampling.choose(gpa, &values, &ids, 0, .{ .seed = 1, .temperature = 0 }); + try std.testing.expectEqual(greedy, try draw(gpa, &words, null, 0, &mask)); + @memset(&mask, 0); + try std.testing.expectError(error.NoAllowedToken, draw(gpa, &words, null, 0, &mask)); +} diff --git a/zig/src/core/segments.zig b/zig/src/core/segments.zig index 5e03c7f3995..eab894083ce 100644 --- a/zig/src/core/segments.zig +++ b/zig/src/core/segments.zig @@ -102,6 +102,7 @@ pub fn runCommitting(device: mtl.Device, queues: []const mtl.Queue, layers: usiz try x.fam.finish(&x.lanes[k]); } }; + const probe = probeOf(fam, n); // committed before the segments encode, so a warm queue has run it by their commit const x: X = .{ .fam = fam, .lanes = lanes[0..n], .evs = evs[0..n_evs], .mode = mode, .queue = queues[0], .every = every, .layers = layers, .done = &done, .n_done = &n_done }; stagger.drive(n, layers, &x) catch |err| { // close the open encoders, drop the open command buffers, let committed chunks finish for (lanes[0..n]) |l| l.enc.end(); @@ -109,6 +110,7 @@ pub fn runCommitting(device: mtl.Device, queues: []const mtl.Queue, layers: usiz return err; }; for (lanes[0..n]) |l| l.enc.end(); + if (probe) |p| try held(p); for (lanes[0..n]) |l| l.cb.commit(); for (lanes[0..n]) |l| l.cb.wait(); // every segment ends before a failure returns and its buffers are reused var gpu: f64 = 0; @@ -130,6 +132,24 @@ pub fn runCommitting(device: mtl.Device, queues: []const mtl.Queue, layers: usiz return gpu; } +/// The family's probe on the first queue (an optional `probe` hook), for chunks whose later segments wait on the GPU. +fn probeOf(fam: anytype, n: usize) ?mtl.CommandBuffer { + if (n < 2 or !@hasDecl(std.meta.Child(@TypeOf(fam)), "probe")) return null; + return fam.probe(); +} + +/// Waits for the probe, so no segment commits before the first queue reaches the chunk and segment 1 never waits long. +fn held(p: mtl.CommandBuffer) !void { + const t0 = mtl.clock.seconds(); + p.wait(); + if (p.failure()) |msg| { + std.log.err("command buffer failed: {s}", .{msg}); + return error.GpuFailed; + } + const ms = (mtl.clock.seconds() - t0) * 1e3; + if (ms >= 500) std.log.info("segments: waited {d:.0} ms for the first queue to reach the chunk (re-wiring or earlier work)", .{ms}); +} + test { _ = stagger; } diff --git a/zig/src/families/flashnext/replay_prompt_segments.zig b/zig/src/families/flashnext/replay_prompt_segments.zig index d076dcd2e00..e8102110d99 100644 --- a/zig/src/families/flashnext/replay_prompt_segments.zig +++ b/zig/src/families/flashnext/replay_prompt_segments.zig @@ -287,6 +287,11 @@ pub const Hooks = struct { s.p.r.enc = l.enc; return s; } + /// The idle keepalive's command buffer on the engine's queue; core/segments.zig waits for it before committing. + pub fn probe(h: *Hooks) ?mtl.CommandBuffer { + const p = h.segs[0].p.r.warm_probe orelse return null; + return p.run(p.ctx); + } pub fn begin(h: *Hooks, l: *segments.Lane) !void { const s = h.at(l); const b = &s.p.b; diff --git a/zig/src/families/flashnext/replay_run.zig b/zig/src/families/flashnext/replay_run.zig index 36f6818898f..fec90b88ed1 100644 --- a/zig/src/families/flashnext/replay_run.zig +++ b/zig/src/families/flashnext/replay_run.zig @@ -21,6 +21,9 @@ const Select = fz.Select; const GSelect = fz.GSelect; const Lane = fz.Lane; +/// A command buffer the host commits on the engine's queue; core/segments.zig waits for it before segments commit. +pub const WarmProbe = struct { ctx: *const anyopaque, run: *const fn (ctx: *const anyopaque) mtl.CommandBuffer }; + pub const Run = struct { window: WindowSettings = .{}, arena: std.mem.Allocator, @@ -32,6 +35,7 @@ pub const Run = struct { shapes: std.StringHashMapUnmanaged(mtl.Buffer) = .empty, held: std.ArrayList(mtl.Buffer) = .empty, // what buffer, load and group made: a host's residency set holds them follow: ?mtl.ResidencySet.Follow = null, // set once the host's set is built: later buffers join it + warm_probe: ?WarmProbe = null, // the host's idle keepalive command buffer, run before staggered segments commit loaded: usize = 0, rows: usize = 1, fused_xsum: bool = false, diff --git a/zig/src/families/flashnext/rows_load.zig b/zig/src/families/flashnext/rows_load.zig index 152b05aabdd..68e32364e01 100644 --- a/zig/src/families/flashnext/rows_load.zig +++ b/zig/src/families/flashnext/rows_load.zig @@ -333,3 +333,7 @@ pub fn attach(p: *const Prompt, m: *Model, mtp_root: []const u8) !void { m.mtp.draft, }) |l| if (l.rows) |d| try warm(r, d); } + +test { + _ = rows_w; +} diff --git a/zig/src/families/flashnext/rows_w.zig b/zig/src/families/flashnext/rows_w.zig index fc2410c89e0..27cec61bb52 100644 --- a/zig/src/families/flashnext/rows_w.zig +++ b/zig/src/families/flashnext/rows_w.zig @@ -48,6 +48,11 @@ pub fn rps(n: usize) u8 { return if (n % 4 == 0) 4 else if (n % 2 == 0) 2 else 1; } +/// Outputs a simdgroup at 8 values a lane step (6 and 8 bits): 2 keeps more simdgroups in flight, same sums; else 1. +pub fn rps2(n: usize) u8 { + return if (n % 2 == 0) 2 else 1; +} + /// How 4-bit dots make nibbles at `rows` rows: converts at 1 row, then half (M3, M4) or the exponent trick. pub fn nib(generation: u32, rows: usize) u8 { if (rows < 2 or generation >= 17) return 0; @@ -102,7 +107,7 @@ pub fn specOf(p: Product, generation: u32, rows: usize, ld: usize) Spec { .bits = p.bits, .group = p.group, .ld = ld, - .rps = if (q4(p)) 4 else rps(p.n), + .rps = if (q4(p)) 4 else if (vpt(p.bits) == 8) rps2(p.n) else rps(p.n), .nib = if (q4(p)) nib(generation, rows) else 0, }; } @@ -287,6 +292,25 @@ test "members back to back at one width merge into one product; a gap, a width o try std.testing.expectEqual(@as(?Product, null), merge(&ms)); } +test "6- and 8-bit products take 2 outputs a simdgroup, 1 at an odd width; 4/32 keeps 4, other widths keep rps" { + const one: mtl.Buffer = .{ .id = @ptrFromInt(0x1000) }; + const q8: Product = .{ .w = .{ .b = one }, .s = .{ .b = one }, .b = .{ .b = one }, .n = 2560, .k = 6144, .bits = 8, .group = 64 }; + try std.testing.expectEqual(@as(u8, 2), specOf(q8, 15, 4, q8.k).rps); + var odd = q8; + odd.n = 2561; + try std.testing.expectEqual(@as(u8, 1), specOf(odd, 15, 4, odd.k).rps); + var four = q8; + four.bits = 4; + four.group = 32; + try std.testing.expectEqual(@as(u8, 4), specOf(four, 15, 4, four.k).rps); + var six = q8; + six.bits = 6; + try std.testing.expectEqual(@as(u8, 2), specOf(six, 15, 4, six.k).rps); + var five = q8; + five.bits = 5; + try std.testing.expectEqual(rps(five.n), specOf(five, 15, 4, five.k).rps); +} + fn slot(bits: u8) usize { return if (vpt(bits) == 8) 0 else 1; } diff --git a/zig/src/families/qwen3_5/draw.zig b/zig/src/families/qwen3_5/draw.zig index 4dbc965264e..68f6db228f0 100644 --- a/zig/src/families/qwen3_5/draw.zig +++ b/zig/src/families/qwen3_5/draw.zig @@ -6,51 +6,16 @@ const c = @import("config.zig"); /// A row's allowed-token bits (structured output): one bit a logit. pub const mask_words = (c.vocab + 31) / 32; -pub fn value(word: u16) f64 { - return @as(f32, @bitCast(@as(u32, word) << 16)); -} +pub const value = lanes.sampling_row.value; -/// The unchanged top-k candidates for the shared fp64 keyed sampler; a `mask` keeps its allowed ones (-inf's draw). +/// The bounded top-k draw when it applies, else core's row draw (lanes.sampling_row) under the Qwen error names. pub fn draw(gpa: std.mem.Allocator, logits: []const u16, settings: ?lanes.Sampling, position: u64, mask: []const u32) !u32 { if (settings) |sampling| if (try @import("draw_topk.zig").draw(logits, sampling, position, mask)) |token| return token; - var best: ?usize = null; - var allowed: usize = 0; - for (logits, 0..) |word, id| { - const x = value(word); - if (!std.math.isFinite(x)) return error.NonfiniteQwenLogits; - if (mask.len > 0 and !lanes.grammar.allows(mask, id)) continue; - allowed += 1; - if (best == null or x > value(logits[best.?])) best = id; - } - if (best == null) return error.NoAllowedQwenToken; - const sampling = settings orelse return @intCast(best.?); - if (sampling.temperature <= 0) return @intCast(best.?); - const k = if (sampling.top_k == 0) allowed else @min(allowed, sampling.top_k); - const values = try gpa.alloc(f64, k); - defer gpa.free(values); - const ids = try gpa.alloc(u64, k); - defer gpa.free(ids); - var filled: usize = 0; - for (logits, 0..) |word, id| { - if (mask.len > 0 and !lanes.grammar.allows(mask, id)) continue; - const x = value(word); - if (k == allowed) { - values[filled] = x; - ids[filled] = id; - filled += 1; - continue; - } - if (filled == k and x <= values[k - 1]) continue; - var at = @min(filled, k - 1); - while (at > 0 and x > values[at - 1]) : (at -= 1) { - values[at] = values[at - 1]; - ids[at] = ids[at - 1]; - } - values[at] = x; - ids[at] = id; - filled = @min(filled + 1, k); - } - return @intCast(try lanes.sampling.choose(gpa, values, ids, position, sampling)); + return lanes.sampling_row.draw(gpa, logits, settings, position, mask) catch |e| switch (e) { + error.NonfiniteLogits => error.NonfiniteQwenLogits, + error.NoAllowedToken => error.NoAllowedQwenToken, + else => e, + }; } test "candidate selection preserves full-vocabulary keyed draws and tie order" { diff --git a/zig/src/metal/keepalive.zig b/zig/src/metal/keepalive.zig index dd472c642e5..d3f89a72f21 100644 --- a/zig/src/metal/keepalive.zig +++ b/zig/src/metal/keepalive.zig @@ -13,12 +13,17 @@ pub fn TargetFor(comptime Metal: type) type { pub const Flush = struct { ctx: *anyopaque, run: *const fn (ctx: *anyopaque) void }; - /// The core ticker's tick: one command buffer that touches every set and commits. + /// The core ticker's tick: the sets' waiting changes, then the probe. pub fn tick(ctx: *anyopaque) void { const t: *Self = @ptrCast(@alignCast(ctx)); const pool = Metal.objc.Pool.push(); defer pool.pop(); if (t.flush) |f| f.run(f.ctx); + _ = t.probe(); + } + + /// One committed command buffer that touches every set, without the flush; a request may wait for it. + pub fn probe(t: *const Self) Metal.CommandBuffer { const cmd = t.queue.commandBuffer(); for (t.sets) |set| cmd.useResidencySet(set); if (t.scratch) |b| { // an empty command buffer need not reach the GPU, and then its sets stay as they were @@ -27,6 +32,7 @@ pub fn TargetFor(comptime Metal: type) type { blit.end(); } cmd.commit(); + return cmd; } }; } diff --git a/zig/src/native/flashnext_residency.zig b/zig/src/native/flashnext_residency.zig index c3b1bb6dc99..27050ce140f 100644 --- a/zig/src/native/flashnext_residency.zig +++ b/zig/src/native/flashnext_residency.zig @@ -10,11 +10,18 @@ fn initial(h: anytype, list: *std.ArrayList(mtl.Buffer)) !void { if (h.vis) |v| try list.appendSlice(h.gpa, &v.buffers()); } +/// The idle keepalive's command buffer without its flush, for the engine's staggered segments to wait for. +fn probeWarm(ctx: *const anyopaque) mtl.CommandBuffer { + const t: *const mtl.keepalive.Target = @ptrCast(@alignCast(ctx)); + return t.probe(); +} + fn attach(h: anytype, io: std.Io, buffers: []const mtl.Buffer, label: []const u8) !void { h.resident = try Resident.holdUnder(h.gpa, io, h.eng.r.device, h.eng.r.queue, buffers, label, if (h.load_limit > 0) h.load_limit else null); if (h.resident) |*r| { h.warm = r.target(); h.eng.r.follow = r.follow(); + h.eng.r.warm_probe = .{ .ctx = &h.warm, .run = probeWarm }; h.eng.snap_pool.follow = r.follow(); } } @@ -28,6 +35,7 @@ pub fn hold(h: anytype) !void { pub fn drop(h: anytype) void { h.eng.r.follow = null; + h.eng.r.warm_probe = null; h.eng.snap_pool.follow = null; if (h.resident) |*r| r.deinit(); h.resident = null; diff --git a/zig/tests/flashnext_widths_rows.zig b/zig/tests/flashnext_widths_rows.zig index 0868aee4775..adea414d1c7 100644 --- a/zig/tests/flashnext_widths_rows.zig +++ b/zig/tests/flashnext_widths_rows.zig @@ -353,7 +353,7 @@ pub fn time(device: mtl.Device, queue: mtl.Queue) !void { const cases = [_][4]usize{ .{ 10240, 2560, 4, 32 }, .{ 6240, 2560, 5, 128 }, .{ 2560, 6144, 5, 128 }, .{ 13952, 2560, 6, 64 }, .{ 2560, 6144, 6, 64 }, .{ 16480, 2560, 6, 32 }, .{ 2560, 6144, 6, 32 }, .{ 13952, 2560, 3, 64 }, - .{ 79616, 2560, 8, 64 }, .{ 248320, 2560, 8, 64 }, + .{ 79616, 2560, 8, 64 }, .{ 248320, 2560, 8, 64 }, .{ 2560, 6144, 8, 64 }, }; std.debug.print( "TIME shape width rows: lane us (GB/s) | rows us (GB/s, % of {d:.0}) | lane/rows | loop, four, twin us\n", diff --git a/zig/tests/segments_probe.zig b/zig/tests/segments_probe.zig new file mode 100644 index 00000000000..e77489f52b3 --- /dev/null +++ b/zig/tests/segments_probe.zig @@ -0,0 +1,170 @@ +//! tf-segments-probe: a two-segment chunk behind a held first queue times out without the probe and passes with it. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const segments = tf.segments; + +pub const std_options: std.Options = .{ .logFn = log }; +var failure: [256]u8 = undefined; // the last error line logged, which segments.run writes for a failed lane +var failure_len: usize = 0; + +fn log(comptime level: std.log.Level, comptime scope: @EnumLiteral(), comptime format: []const u8, args: anytype) void { + std.log.defaultLog(level, scope, format, args); + if (level != .err) return; + failure_len = if (std.fmt.bufPrint(&failure, format, args)) |line| line.len else |_| failure.len; +} + +const source = + \\#include + \\using namespace metal; + \\kernel void spin(device uint* out [[buffer(0)]], constant uint& n [[buffer(1)]], uint t [[thread_position_in_grid]]) { + \\ uint x = t + 1; + \\ for (uint i = 0; i < n; i++) x = x * 1664525u + 1013904223u; + \\ out[t] = x; + \\} +; + +const slot = 16; // bytes of `out` each writer owns, so no two queues write the same word +const spin_s = 1.5; // each spin command buffer stays well under the GPU watchdog itself +const busy_buffers = 5; // together well past it: spin_s * busy_buffers ahead of the chunk, also the hold + +/// One layer of a little work a segment: segment 1 runs its pre, then waits on the GPU for segment 0's event. +const Fam = struct { + first: mtl.Queue, + scratch: mtl.Buffer, + pipe: mtl.Pipeline, + out: mtl.Buffer, + with_probe: bool, + + pub fn begin(_: *Fam, _: *segments.Lane) !void {} + pub fn wait(_: *Fam, _: usize) segments.Wait { + return .mixer; + } + pub fn handoff(_: *Fam, _: *segments.Lane, _: usize) !void {} + pub fn pre(f: *Fam, l: *segments.Lane, _: usize) !void { + work(l.enc, f.pipe, f.out, slot * (l.k + 1), 1000); + } + pub fn mixer(f: *Fam, l: *segments.Lane, _: usize) !void { + work(l.enc, f.pipe, f.out, slot * (l.k + 1), 1000); + } + pub fn post(_: *Fam, _: *segments.Lane, _: usize) !void {} + pub fn finish(_: *Fam, _: *segments.Lane) !void {} + pub fn probe(f: *Fam) ?mtl.CommandBuffer { + if (!f.with_probe) return null; + const t: mtl.keepalive.Target = .{ .queue = f.first, .scratch = f.scratch }; + return t.probe(); + } +}; + +fn work(enc: mtl.ComputeEncoder, pipe: mtl.Pipeline, out: mtl.Buffer, at: usize, n: u32) void { + enc.setPipeline(pipe); + enc.setBuffer(out, at, 0); + enc.setBytes(std.mem.asBytes(&n), 1); + enc.dispatchThreads(mtl.Size.of(1, 1, 1), mtl.Size.of(1, 1, 1)); +} + +fn spin(queue: mtl.Queue, pipe: mtl.Pipeline, out: mtl.Buffer, n: u32) mtl.CommandBuffer { + const cb = queue.commandBuffer(); + const enc = cb.compute(.serial); + work(enc, pipe, out, 0, n); + enc.end(); + cb.commit(); + return cb; +} + +/// Iterations for one spin command buffer of about `spin_s` on this GPU. +fn calibrate(queue: mtl.Queue, pipe: mtl.Pipeline, out: mtl.Buffer) !u32 { + var n: u32 = 1 << 22; + for (0..4) |_| { + const cb = spin(queue, pipe, out, n); + cb.wait(); + if (cb.failure()) |msg| { + std.debug.print("calibration failed: {s}\n", .{msg}); + return error.GpuFailed; + } + const s = cb.gpuSeconds(); + if (s > 0.9 * spin_s and s < 1.1 * spin_s) break; + // at most 16x a step, so a tiny first sample cannot overshoot into one long command buffer + n = @intFromFloat(@min(@as(f64, @floatFromInt(n)) * @min(spin_s / @max(s, 1e-6), 16.0), 4.0e9)); + } + return n; +} + +/// Releases the held first queue one blocker every `each_ms`: the wait on a value not yet set is the sleep. +fn release(ev: mtl.SharedEvent, each_ms: u64) void { + for (1..busy_buffers + 1) |v| { + _ = ev.wait(busy_buffers + 1, each_ms); + ev.set(v); + } +} + +pub fn main(init: std.process.Init) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const args = try init.minimal.args.toSlice(init.arena.allocator()); + const busy_mode = args.len > 1 and std.mem.eql(u8, args[1], "busy"); // spin kernels ahead: reported, not judged + const device = try mtl.Device.init(); + const first = try device.queue(); + const lib = try mtl.Library.fromSource(device, source, mtl.CompileOptions.mlx()); + const pipe = try mtl.Pipeline.init(device, lib, "spin", false); + const out = try device.buffer(64, mtl.ResourceOptions.shared); + const scratch = try device.buffer(64, mtl.ResourceOptions.shared); + const n = if (busy_mode) try calibrate(first, pipe, out) else 0; + const hold_ms: u64 = @intFromFloat(spin_s * busy_buffers * 1e3); + var wrong: usize = 0; + for ([_]bool{ true, false }) |with_probe| { // the probe first: after a timeout macOS ignores this process's work + var ahead: [busy_buffers]mtl.CommandBuffer = undefined; + var n_ahead: usize = 0; + var thread: ?std.Thread = null; + if (busy_mode) { + for (&ahead) |*cb| cb.* = spin(first, pipe, out, n); + n_ahead = busy_buffers; + } else { // the first queue held with the GPU idle, as when segment 0's commit re-wires + const ev = try device.sharedEvent(); + for (&ahead, 1..) |*cb, v| { + cb.* = first.commandBuffer(); + cb.*.waitFor(ev, v); + cb.*.commit(); + } + n_ahead = busy_buffers; + thread = try std.Thread.spawn(.{}, release, .{ ev, @as(u64, @intFromFloat(spin_s * 1e3)) }); + } + const queues = [_]mtl.Queue{ first, try device.queue() }; + var fam: Fam = .{ .first = first, .scratch = scratch, .pipe = pipe, .out = out, .with_probe = with_probe }; + failure_len = 0; + const t0 = mtl.clock.seconds(); + const got = segments.run(device, &queues, 1, .serial, &fam); + const chunk_s = mtl.clock.seconds() - t0; + if (thread) |t| t.join(); + var ahead_s: f64 = if (busy_mode) 0 else @as(f64, @floatFromInt(hold_ms)) / 1e3; + for (ahead[0..n_ahead]) |cb| { + cb.wait(); + if (busy_mode) ahead_s += cb.gpuSeconds(); + if (cb.failure()) |msg| { // only the chunk may fail: a failed blocker would void the comparison + std.debug.print("a command buffer ahead of the chunk failed: {s}\n", .{msg}); + wrong += 1; + } + } + const label = if (with_probe) "with the probe" else "without the probe"; + const what = if (busy_mode) "of spin kernels (GPU time)" else "held by the host (nominal), GPU idle"; + if (got) |_| { + std.debug.print("RESULT {s}: the chunk passed after {d:.2} s, behind {d:.2} s {s}\n", .{ label, chunk_s, ahead_s, what }); + if (!with_probe and !busy_mode) wrong += 1; + if (with_probe and !busy_mode and chunk_s < 0.9 * ahead_s) { // the pass must come from waiting out the hold + std.debug.print("the chunk passed before the hold ended: the first queue was not held\n", .{}); + wrong += 1; + } + } else |err| { + std.debug.print("RESULT {s}: the chunk failed ({s}) after {d:.2} s, behind {d:.2} s {s}\n", .{ label, @errorName(err), chunk_s, ahead_s, what }); + // only the watchdog's timeout counts as the failure this tool is about + const timeout = std.mem.indexOf(u8, failure[0..failure_len], "CallbackErrorTimeout") != null; + if (!busy_mode and (with_probe or err != error.GpuFailed or !timeout)) wrong += 1; + } + } + if (busy_mode) return; + if (wrong > 0) { + std.debug.print("FAIL {d} result(s) other than expected: a pass with the probe, a timeout without it\n", .{wrong}); + std.process.exit(1); + } + std.debug.print("PASS with the probe the chunk passed; without it segment 1 timed out in its wait\n", .{}); +}