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

- Qwen3.6-35B-A3B on Metal: the text-only checkpoint serves on the routed expert path, `--vision` refuses it by name, and `tf-qwen27-run --stages DIR` writes each layer's stream for a float64 comparison (#3239). Thanks to @cshintov.

- Metal Qwen3.8-27B with MTP drafts: `TF_Q27_MTP_GPU_PICK=1` runs each MTP absorb in one command buffer and picks draft tokens on the GPU, removing two blocking waits per absorb and the CPU pass over the vocabulary; off by default (#N).

- Idol: octree and decode-trace allocation failures now unwind cleanly and free what they hold, with successful output unchanged (#4304).
Expand Down
9 changes: 9 additions & 0 deletions docs/kernel-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,15 @@ Ornith-1.5-122B's routed block on Metal registers the experts' decode rows with
(`q27_rows_extra`, 4 and 8 bits), the router's softmax and top-k with renormalized bf16 weights (`q27_route`: picks
equal to the host's, each weight within float64's range at its bf16 points), the tensor units' expert sort and gather
(bit for bit), the experts' SwiGLU, and the weighted combine with the gated shared expert (in place and from its slot).
The same kernels register at Qwen3.6-35B-A3B's served widths (experts of 512 over 2,048).
qwen27's attention registers at the 27B's 24 query heads over 4 and the 35B-A3B's 16 over 2: a round's rows through the
engine's own plan and launcher against float64 attention, prompt rows through the prompt kernel on every chip that
builds it (`attention_prompt_sg` before the M5), and attention_io's packing, append and keep checked bit for bit (keep
a second time on the caches the first left). A plan check shows the decode shapes plan prefix_1 to _6 for chains and
_2 to _6 for trees, and a tree over two tail chunks. Its known finding: before the M5 a masked key's zero probability
times an infinite value gives NaN in P V. Its controls: a row seeing one key past its own, the one-Mac merge dropping
a round's later tail chunks, the prompt kernel losing its bounded last step, and an append one row late. prefix_5 and
_6 have no launch record yet: past 256 threads they need a reserved thread count before M1 and M2 can admit them.
GLM's Metal window projections register narrow and wide rows at 2, 3, 4, 5, 6 and 8 bits, plus both gathered paths.
Independent FP64 linear cases accompany byte replacements against frozen pre-window-optimization kernels.
The gathered SwiGLU keeps its predecessor's clipped BF16 output and nonfinite rules; gate/up taps qualify its dots separately.
Expand Down
223 changes: 223 additions & 0 deletions tools/zig/qwen36_f64.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
"""A float64 qwen3_5_moe forward of an MLX affine checkpoint, exact weights, mlx_lm 0.31's math; no rounding."""
from __future__ import annotations

import json
from pathlib import Path

import mlx.core as mx
import numpy as np

F = np.float64


def softplus(x):
return np.logaddexp(0.0, x)


def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))


def silu(x):
return x * sigmoid(x)


def rms(x, weight, eps):
y = x / np.sqrt(np.mean(x * x, axis=-1, keepdims=True) + eps)
return y if weight is None else y * weight


def delta_rule(q, k, v, g, beta):
"""The gated delta rule from a zero state: q, k [T, Hk, Dk]; v [T, Hv, Dv]; g, beta [T, Hv]; returns [T, Hv, Dv]."""
t, hv = v.shape[0], v.shape[1]
q, k = np.repeat(q, hv // q.shape[1], axis=1), np.repeat(k, hv // k.shape[1], axis=1)
state = np.zeros((hv, v.shape[2], k.shape[2]))
ys = np.empty(v.shape)
for i in range(t):
state *= g[i][:, None, None]
delta = (v[i] - (state @ k[i][:, :, None])[..., 0]) * beta[i][:, None]
state += delta[:, :, None] * k[i][:, None, :]
ys[i] = (state @ q[i][:, :, None])[..., 0]
return ys


class Checkpoint:
"""The text model's tensors by name, dequantized to float64 on request."""

def __init__(self, snapshot: Path):
self.snapshot = snapshot
config = json.loads((snapshot / "config.json").read_text())
self.config = config.get("text_config", config)
quant = config["quantization"]
self.bits, self.group = quant["bits"], quant["group_size"]
self.widths = {k: v for k, v in quant.items() if isinstance(v, dict)}
index = json.loads((snapshot / "model.safetensors.index.json").read_text())["weight_map"]
self.shards = {}
for name in sorted(set(index.values())):
self.shards.update(mx.load(str(snapshot / name)))
self.prefix = "language_model.model."

def raw(self, name):
return self.shards[name]

def vector(self, name):
return np.array(self.raw(name).astype(mx.float32)).astype(F)

def width(self, module):
w = self.widths.get(module, {})
return w.get("bits", self.bits), w.get("group_size", self.group)

def dense(self, module, rows=None, index=None):
"""`module`'s weight [out, in] (or expert `index`'s), only `rows` of out when given."""
bits, group = self.width(module)
q, s, b = (self.raw(f"{module}.{k}") for k in ("weight", "scales", "biases"))
if index is not None:
q, s, b = q[index], s[index], b[index]
if rows is not None:
q, s, b = q[rows], s[rows], b[rows]
q = np.array(q)
s = np.array(s.astype(mx.float32)).astype(F)
b = np.array(b.astype(mx.float32)).astype(F)
per = 32 // bits
shifts = (np.arange(per, dtype=np.uint32) * bits).astype(np.uint32)
values = (q[..., None] >> shifts) & np.uint32((1 << bits) - 1)
values = values.reshape(*q.shape[:-1], -1).astype(F)
grouped = values.reshape(*values.shape[:-1], -1, group)
return (grouped * s[..., None] + b[..., None]).reshape(values.shape)


class Model:
def __init__(self, ckpt: Checkpoint):
c = ckpt.config
self.ck = ckpt
self.layers = c["num_hidden_layers"]
self.hidden = c["hidden_size"]
self.vocab = c["vocab_size"]
self.eps = c["rms_norm_eps"]
self.types = c["layer_types"]
self.k_heads, self.v_heads = c["linear_num_key_heads"], c["linear_num_value_heads"]
self.k_dim, self.v_dim = c["linear_key_head_dim"], c["linear_value_head_dim"]
self.heads, self.kv_heads, self.head_dim = c["num_attention_heads"], c["num_key_value_heads"], c["head_dim"]
rope = c["rope_parameters"]
self.rotary = int(self.head_dim * rope["partial_rotary_factor"])
self.theta = float(rope["rope_theta"])
self.experts, self.top_k = c["num_experts"], c["num_experts_per_tok"]

def p(self, layer, rest):
return f"{self.ck.prefix}layers.{layer}.{rest}"

def embed(self, ids):
return self.ck.dense(self.ck.prefix + "embed_tokens", rows=mx.array(np.asarray(ids, np.int32)))

def mixer(self, layer, xs, positions):
"""xs: the stream rows of one or more independent runs, each [T, hidden]; returns their mixer outputs."""
norm = self.ck.vector(self.p(layer, "input_layernorm.weight"))
normed = [rms(x, norm, self.eps) for x in xs]
if self.types[layer] == "linear_attention":
return self.gdn(layer, normed)
return self.attention(layer, normed, positions)

def gdn(self, layer, xs):
m = lambda n: self.ck.dense(self.p(layer, f"linear_attn.{n}"))
wqkv, wz, wa, wb, wo = m("in_proj_qkv"), m("in_proj_z"), m("in_proj_a"), m("in_proj_b"), m("out_proj")
conv = self.ck.vector(self.p(layer, "linear_attn.conv1d.weight"))[:, :, 0] # [channels, kernel]
a_log = self.ck.vector(self.p(layer, "linear_attn.A_log"))
dt_bias = self.ck.vector(self.p(layer, "linear_attn.dt_bias"))
gain = self.ck.vector(self.p(layer, "linear_attn.norm.weight"))
kd, vd, hk, hv = self.k_dim, self.v_dim, self.k_heads, self.v_heads
key = kd * hk
out = []
for x in xs:
t = x.shape[0]
qkv = x @ wqkv.T
z = (x @ wz.T).reshape(t, hv, vd)
g = np.exp(-np.exp(a_log) * softplus(x @ wa.T + dt_bias))
beta = sigmoid(x @ wb.T)
padded = np.concatenate([np.zeros((conv.shape[1] - 1, qkv.shape[1])), qkv])
mixed = sum(padded[j:j + t] * conv[:, j] for j in range(conv.shape[1]))
mixed = silu(mixed)
q = mixed[:, :key].reshape(t, hk, kd)
k = mixed[:, key:2 * key].reshape(t, hk, kd)
v = mixed[:, 2 * key:].reshape(t, hv, vd)
q = rms(q, None, 1e-6) * kd ** -1.0
k = rms(k, None, 1e-6) * kd ** -0.5
y = rms(delta_rule(q, k, v, g, beta), gain, self.eps) * silu(z)
out.append(y.reshape(t, hv * vd) @ wo.T)
return out

def rope(self, x, positions):
half = self.rotary // 2
freq = self.theta ** (-np.arange(half, dtype=F) * 2.0 / self.rotary)
angle = np.asarray(positions, F)[:, None] * freq[None, :]
cos, sin = np.cos(angle)[:, None, :], np.sin(angle)[:, None, :]
x1, x2 = x[..., :half], x[..., half:self.rotary]
return np.concatenate([x1 * cos - x2 * sin, x1 * sin + x2 * cos, x[..., self.rotary:]], axis=-1)

def attention(self, layer, xs, positions):
m = lambda n: self.ck.dense(self.p(layer, f"self_attn.{n}"))
wq, wk, wv, wo = m("q_proj"), m("k_proj"), m("v_proj"), m("o_proj")
qn = self.ck.vector(self.p(layer, "self_attn.q_norm.weight"))
kn = self.ck.vector(self.p(layer, "self_attn.k_norm.weight"))
h, kvh, d = self.heads, self.kv_heads, self.head_dim
out = []
for x in xs:
t = x.shape[0]
qg = (x @ wq.T).reshape(t, h, 2 * d)
q, gate = qg[..., :d], qg[..., d:].reshape(t, h * d)
k = (x @ wk.T).reshape(t, kvh, d)
v = (x @ wv.T).reshape(t, kvh, d)
q = self.rope(rms(q, qn, self.eps), positions)
k = self.rope(rms(k, kn, self.eps), positions)
k, v = np.repeat(k, h // kvh, axis=1), np.repeat(v, h // kvh, axis=1)
scores = np.einsum("thd,shd->hts", q, k) * d ** -0.5
scores = np.where(np.tril(np.ones((t, t), bool))[None], scores, -np.inf)
scores = np.exp(scores - scores.max(axis=-1, keepdims=True))
scores /= scores.sum(axis=-1, keepdims=True)
o = np.einsum("hts,shd->thd", scores, v).reshape(t, h * d)
out.append((o * sigmoid(gate)) @ wo.T)
return out

def route(self, logits):
"""Top-k experts per row (ties to the lower id), their renormalized weights, the k-th/(k+1)-th gap."""
order = np.argsort(-logits, axis=-1, kind="stable")
picks = order[:, :self.top_k]
top = np.take_along_axis(logits, picks, axis=-1)
weights = np.exp(top - top[:, :1])
weights /= weights.sum(axis=-1, keepdims=True)
nxt = np.take_along_axis(logits, order[:, self.top_k:self.top_k + 1], axis=-1)[:, 0]
return picks, weights, top[:, -1] - nxt

def moe(self, layer, xs):
"""xs: stream rows after the mixer; returns each run's MLP output and per-row routing (picks, k/k+1 gap)."""
norm = self.ck.vector(self.p(layer, "post_attention_layernorm.weight"))
sizes = [x.shape[0] for x in xs]
x = rms(np.concatenate(xs), norm, self.eps)
logits = x @ self.ck.dense(self.p(layer, "mlp.gate")).T
picks, weights, gap = self.route(logits)
y = np.zeros_like(x)
base = self.p(layer, "mlp.switch_mlp")
for e in np.unique(picks):
rows, slot = np.nonzero(picks == e)
g = self.ck.dense(f"{base}.gate_proj", index=int(e))
u = self.ck.dense(f"{base}.up_proj", index=int(e))
dn = self.ck.dense(f"{base}.down_proj", index=int(e))
xe = x[rows]
y[rows] += weights[rows, slot][:, None] * ((silu(xe @ g.T) * (xe @ u.T)) @ dn.T)
s = lambda n: self.ck.dense(self.p(layer, f"mlp.shared_expert.{n}"))
shared = (silu(x @ s("gate_proj").T) * (x @ s("up_proj").T)) @ s("down_proj").T
y += sigmoid(x @ self.ck.dense(self.p(layer, "mlp.shared_expert_gate")).T) * shared
cuts = np.cumsum(sizes)[:-1]
return np.split(y, cuts), np.split(picks, cuts), np.split(gap, cuts)

def final(self, x):
return rms(x, self.ck.vector(self.ck.prefix + "norm.weight"), self.eps)

def head(self, xs, chunk=16384):
"""Logits for each run's rows, the head dequantized a vocab chunk at a time."""
sizes = [x.shape[0] for x in xs]
x = np.concatenate(xs)
out = np.empty((x.shape[0], self.vocab))
for at in range(0, self.vocab, chunk):
rows = mx.arange(at, min(at + chunk, self.vocab))
out[:, at:at + chunk] = x @ self.ck.dense("language_model.lm_head", rows=rows).T
return np.split(out, np.cumsum(sizes)[:-1])
96 changes: 96 additions & 0 deletions tools/zig/qwen36_mlx_stages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""mlx_lm's staged references for qwen3_5_moe, in the layout families/qwen3_5/stages.zig writes (see USAGE)."""
from __future__ import annotations

USAGE = """The rows follow mlx_lm's generate_step: the prompt but its last token in one call, then one-row steps
feeding the last prompt token and every teacher token but the last; logits are each step's row. The decoder layer
runs its own ops unchanged and records the stream after the mixer and after the MLP.

python tools/zig/qwen36_mlx_stages.py --snapshot SNAP --ids ids.json --reference ref.json --out DIR"""

import argparse
import json
from pathlib import Path

import mlx.core as mx
import numpy as np
from mlx_lm import load
from mlx_lm.models import qwen3_5
from mlx_lm.models.cache import make_prompt_cache

RECORD: list | None = None


def decoder_call(self, x, mask=None, cache=None):
if self.is_linear:
r = self.linear_attn(self.input_layernorm(x), mask, cache)
else:
r = self.self_attn(self.input_layernorm(x), mask, cache)
h = x + r
out = h + self.mlp(self.post_attention_layernorm(h))
if RECORD is not None:
RECORD.append((h, out))
return out


def raw(x):
x = x.astype(mx.bfloat16)
mx.eval(x)
return np.array(x.view(mx.uint16)).reshape(-1, x.shape[-1])


def main():
global RECORD
ap = argparse.ArgumentParser(description=__doc__ + "\n\n" + USAGE, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--snapshot", type=Path, required=True)
ap.add_argument("--ids", type=Path, required=True)
ap.add_argument("--reference", type=Path, required=True)
ap.add_argument("--out", type=Path, required=True)
args = ap.parse_args()
prompt = json.loads(args.ids.read_text())
reference = json.loads(args.reference.read_text())

qwen3_5.DecoderLayer.__call__ = decoder_call
model, _ = load(str(args.snapshot))
text = model.language_model.model
layers = len(text.layers)
names = ["embed"] + [f"l{l:02d}.{k}" for l in range(layers) for k in ("mixer", "block")] + ["final"]
planes = {n: [] for n in names + ["logits"]}
cache = make_prompt_cache(model)
if len(prompt) < 2:
raise SystemExit("the prompt needs two tokens: one prefill call, then the steps")
calls = [prompt[:-1], [prompt[-1]]] + [[t] for t in reference[:-1]]
picks = []
for step, ids in enumerate(calls):
tokens = mx.array(ids)[None]
RECORD = []
logits = model(tokens, cache=cache)
mx.eval(logits, [c.state for c in cache])
planes["embed"].append(raw(text.embed_tokens(tokens)))
for l, (h, out) in enumerate(RECORD):
planes[f"l{l:02d}.mixer"].append(raw(h))
planes[f"l{l:02d}.block"].append(raw(out))
planes["final"].append(raw(text.norm(RECORD[-1][1])))
if step > 0:
last = logits[:, -1, :]
planes["logits"].append(raw(last))
logprobs = last - mx.logsumexp(last, keepdims=True)
picks.append(int(mx.argmax(logprobs, axis=-1).item()))
RECORD = None
args.out.mkdir(parents=True, exist_ok=True)
stages = []
for n, chunks in planes.items():
data = np.concatenate(chunks)
data.tofile(args.out / f"{n}.bf16")
stages.append({"name": n, "width": int(data.shape[1]), "rows": int(data.shape[0])})
total = len(prompt) + len(reference) - 1
index = {"version": 1, "dtype": "bf16", "layers": layers, "hidden": stages[0]["width"],
"vocab": stages[-1]["width"], "stages": stages, "positions": list(range(total)),
"logit_positions": list(range(len(prompt) - 1, total)),
"mlx": mx.__version__, "greedy_picks_equal_reference": picks == reference, "picks": picks}
(args.out / "index.json").write_text(json.dumps(index))
print(json.dumps({"picks_equal_reference": picks == reference,
"differ_at": [i for i, (a, b) in enumerate(zip(picks, reference)) if a != b]}))


if __name__ == "__main__":
main()
Loading
Loading