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

## Unreleased

- Cluster: bring-up reports the leader, epoch and view it agreed on and counts only acknowledgments for that view, so a rank that finishes after a peer says goodbye no longer reports a smaller view on slow runners (#4135, fixes #4123). Thanks to @AIFlowML.

- Ling-3.0-tiny on Metal: a bf16 forward diagnostic runs all 24 layers of the published checkpoint on kernels that already exist, with no new GPU kernel source; `zig build test-ling-forward`, given `TF_LING_CHECKPOINT` and a Python with torch and safetensors (`TF_LING_PYTHON`), checks whole, chunked and resumed runs byte for byte and reports the distance from float64. Nothing is served yet (#3919, part of #1247). Thanks to @ThinkOffApp.

- Tests: the Web loopback startup test sets its fixture ready before probing, so its health, model-list and relay checks no longer depend on warm-up timing (#3753, fixes #3752). Thanks to @AIFlowML.

- Server: `TENSORFOLD_PARALLEL` sets the default lanes when `serve` has no `--parallel`: a whole number 1 to 4096 or `auto`; the flag wins when both are given, a blank value keeps the default, and any other value is refused by name at startup (#3685, for #3684). Thanks to @bikepresentball.
Expand Down Expand Up @@ -32,8 +36,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

- Qwen3.5-2B on Metal: a new stream's prompt runs one chunk a call at the same cuts as before, so other streams' decode rounds run between its chunks instead of waiting for the whole prompt; a cancel between chunks keeps the state at the last chunk's end (#3090, refs #3021).



- Tools: add tf-h3-image to compare MiniMax-H3-Image Metal transformer steps with exported picture cases (#2766).

- Qwen3.8-27B on Metal with `TF_QWEN27_METAL_KV_PAGES=1`: a stream that opens a slot is promised the KV pages of its prompt and one widest pass instead of every slot being promised its whole window at load; a pass past that promises the rest before it takes a page and fails with `LaneMemory` before any page is taken when the pool cannot meet it, and a stream that leaves, a failed or requeued prompt pass, a reset and a move to slot 0 give back the slot's pages and promise. Without the flag nothing changes (#3377, refs #1293). Thanks to @CodingEmil.
Expand Down
76 changes: 76 additions & 0 deletions docs/recipes/ling-bf16-forward.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Ling tiny bf16 forward diagnostic

This diagnostic runs the 24-layer Ling-3.0-tiny backbone on Metal.
It reuses Kimi's row projections, RMS, residual add, KDA, MLA and expert combine;
Ling's grouped route and three MLA glue kernels; and LFM3's bf16-point SwiGLU.
No GPU kernel source or registration changes are introduced. `kernel_contract.zig`
only registers the separate diagnostic build module.

The supported checkpoint is `inclusionAI/Ling-3.0-tiny`, revision
`9a98e35fe1c9ee255f78dd64771c7ae15a799481` (32 bf16/F32 shards).
The forward refuses incompatible config geometry, quantization and expert clamps.
Checkpoint tensors stay mapped; interleaved projection weights are cached separately.
This is a correctness diagnostic, not serving or a qualified performance path.

## Run

Use the repository's pinned Zig and build for the compatible Apple CPU target:

```sh
zig build tf-ling-forward tf-ling-checkpoint tf-ling-projection -Dcpu=apple_m1
export TF_LING_CHECKPOINT=/path/to/Ling-3.0-tiny
export TF_LING_PYTHON=/path/to/python-with-torch-and-safetensors
zig build test-ling-forward -Dcpu=apple_m1
```

`TF_LING_PYTHON` takes precedence; otherwise the oracle uses `python3` on PATH.
Without the checkpoint or Python dependencies, the optional check prints an explicit
`SKIP`. It never downloads weights or changes another model service.
For persistent artifacts, run the wrapper directly:

```sh
python3 tools/zig/ling_forward_check.py --binary zig-out/bin/ling-forward --out /tmp/ling-receipts
```

The fixed IDs are `(37*t + 11) % 157182`, at 2, 8 and 32 rows.
The native diagnostic compares whole execution with single-row chunks and a fresh
instance restored after token 1. It compares logits, KDA recurrent/conv state and
MLA cache bytes. A truncated snapshot must be rejected.
Both the chunked and resumed instances' final recurrent states and caches are compared
with the whole run. A temporary one-byte corruption of the resumed final MLA slot
was planted after the logits check: the new state comparison failed, and the fault
was removed before the clean 2/8/32-row rerun.
Forced late-Forward and early-MLA buffer errors also test owned-buffer rollback.
Pipeline/library error cleanup is guarded by `errdefer`; driver object counts are
not independently instrumented by these allocator-failure checks.
The snapshot is an internal same-checkpoint diagnostic format, not a serving or
portable checkpoint handover API. These receipts exercise in-process restoration.
The oracle remains `families/ling/oracle/ling_forward.py`, using native expert picks
for both its float64 and bf16-point runs. Its optional `--layer-trace` writes residual
hidden rows without changing logits. No second reference formula is introduced.

## Measured numerical distances

On an Apple M5 Metal device, all native logits were finite, all next-token argmaxes
agreed with both reference precisions, and all three whole/chunk/resume scenarios
completed with exact bytes. Numerical acceptance is **unresolved**, not passed.
The reference's rounding nodes include linears, SiLU, products, norms and residuals.

| Rows | Metal RMS | bf16-point RMS | Metal maximum | bf16-point maximum | Rows with larger Metal RMS |
| --- | --- | --- | --- | --- | --- |
| 2 | 0.0317046309744 | 0.0298559560322 | 0.213487908284 | 0.185932075501 | 2/2 |
| 8 | 0.0292602858773 | 0.0310663639610 | 0.213487908284 | 0.217792950829 | 5/8 |
| 32 | 0.0200687156935 | 0.0205596869419 | 0.213487908284 | 0.217792950829 | 19/32 |

These are distances from float64 on the same native route picks. The forced-route
selection gap is 0.00135229020 at 2/8 rows and 0.01254995249 at 32 rows.
The native route need not choose the reference's preferred set; forcing records that
difference instead of mixing reference routing with native routing.
Aggregate improvement at 8/32 rows does not establish a per-row or per-column bound.
The JSON receipts retain every row's RMS, maximum and argmax for both precisions.
Whether the maintainer's acceptance comparison is aggregate or row-wise remains a
review question; the implementation does not increase a tolerance to accept itself.

Runs used one low-priority Ling GPU job at a time beside an existing model service;
no timing or isolated performance result is claimed. The wrapper refuses a macOS
run with system-wide free memory at or below 40%.
93 changes: 93 additions & 0 deletions tools/zig/ling_forward_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
"""Run native Ling whole/chunk/resume checks beside the one FP64 oracle on identical routed picks."""
import argparse
import array
import json
import math
import os
from pathlib import Path
import shutil
import struct
import sys
import subprocess
import tempfile

ROOT = Path(__file__).resolve().parents[2]


def compare(native, reference):
data = reference.read_bytes()
if data[:8] != b"TFLINGF2":
raise ValueError("unexpected oracle format")
tokens, vocab, layers, topk = struct.unpack_from("<4I", data, 8)
at = 36 + tokens * 4
exact = array.array("d", data[at:at + tokens * vocab * 8])
rounded = array.array("d", data[at + tokens * vocab * 8:at + tokens * vocab * 16])
metal = array.array("f", native.read_bytes())
if len(metal) != tokens * vocab:
raise ValueError("native logits shape mismatch")
rows = []
for row in range(tokens):
lo, hi = row * vocab, (row + 1) * vocab
a, b, g = exact[lo:hi], rounded[lo:hi], metal[lo:hi]
if not all(math.isfinite(v) for v in g):
raise ValueError("non-finite native logits")
pair = {}
for name, values in (("metal", g), ("bf16", b)):
errors = [x - y for x, y in zip(values, a)]
pair[name] = {"rms": math.sqrt(math.fsum(x*x for x in errors) / vocab),
"max": max(map(abs, errors)), "top": max(range(vocab), key=values.__getitem__)}
pair["top64"] = max(range(vocab), key=a.__getitem__)
rows.append(pair)
result = {"tokens": tokens, "moe_layers": layers, "top_k": topk, "rows": rows,
"forced_gap": struct.unpack_from("<d", data, 28)[0]}
for name in ("metal", "bf16"):
result[name] = {"rms": math.sqrt(math.fsum(r[name]["rms"]**2 for r in rows) / tokens),
"max": max(r[name]["max"] for r in rows)}
result["rows_above_bf16_rms"] = sum(r["metal"]["rms"] > r["bf16"]["rms"] for r in rows)
result["top_tokens_equal"] = all(r["metal"]["top"] == r["bf16"]["top"] == r["top64"] for r in rows)
result["accuracy_acceptance"] = "unresolved; distances reported without relaxing the reference bound"
return result


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", type=Path, required=True)
parser.add_argument("--counts", type=int, nargs="+", default=[2, 8, 32])
parser.add_argument("--out", type=Path)
args = parser.parse_args()
checkpoint = os.environ.get("TF_LING_CHECKPOINT")
if not checkpoint or not (Path(checkpoint) / "model.safetensors.index.json").is_file():
print("SKIP Ling full forward: set TF_LING_CHECKPOINT to the bf16 Ling-3.0-tiny checkpoint")
return
python = os.environ.get("TF_LING_PYTHON") or shutil.which("python3")
if not python:
print("SKIP Ling oracle: set TF_LING_PYTHON or install python3 on PATH")
return
probe = subprocess.run([python, "-c", "import torch, safetensors"], capture_output=True)
if probe.returncode:
print("SKIP Ling oracle: selected Python needs torch and safetensors")
return
with tempfile.TemporaryDirectory(prefix="ling-forward-") as temp:
out = args.out or Path(temp)
out.mkdir(parents=True, exist_ok=True)
for count in args.counts:
native, reference = out / f"native-{count}.f32", out / f"reference-{count}.bin"
if sys.platform == "darwin":
pressure = subprocess.check_output(["memory_pressure"], text=True)
free = int(pressure.split("System-wide memory free percentage:")[-1].strip().rstrip("%"))
if free <= 40:
raise RuntimeError("memory free is at or below 40%; refusing the Ling GPU run")
subprocess.run([str(args.binary.resolve()), checkpoint, str(native), str(count)], check=True)
oracle = ROOT / "zig/src/families/ling/oracle/ling_forward.py"
subprocess.run([python, str(oracle), checkpoint, str(reference), "--tokens", str(count),
"--picks", str(native) + ".picks"], check=True)
result = compare(native, reference)
(out / f"summary-{count}.json").write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps(result), flush=True)
if not result["top_tokens_equal"]:
raise RuntimeError("top-token mismatch; inspect the numerical receipt")
print("Ling exactness checks completed; numerical acceptance remains a separate review decision")


if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions zig/build/kernel_contract.zig
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void {
/// macOS: tf-kernel-contract over the engine's Metal kernels; `kernel-contract` runs it on this Mac's GPU.
pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal_mod: *std.Build.Module, engine: *std.Build.Module, sources: *std.Build.Module, kimi_metallib: *std.Build.Module) void {
@import("rotary_sweep.zig").steps(b, target, metal_mod);
@import("ling_forward.zig").steps(b, target, optimize, metal_mod, sources, kimi_metallib);
const exe = b.addExecutable(.{ .name = "tf-kernel-contract", .root_module = b.createModule(.{
.root_source_file = b.path("zig/tests/contract/metal_main.zig"),
.target = target,
Expand Down
79 changes: 79 additions & 0 deletions zig/build/ling_forward.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//! Local bf16 Ling forward diagnostics over existing registered Metal kernels.
const std = @import("std");
pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal_mod: *std.Build.Module, sources: *std.Build.Module, kimi_metallib: *std.Build.Module) void {
const ling_ck = b.createModule(.{
.root_source_file = b.path("zig/src/families/ling/checkpoint.zig"),
.target = target,
.imports = &.{
.{ .name = "metal", .module = metal_mod },
.{ .name = "safetensors", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target }) },
},
});
const ling_kernels = b.createModule(.{ .root_source_file = b.path("zig/src/families/kimi_k3/kernels.zig"), .target = target, .imports = &.{.{ .name = "metal", .module = metal_mod }} });
const ling_rows = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_rows.zig"), .target = target, .imports = &.{
.{ .name = "metal", .module = metal_mod },
.{ .name = "kernel_sources", .module = sources },
.{ .name = "ling_checkpoint", .module = ling_ck },
.{ .name = "kimi_kernels", .module = ling_kernels },
.{ .name = "kimi_metallib", .module = kimi_metallib },
} });
const ling_kda = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_kda.zig"), .target = target, .imports = &.{
.{ .name = "metal", .module = metal_mod },
.{ .name = "ling_checkpoint", .module = ling_ck },
.{ .name = "kimi_kernels", .module = ling_kernels },
.{ .name = "ling_rows", .module = ling_rows },
} });
const ling_sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/ling/sources.zig") });
const ling_mla = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_mla.zig"), .target = target, .imports = &.{
.{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck },
.{ .name = "kimi_kernels", .module = ling_kernels }, .{ .name = "ling_rows", .module = ling_rows },
.{ .name = "ling_sources", .module = ling_sources },
} });
const ling_moe = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_moe.zig"), .target = target, .imports = &.{
.{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck },
.{ .name = "kimi_kernels", .module = ling_kernels }, .{ .name = "ling_rows", .module = ling_rows },
.{ .name = "ling_sources", .module = ling_sources },
} });
const ling_forward = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_forward.zig"), .target = target, .imports = &.{
.{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck },
.{ .name = "ling_rows", .module = ling_rows }, .{ .name = "ling_kda", .module = ling_kda },
.{ .name = "ling_mla", .module = ling_mla }, .{ .name = "ling_moe", .module = ling_moe },
} });
const ling_forward_tool = b.addExecutable(.{ .name = "ling-forward", .root_module = b.createModule(.{
.root_source_file = b.path("zig/tests/ling_forward.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
.imports = &.{ .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck }, .{ .name = "ling_rows", .module = ling_rows }, .{ .name = "ling_forward", .module = ling_forward }, .{ .name = "ling_mla", .module = ling_mla } },
}) });
b.step("tf-ling-forward", "Build the native Ling bf16 full-forward diagnostic").dependOn(&b.addInstallArtifact(ling_forward_tool, .{}).step);
const python = b.graph.environ_map.get("TF_LING_PYTHON") orelse "python3";
const full_check = b.addSystemCommand(&.{ python, "tools/zig/ling_forward_check.py", "--binary" });
full_check.addArtifactArg(ling_forward_tool);
b.step("test-ling-forward", "Optional real-checkpoint Ling exactness and FP64 comparison receipts").dependOn(&full_check.step);
const ling_projection = b.addExecutable(.{ .name = "ling-projection", .root_module = b.createModule(.{
.root_source_file = b.path("zig/tests/ling_projection.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
.imports = &.{
.{ .name = "metal", .module = metal_mod },
.{ .name = "ling_checkpoint", .module = ling_ck },
.{ .name = "kimi_metallib", .module = kimi_metallib },
.{ .name = "kimi_kernels", .module = ling_kernels },
.{ .name = "ling_rows", .module = ling_rows },
.{ .name = "ling_kda", .module = ling_kda },
.{ .name = "ling_mla", .module = ling_mla },
.{ .name = "ling_moe", .module = ling_moe },
},
}) });
b.step("tf-ling-projection", "Build Ling's real bf16 projection diagnostic").dependOn(&b.addInstallArtifact(ling_projection, .{}).step);
const ling_checkpoint = b.addExecutable(.{ .name = "ling-checkpoint", .root_module = b.createModule(.{
.root_source_file = b.path("zig/tests/ling_checkpoint.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
.imports = &.{ .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck } },
}) });
b.step("tf-ling-checkpoint", "Build the native bf16 Ling checkpoint validator").dependOn(&b.addInstallArtifact(ling_checkpoint, .{}).step);
}
Loading