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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 11 additions & 1 deletion tools/conformance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -30,6 +33,7 @@
import argparse
import hashlib
import json
import os
import re
import socket
import subprocess
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down
78 changes: 78 additions & 0 deletions tools/conformance_profiles/qwen27-metal.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
8 changes: 8 additions & 0 deletions tools/tests/test_bench_conformance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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__":
Expand Down
1 change: 1 addition & 0 deletions zig/build/metal_targets.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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" },
Expand Down
55 changes: 4 additions & 51 deletions zig/kernels/cuda/glm_glue_moe.cuh
Original file line number Diff line number Diff line change
@@ -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 <int S>
__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<const uint2*>(gu + r * 2 * w + d0);
const uint2 uv = *reinterpret_cast<const uint2*>(gu + r * 2 * w + w + d0);
const __nv_bfloat16* gh = reinterpret_cast<const __nv_bfloat16*>(&gv);
const __nv_bfloat16* uh = reinterpret_cast<const __nv_bfloat16*>(&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<uint2*>(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)
Expand Down
63 changes: 63 additions & 0 deletions zig/kernels/cuda/glm_swiglu.cuh
Original file line number Diff line number Diff line change
@@ -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 <int S>
__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 <bool AFTER>
__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<const uint2*>(gu + r * 2 * w + d0); \
const uint2 uv = *reinterpret_cast<const uint2*>(gu + r * 2 * w + w + d0); \
const __nv_bfloat16* gh = reinterpret_cast<const __nv_bfloat16*>(&gv); \
const __nv_bfloat16* uh = reinterpret_cast<const __nv_bfloat16*>(&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<AFTER>(bf(gh[j]), bf(uh[j]), limit); \
oh[j] = __float2bfloat16_rn(a[j]); \
} \
*reinterpret_cast<uint2*>(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<AFTER>(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; \
}
2 changes: 2 additions & 0 deletions zig/src/core/lanes/lanes.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -93,4 +94,5 @@ pub const learned_dirs = @import("learned_dirs.zig");

test {
_ = @import("context_copy_price_test.zig");
_ = @import("sampling_row.zig");
}
Loading
Loading