diff --git a/CHANGELOG.md b/CHANGELOG.md index e43dd23b524..24215c79db3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Metal: opt-in GLP additive control vectors for Qwen3.8-27B through `--glp FILE` and `--glp-alpha`, in the GLP format of the `weightless` project; startup reports the escaped filename, the file's SHA-256 and that replies are steered, other modes and malformed files are refused, saved conversation states carry the file hash and strength in their identity, and output is unchanged without `--glp` (#1835, fixes #1834). Thanks @BlivionIaG. + - Metal contracts, Qwen3.5 CUDA drafts and Qwen27 lanes: four more busy 600-line sources split into their own files, leaving room under the cap; no call site changes (#5595). - Inkling 2 Small EXL3 on Metal: the non-looped 48-layer forward, its Metal ops with kernel-contract gates and launch-limit records, and disk-pack loader and oracle tests; Inkling 2 Mini is unchanged (#5105). Thanks to @trozzelle. diff --git a/README.md b/README.md index 0bcbcf30cfe..84b814848a0 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ See [the chat command](docs/chat.md) for its flags and the serve flags it passes Cortheon mode, every serve flag, the Mac app and TensorFold Starlight. - [Supported models](docs/supported-models.md): which checkpoints run on which machines, models on disk and model discovery. - [Living Weights (experimental)](docs/living-weights.md): teach a running model new facts in its own weights. +- [Control vectors](docs/control-vectors.md): steer Qwen3.8-27B on Metal with `--glp FILE` and `--glp-alpha ALPHA`, the vector file's format and how one is brought. - [Installation runbook](RUNBOOK.md): macOS and CUDA installation, paired Metal serving and troubleshooting. - [Windows](docs/WINDOWS.md), [TensorFold Web](docs/web.md) and [the Mac app](app/README.md). - [API](docs/api.md), [Cortheon mode](docs/cortheon.md) and [known issues](docs/known-issues.md). diff --git a/build.zig b/build.zig index 448a9a9971b..aa7c1bd8bc8 100644 --- a/build.zig +++ b/build.zig @@ -117,6 +117,10 @@ pub fn build(b: *std.Build) void { @import("zig/build/quant_geometry_host.zig").steps(b, test_step); @import("zig/build/glm_tfq3_host.zig").steps(b, test_step); @import("zig/build/stage.zig").steps(b, test_step); + @import("zig/build/glp.zig").tests(b, test_step); + @import("zig/build/glp_steer.zig").tests(b, test_step); + @import("zig/build/glp_serve.zig").tests(b, test_step); + @import("zig/build/steer.zig").tests(b, test_step); @import("zig/build/dsv41_metal.zig").hostSteps(b); if (b.graph.host.result.os.tag == .macos) { const step5_mods = metalEngineModules(b, b.graph.host, .Debug, draft_ids); diff --git a/docs/control-vectors.md b/docs/control-vectors.md new file mode 100644 index 00000000000..0e3ab7bbce9 --- /dev/null +++ b/docs/control-vectors.md @@ -0,0 +1,213 @@ +# Control vectors + +A control vector steers a model's residual stream at inference time. It is a +direction per layer: at the output of a block, the direction, scaled by the +strength, is added to the residual stream as a bias. Nothing is written to the +checkpoint. Steering is disabled unless the server starts with `--glp`. + +TensorFold reads these vectors on Metal for Qwen3.8-27B. The container, the +kernel and the serve surface are all native Zig. The engine ships the mechanism +only: a vector file is supplied by the operator, and the repository carries no +derived direction files. + +## Serving one + +``` +tensorfold serve TensorFold/Qwen3.8-27B-MLX-4bit --glp vector.gguf --glp-alpha 1.0 +``` + +`--glp` names the file and `--glp-alpha` the strength. Without `--glp-alpha` +the file's own `glp.alpha_default` applies. The applied fp32 strength must be +finite and above 0. + +At startup the server names the file it loaded, the SHA-256 of that file's +exact bytes, and says that replies are steered. + +The file name is written escaped, so a name with a newline or a quote cannot +add a line of its own. The file hash is taken over the bytes the server read +once, before the model loads; it is the hash to compare against the file you +meant to load. The tensor digest is the separate SHA-256 over the direction +tensors that a file may claim in `glp.content_sha256`. The engine repeats that +replies are steered, with the file hash, when the vector is in force. + +Saved conversation states also include that file hash and the applied strength +in their identity. Changing either starts those states cold; without `--glp` +the existing policy key is unchanged. + +A file the server cannot apply is refused and the server does not start. + +## Bringing a vector + +The repository carries none, and this page names none to download. A vector is +derived by the operator, for the style or topic they want a model to lean +toward, and the prerequisites are theirs to meet: + +- Two sets of prompts that differ in the one thing the vector should carry, + and activations collected from Qwen3.8-27B (the 5120-wide model) at the + output of its blocks on both sets. +- One direction per layer from those activations, for example the difference + of the two sets' mean activations, in fp32. llama.cpp's `cvector-generator` + writes this container; any tool that writes the format below works. +- Layer ids of 1 to 63 for the 64-block model, zero-based (see below), in a + file whose `glp.base_model`, if present, names the checkpoint served. + +The strength is the operator's to find on their own prompts: a direction added +too strongly degrades the text, and one added too weakly changes nothing. The +reader does not judge either. + +## Add only + +A vector is applied by adding the direction to the residual stream. A file +whose mode is missing is an `add` file, as the format specifies, so a llama.cpp +control vector works as it stands. A file that names another mode is refused, +`project` included, and is never read as an `add` file. + +## What the server refuses + +The reader fails closed rather than guessing. + +| Refused | Why | +| --- | --- | +| `glp.mode` (or `dspark.mode`) is anything but `add` | Only add vectors are applied. A file that names `project` is refused by name, not coerced to `add`. | +| `glp.hook_point` is not `residual_stream_post_layer` | The vector was derived at another site. | +| `glp.rank` is not the integer 1 | The reader implements rank 1. | +| `glp.spec_version` is not 1 | The reader implements version 1. | +| `glp.alpha_default` is not a floating-point value | A malformed strength is not silently replaced with 1. | +| A direction holds a NaN or an infinity | The direction is added as it stands, so every value has to be finite. | +| The digest does not match the bytes | The file says one thing and holds another. | +| `glp.content_sha256` is not text | A digest that cannot be read is not reported as verified, so the file is refused instead. | +| A tensor's offset or byte count runs past the file | The bounds are checked before the bytes are read, and a value that would wrap is refused, not wrapped. | +| A metadata array nests deeper than four | The reader bounds its own recursion; no control vector names an array inside an array this deep. | +| One layer is named twice | `direction.5` and `direction.05` both parse as layer 5; a file has one direction per layer. | +| A layer id is past the checkpoint's depth | The checkpoint's `num_hidden_layers` is read at startup, so the file is refused before the model loads. | +| The width does not match the checkpoint | The vector is for another model. | +| The base model does not match | The vector was derived from another checkpoint. The names are compared without their owners, because a checkpoint is often a quantization of another repo's model under a new name. | +| A Gemma checkpoint | A Gemma is never steered. | +| A CUDA or ROCm backend | Only the Metal engine steers. | +| Any other model family | Only Qwen3.8-27B takes a control vector. | + +A file whose `glp.derived_at` differs from its `glp.hook_point` is a warning, +not a refusal: the vector is applied at the residual stream either way. + +## The layer a direction names + +`direction.N` is the layer index `N`, and the layers are zero-based: `direction.N` +is the output of the N-th block, the residual stream as that block leaves it. +Layer 0 is not steerable, so a file for a 64-block model names layers 1 to 63. + +This is worth stating because the alternative is silently wrong. The container +follows llama.cpp, and llama.cpp's own generator writes `direction.{il+1}` while +its applier reads `direction.il`: the two cancel, so the applier's numbering is +the one a file means. An off-by-one here does not fail loudly either, because +adjacent layers' directions are highly correlated and a stack shifted by one +layer still produces plausible output. + +The file says so itself. A vector for this model can carry its layer list in +its metadata: + +``` +glp.layer_ids_zero_based = 10,11,12,...,58 +``` + +and this reader refuses a file whose tensor names and that list disagree. + +The direction lands on the residual stream after a block, and the block that +follows reads the result: the direction is added before the next block's +normalisation sees the stream. + +## How the bias is applied + +A steered layer takes one dispatch, the same one an unsteered layer takes: the +norm that adds the block's output to the residual stream also adds the +direction, scaled by the strength, to the row, and the normalisation that +follows reads the result. There is no separate pass over the residual row. + +The arithmetic is pinned by the kernel contract +(`zig/src/core/contract/steer.zig`): a float64 reference and the bound the +kernel's own fp32 arithmetic is checked against. The GPU half of that contract +(`zig/tests/contract/metal_qwen27_steer.zig`) needs a Mac and has to be run +there; this page carries no timing or output measurement for it. + +## The file + +The container is GGUF v3, read by `zig/src/core/glp_container.zig`, the GLP +reader for the subset a vector needs. The metadata follows the GLP standard: + +| Key | Meaning | +| --- | --- | +| `glp.spec_version` | 1. | +| `glp.mode` | `add`, or absent. | +| `glp.rank` | 1. | +| `glp.hook_point` | `residual_stream_post_layer`. | +| `glp.derived_at` | The site the direction was captured at. It is a site, not a time: the format's own validator refuses a value that is not a hook name, and a file whose `derived_at` differs from its `hook_point` is a transferred vector, which is warned about. | +| `glp.created` | The day the file was written. | +| `glp.alpha_default` | The strength the file applies with by default. | +| `glp.method` | How the numbers were made, for example `difference_of_means_last_token_per_layer`. | +| `glp.contrast` | What the two prompt sets contrast. | +| `glp.base_model`, `glp.base_revision` | The checkpoint the vector came from. | +| `glp.layer_ids_zero_based` | The layers the file holds. | +| `glp.content_sha256` | SHA-256 over the tensor bytes, which the reader checks. | + +The tensors are `direction.N`, fp32, one per layer, each the width of the +residual stream. + +The file also says what it is, for a consumer that reads the header before it +reads the directions: `general.name`, `general.description`, `general.author`, +`general.license`, `general.base_model.*` (the repo it came from), and +`controlvector.model_hint` and `controlvector.layer_count`. The reader keeps +these when the file carries them; `tf-glp-check rewrite` writes a file back out +with the fields it read. + +### The checkpoint the file names + +`glp.base_model` is the checkpoint the vector came from, and the server refuses +a vector whose checkpoint is not the one it is serving. The check compares +names: the served checkpoint's model name has to be the vector's model name or +start with it, so a conversion published under a longer name takes the vector +and a different model does not. + +The same weights under another name are refused with it. A file can be +re-stamped for that name: + +``` +tf-glp-check rewrite vector.gguf vector-mlx.gguf \ + --repo mlx-community/Qwen3.8-27B-4bit --revision REV +``` + +The directions stay the same bytes and the digest over them does not move; only +the name the file carries changes. That is a claim the operator makes, not one +the reader verifies: the check is a name comparison, so only re-stamp a file +for a checkpoint that holds the same weights. + +## The integration test + +A file that one implementation accepts has to mean the same thing to another. +The GLP format is defined by the `weightless` project (@msuiche); its +`docs/spec/GLP.md` at commit `b181a07d` is the specification this reader +implements, and `plugins/vllm/weightless_steer/container.py` at the same commit +is the container reader the parity test compares against. This repository does +not vendor either: the test takes a checkout of that commit and reads the +reader as a package. + +``` +zig build tf-glp-check +python3 tools/zig/glp_parity.py --reference PATH/TO/weightless \ + --vector vector.gguf --vector PATH/TO/another-vector.gguf +``` + +Four legs, over the same files: + +| Leg | What it checks | +| --- | --- | +| read | The reader in Zig and the reference reader on one file: the layer ids, the metadata and every direction's bytes are equal. | +| rewrite | The file read in Zig and written out again, read by the reference: the numbers, the hook point and the strength survive the round trip. | +| digest | The file's own `glp.content_sha256` over the tensor payloads, hashed the same way on both sides. | +| file hash | The SHA-256 the reader reports for the file's bytes is Python's SHA-256 of the same file. | + +The reader that does the Zig half is `tf-glp-check`, which prints the reader's +view of a file and writes its directions out as bytes, so the two sides can be +compared exactly rather than approximately. + +The test needs `numpy` for the reference reader, and a `weightless` checkout at +commit `b181a07d`. Nothing of the reference is committed here, and no vector is +either: the file is supplied when the test runs. diff --git a/docs/run-guide.md b/docs/run-guide.md index 43f0bc07d17..53f503e4f2e 100644 --- a/docs/run-guide.md +++ b/docs/run-guide.md @@ -113,6 +113,7 @@ The read-only [`/memory` diagnostics](memory-diagnostics.md) report process foot available backend allocation counters, and the applied retained-prefix plan without changing memory policy. The binary's `capabilities --json` response lists its supported flags and platform-specific values. +The GLP flags are left out where the build cannot serve them (everything but Metal on macOS), though they still parse there so their refusal names the engine. `serve MODEL --help` prints usage without loading a model. | Flag | Meaning | @@ -154,6 +155,8 @@ The binary's `capabilities --json` response lists its supported flags and platfo | `--drafter DRAFTER` | An external drafter, as a directory or a repo id in the Hugging Face cache, for models that take one (Gemma 4 31B's recipe names its drafter); `none` serves without one. Without the flag, Qwen3.8-27B pairs DFlash2 when the cache holds it (never downloaded, not on HIP): one line names it, and serve runs without it if it does not open. | | `--drafter-bits 0\|4` | Drafter weight precision where the model offers a choice: 4 bits (the default), or 0 to keep bf16. Qwen3.8-27B on CUDA takes 4 only. | | `--record DIR` | Write each stream's committed tokens, positions and tapped rows under DIR, for drafter training. CUDA Nemotron only; a single stream runs through the lane rounds, and recording stops below 25 GiB free disk. | +| `--glp FILE` | A GLP control vector whose directions are added to the residual stream, one per layer; off unless given. Qwen3.8-27B on Metal takes one; the file's width and base model must match the checkpoint, and a Gemma checkpoint, CUDA and ROCm are refused. Only add vectors are applied. | +| `--glp-alpha ALPHA` | The strength the vector applies with, above 0; the file's own `glp.alpha_default` by default. | | `--keep-warm SECONDS` | Keep the Metal GPU active while idle for this long after a request, default 900; zero disables it. | | `--cfg-gamma GAMMA` | Drama speech on Metal and CUDA: semantic guidance strength, finite 1–5; 0/default disables it. Only reference-conditioned requests are guided. Enabled replies report `X-Cfg-Gamma`; codec heads stay conditional. | | `--cfg-allow-request-gamma` | Drama speech on Metal and CUDA: allow a finite 1–5 `X-Cfg-Gamma` request header; invalid values return 400 before engine submission. Without this opt-in, the server's gamma is fixed. | @@ -206,6 +209,12 @@ a long conversation. Where the cache cannot keep a whole context, the server als at each prompt's history end, so a turn whose template drops the last reply's reasoning resumes there. Replies are the same tokens as a fresh prompt pass; `TF_QWEN27_SLOT_RESUME=0` turns both off. +`--glp` reads its file once at startup, and the startup line names the file (escaped), the SHA-256 of its exact bytes and +that replies are steered, with the strength in force, the layers the file names, the checkpoint the vector was derived from +and whether the file's own tensor digest matched; a vector derived at another site is reported as a warning, not refused. +The [control vector guide](control-vectors.md) covers the format, the layer a direction names, the files the server +refuses and how a vector is brought. + Sampling defaults come from the checkpoint's `generation_config.json`, then serve flags and request fields override them. `--context 0` is family-specific; use a positive limit for GLM and inspect the capacity reported at startup. The supported environment variables are listed in `capabilities --json`, including API keys, request logging and Hugging Face cache paths. diff --git a/tools/zig/glp_parity.py b/tools/zig/glp_parity.py new file mode 100644 index 00000000000..a7f367104d8 --- /dev/null +++ b/tools/zig/glp_parity.py @@ -0,0 +1,157 @@ +"""GLP control vectors in Zig against weightless's container reader: the same layers, numbers and digest.""" +from __future__ import annotations + +import argparse +import hashlib +import importlib.util +import json +import subprocess +import sys +import types +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] + + +def load_reference(reference: Path): + """weightless's container module, read from the checkout; torch is stubbed when it is absent.""" + path = reference / "plugins" / "vllm" / "weightless_steer" / "container.py" + if not path.is_file(): + raise SystemExit(f"{path} is not there: point --reference at a weightless checkout") + try: + import torch # noqa: F401 + except ImportError: + # The module imports torch at the top; the parse below needs numpy alone. + sys.modules["torch"] = types.ModuleType("torch") + spec = importlib.util.spec_from_file_location("weightless_container", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def direction_ids(tensors: dict) -> list[int]: + """The layer ids the file's tensor names carry, ascending.""" + ids = [] + for name in tensors: + if not name.startswith("direction."): + continue + ids.append(int(name.split(".")[1])) + return sorted(ids) + + +def payload_digest(tensors: dict) -> str: + """SHA-256 over the tensor payloads in the order the file holds them.""" + h = hashlib.sha256() + for values in tensors.values(): + h.update(values.astype(" None: + """The reference's view against ours: the ids, the metadata and every direction's bytes.""" + their_ids = direction_ids(tensors) + if their_ids != ours["layers"]: + problems.append(f"layer ids differ: reference {their_ids[:4]}..{their_ids[-1:]} against ours {ours['layers'][:4]}..{ours['layers'][-1:]}") + return + for key, field in (("glp.hook_point", "hook_point"), ("glp.method", "method"), + ("glp.contrast", "contrast"), ("glp.base_model", "base_model"), ("glp.base_revision", "base_revision")): + if key in meta and meta[key] != ours[field]: + problems.append(f"{key} is {meta[key]!r} for the reference and {ours[field]!r} for us") + if "glp.alpha_default" in meta and float(meta["glp.alpha_default"]) != float(ours["alpha"]): + problems.append(f"glp.alpha_default is {meta['glp.alpha_default']} for the reference and {ours['alpha']} for us") + if "glp.layer_ids_zero_based" in meta: + declared = [int(part) for part in str(meta["glp.layer_ids_zero_based"]).split(",")] + if declared != their_ids: + problems.append(f"the file names layers {declared[:4]}..{declared[-1:]} and holds {their_ids[:4]}..{their_ids[-1:]}") + + step = len(tensors[next(iter(tensors))].astype(" int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--reference", required=True, help="a weightless checkout") + ap.add_argument("--vector", required=True, action="append", help="a control vector file to compare") + ap.add_argument("--exe", default=str(ROOT / "zig-out" / "bin" / "tf-glp-check"), help="tf-glp-check") + ap.add_argument("--work", default="/tmp/tf-glp-parity", help="folder for the receipts") + args = ap.parse_args(argv) + + container = load_reference(Path(args.reference)) + work = Path(args.work) + work.mkdir(parents=True, exist_ok=True) + problems: list[str] = [] + checked = 0 + agreed = 0 + + for vector in args.vector: + path = Path(vector) + checked += 1 + before = len(problems) + if not path.is_file(): + problems.append(f"{path} is not there") + print(f"{path.name}: missing") + continue + meta, tensors = container.read_gguf_cvec(str(path)) + + receipt = work / "ours.json" + blob_path = work / "ours.bin" + read = subprocess.run([args.exe, "read", str(path), str(receipt), str(blob_path)], capture_output=True, text=True) + if read.returncode != 0: + # The reference took the file and this reader did not: a difference the pair has to name. + problems.append(f"{path.name}: the reference reads it, this reader refuses it ({read.stdout.strip()})") + print(f"{path.name}: the reference reads it, this reader refuses it") + continue + ours = json.loads(receipt.read_text()) + blob = blob_path.read_bytes() + + compare(meta, tensors, ours, blob, problems) + if ours["file_sha256"] != hashlib.sha256(path.read_bytes()).hexdigest(): + problems.append(f"{path.name}: the reader's file SHA-256 is not the SHA-256 of the file's bytes") + + # The file read in Zig and written out again, then read by the reference. + rewritten = work / "rewritten.gguf" + subprocess.run([args.exe, "rewrite", str(path), str(rewritten)], check=True) + back_meta, back_tensors = container.read_gguf_cvec(str(rewritten)) + if direction_ids(back_tensors) != direction_ids(tensors): + problems.append(f"{path.name}: the rewrite holds different layers") + for layer in direction_ids(tensors): + if back_tensors[f"direction.{layer}"].astype(" 1e-6: + problems.append(f"{path.name}: the rewrite changed the strength") + + added = len(problems) - before + summary = (f"{len(tensors)} layers, {ours['width']} wide, alpha {ours['alpha']}, " + f"digest {ours['sha256'][:12]}, file sha256 {ours['file_sha256'][:12]}") + if added == 0: + agreed += 1 + print(f"{path.name}: {summary}: reference and Zig agree") + else: + print(f"{path.name}: {summary}: {added} difference(s)") + + for problem in problems: + print(f"differs: {problem}") + print(f"glp parity: {agreed}/{checked} files agree") + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/zig/test_glp_parity.py b/tools/zig/test_glp_parity.py new file mode 100644 index 00000000000..4f16bafe7ed --- /dev/null +++ b/tools/zig/test_glp_parity.py @@ -0,0 +1,140 @@ +"""The GLP parity comparator rejects mismatched values and layer identities.""" +from __future__ import annotations + +import contextlib +import hashlib +import io +import json +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import glp_parity as parity + +try: + import numpy # noqa: F401 + HAVE_NUMPY = True +except ImportError: + HAVE_NUMPY = False + + +class Compare(unittest.TestCase): + """The comparison the script runs on the two readers' views of one file.""" + + def setUp(self): + if not HAVE_NUMPY: + self.skipTest("numpy is required") + self.meta = { + "glp.mode": "add", + "glp.hook_point": "residual_stream_post_layer", + "glp.alpha_default": "1.0", + "glp.layer_ids_zero_based": "7", + } + self.tensors = {"direction.7": numpy.zeros(8, dtype=numpy.float32)} + self.tensors["direction.7"][3] = 1.0 + self.ours = { + "hook_point": "residual_stream_post_layer", + "alpha": 1.0, + "method": "", + "contrast": "", + "base_model": "", + "base_revision": "", + "sha256": "0" * 64, + "layers": [7], + } + self.blob = self.tensors["direction.7"].astype(" +// alpha * d is rounded on its own before the sum, as the contract's reference orders it: never one fused multiply-add. +#pragma clang fp contract(off) +using namespace metal; +typedef bfloat bfloat16_t; +typedef half float16_t; + +// The norm of a steered residual: the row is summed, the direction is added to it, then it is normalised. +[[kernel]] void custom_kernel_q27_norm_steer_bfloat16_t_bfloat16_t_bfloat16_t_floatc_int32_t_bfloat16_t_bfloat16_t_float_float_float( + const device bfloat16_t* H [[buffer(0)]], + const device bfloat16_t* R [[buffer(1)]], + const device bfloat16_t* Wt [[buffer(2)]], + const constant float* eps [[buffer(3)]], + const device int32_t* dims [[buffer(4)]], + device bfloat16_t* HO [[buffer(5)]], + device bfloat16_t* XO [[buffer(6)]], + device float* XS [[buffer(7)]], + const device float* DIR [[buffer(8)]], + constant float& ALPHA [[buffer(9)]], + uint simdgroup_index_in_threadgroup [[simdgroup_index_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { +Q27_SPECIALIZE + + const uint t = thread_position_in_threadgroup.x; + const uint m = threadgroup_position_in_grid.y; + const int M = dims[0], MP = dims[1]; + constexpr int E = 16; + constexpr int TPG = K / E; + threadgroup float sq_parts[TPG / 32]; + if (int(m) >= M) { + if ((t & 3) == 0) XS[(t >> 2) * MP + m] = 0.0f; + return; + } + const int base = int(m) * K + int(t) * E; + const int dbase = int(t) * E; + float hv[E]; + float dv[E]; + for (int i = 0; i < E; i++) { + // The residual as the block before it left it, in the precision the stream carries. + hv[i] = float(bfloat(float(H[base + i]) + float(R[base + i]))); + // The direction's own stretch, read once. + dv[i] = DIR[dbase + i]; + } + + // What the stream holds after the direction is added to it, and the squares the normalisation reads. + float pv[E]; + float ss = 0.0f; + for (int i = 0; i < E; i++) { + const float d = dv[i]; + const float step = ALPHA * d; + // a zero step leaves the rounded residual alone, so a negative zero stays negative + const float v = step == 0.0f ? hv[i] : (hv[i] + step); + const bfloat rounded = bfloat(v); + HO[base + i] = rounded; + pv[i] = float(rounded); + ss = fma(pv[i], pv[i], ss); + } + ss = simd_sum(ss); + if (thread_index_in_simdgroup == 0) sq_parts[simdgroup_index_in_threadgroup] = ss; + threadgroup_barrier(mem_flags::mem_threadgroup); + float total = 0.0f; + for (int i = 0; i < TPG / 32; i++) total += sq_parts[i]; + const float inv = metal::rsqrt(total / float(K) + eps[0]); + float xv[E]; + for (int i = 0; i < E; i++) { + const bfloat x = bfloat(float(Wt[dbase + i]) * (pv[i] * inv)); + XO[base + i] = x; + xv[i] = float(x); + } + // a group's 64 values summed in order from zero, as the lane projection's sums are: its four threads take turns + float gs = 0.0f; + for (uint turn = 0; turn < 4; turn++) { + if ((t & 3) == turn) for (int i = 0; i < E; i++) gs += xv[i]; + gs = simd_shuffle(gs, ushort((thread_index_in_simdgroup & ~3u) | turn)); + } + if ((t & 3) == 0) XS[(t >> 2) * MP + m] = gs; + +} diff --git a/zig/persistence_policy_test.zig b/zig/persistence_policy_test.zig index dc7e699de0f..fe8442d62f8 100644 --- a/zig/persistence_policy_test.zig +++ b/zig/persistence_policy_test.zig @@ -23,6 +23,15 @@ test "persistence identity: Qwen Metal loaded ANE columns miss with the same pro try fixture.misses(before, matching, &.{ other_share, qwen.withPolicy(7, &h) }); } +test "persistence identity: Qwen Metal control vector and strength miss with the same probe" { + var file_sha: [32]u8 = @splat(0x13); + const before = qwen.withSteering(7, &file_sha, 0.75); + const matching = qwen.withSteering(7, &file_sha, 0.75); + const stronger = qwen.withSteering(7, &file_sha, 1.5); + file_sha[31] ^= 1; + try fixture.misses(before, matching, &.{ qwen.withSteering(7, &file_sha, 0.75), stronger, 7 }); +} + test "persistence identity: GLM Metal resolved policy misses with the same probe" { const Config = @import("src/families/glm/config.zig").Config; const Prompt = struct { rows: u32 = 4096, sparse_nax: bool = true }; diff --git a/zig/runtime_sources/qwen27.zig b/zig/runtime_sources/qwen27.zig index 54a69c9f0da..373d6d15d7a 100644 --- a/zig/runtime_sources/qwen27.zig +++ b/zig/runtime_sources/qwen27.zig @@ -21,6 +21,7 @@ pub fn add(s: *Set) !void { if (kind == .norm or kind == .input_norm or kind == .mlp or kind == .mlp_rows) try s.rawFrom("qwen27", try std.fmt.allocPrint(s.a, "{s}-no-xs", .{@tagName(kind)}), &.{origin}, try quant.specializedSource(s.a, .{ .kind = kind, .k = 512, .n = 1024, .xs = false })); } + try s.rawFrom("qwen27", "norm-steer", &.{ks.norm_steer}, try @import("../src/families/qwen27/norm_steer_gpu.zig").source(s.a, 5120)); if (s.units) for (1..9) |sk| for ([_]u32{ 8, 16, 24, 32, 40, 48 }) |block| { const split: u32 = @intCast(sk); if (@import("../src/core/qk_projection.zig").threadgroupBytes(block, split) > 32768) continue; diff --git a/zig/src/core/contract.zig b/zig/src/core/contract.zig index 1955976aa13..1917f170736 100644 --- a/zig/src/core/contract.zig +++ b/zig/src/core/contract.zig @@ -10,6 +10,7 @@ pub const attention_pv = @import("contract/attention_pv.zig"); pub const rows = @import("contract/rows.zig"); pub const reference_threads = @import("contract/reference_threads.zig"); pub const affine = @import("contract/affine.zig"); +pub const steer = @import("contract/steer.zig"); pub const dense = @import("contract/dense.zig"); pub const bf16_round = @import("bf16_round"); pub const attention_range = @import("attention_range.zig"); diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 1f51b727413..9b31612f580 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -144,6 +144,7 @@ pub const all_metal = @import("penalties_records.zig").records ++ @import("hy4_records.zig").metal ++ @import("uocr_records.zig").records ++ @import("bolt_records.zig").records ++ + @import("steer_records.zig").metal ++ @import("ricursive_records.zig").records; pub const landed_cuda = registry.cuda ++ @import("muse_cuda_records.zig").cuda ++ @import("dory_cuda_records.zig").cuda ++ diff --git a/zig/src/core/contract/steer.zig b/zig/src/core/contract/steer.zig new file mode 100644 index 00000000000..dccd3fc0920 --- /dev/null +++ b/zig/src/core/contract/steer.zig @@ -0,0 +1,280 @@ +//! Control vectors: the operator's parameters, its float64 reference, the bounds the gates check and its launch. +const std = @import("std"); +const c = @import("contract.zig"); +const rows = @import("rows.zig"); +const bf16 = @import("bf16_round"); + +/// The hidden width this family's residual stream has. +pub const hidden = 5120; + +/// The elements a thread of the fused norm holds, so the row's squares are spread over `hidden / elements` threads. +pub const elements = 16; + +/// The threads a row is spread over, as the kernel launches it. +pub const threads = hidden / elements; + +/// The threadgroup memory the kernel's one set of partials takes, in the 16-byte units the Metal compiler allocates. +pub const group_memory = std.mem.alignForward(usize, (threads / 32) * 4, 16); + +/// The operator's parameters: the strength, the rows and the hidden width. +pub const Params = struct { + alpha: f32 = 1.0, + rows: usize = 1, + hidden: usize = hidden, +}; + +/// One call's inputs: the residual rows in bf16 and the direction in fp32, with the float64 reference beside them. +pub const Steer = struct { + a: std.mem.Allocator, + p: Params, + x: []u16, + dir: []f32, + + /// A call's rows and a direction as wide as they are. + pub fn init(a: std.mem.Allocator, p: Params) !Steer { + if (p.hidden == 0 or p.rows == 0) return error.BadDirectionWidth; + const x = try a.alloc(u16, p.rows * p.hidden); + errdefer a.free(x); + return .{ .a = a, .p = p, .x = x, .dir = try a.alloc(f32, p.hidden) }; + } + + /// A call whose direction is the caller's width: a width that does not match the rows is refused. + pub fn withDirection(a: std.mem.Allocator, p: Params, dir: []const f32) !Steer { + if (p.hidden == 0 or p.rows == 0) return error.BadDirectionWidth; + const x = try a.alloc(u16, p.rows * p.hidden); + errdefer a.free(x); + return .{ .a = a, .p = p, .x = x, .dir = try a.dupe(f32, dir) }; + } + + pub fn deinit(s: Steer) void { + s.a.free(s.x); + s.a.free(s.dir); + } + + /// The outputs a call writes: the rows the hidden width. + pub fn outputs(p: Params) usize { + return p.rows * p.hidden; + } + + /// The inputs a gate asks for: ordinary rows with a direction, or rows that hold NaN and infinities. + pub fn fill(s: *Steer, mode: rows.Fill, seed: u64) void { + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (s.dir) |*d| d.* = rng.float(f32) * 2 - 1; + for (s.x) |*v| v.* = c.toBf16(rng.float(f32) * 4 - 2); + switch (mode) { + .random, .stress => {}, + .nonfinite => s.plant(), + } + } + + /// A NaN and both infinities, where float64 and the kernel must agree on the class. + fn plant(s: *Steer) void { + const k = s.p.hidden; + if (k < 4) return; + const nan = c.toBf16(std.math.nan(f32)); + const inf = c.toBf16(std.math.inf(f32)); + const ninf = c.toBf16(-std.math.inf(f32)); + const at = [_][2]usize{ .{ 0, k / 3 }, .{ 1, k / 2 }, .{ 2, k - 1 }, .{ 3, 0 }, .{ 3, k - 1 } }; + const put = [_]u16{ nan, inf, ninf, inf, ninf }; + for (at, put) |p, v| if (p[0] < s.p.rows) { + s.x[p[0] * k + p[1]] = v; + }; + } + + /// Rows whose bf16 sum shows the add's order: x cancels alpha * d's bf16 part, leaving a tie its rounding breaks. + pub fn fillOrdered(s: *Steer, seed: u64) !void { + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const k = s.p.hidden; + for (0..k) |i| { + const d, const x = for (0..1 << 20) |_| { + const dir = rng.float(f32) * 2 - 1; + const step = s.p.alpha * dir; + if (step == 0) continue; + const row: u16 = @truncate(@as(u32, @bitCast(-step)) >> 16); + const v = c.fromBf16(row); + if (bits(v, s.p.alpha, dir) != fused(v, s.p.alpha, dir)) break .{ dir, row }; + } else return error.OrderInvisible; + s.dir[i] = d; + for (0..s.p.rows) |r| s.x[r * k + i] = x; + } + } + + /// The float64 outputs and, per output, the magnitude a sum's error would carry into it: there are no sums. + pub fn reference(s: Steer, want: []f64, mag: []f64) !void { + if (s.dir.len != s.p.hidden) return error.BadDirectionWidth; + const k = s.p.hidden; + for (0..s.p.rows) |r| { + for (0..k) |i| { + const x = c.fromBf16(s.x[r * k + i]); + const g: f64 = s.dir[i]; + want[r * k + i] = x + @as(f64, s.p.alpha) * g; + mag[r * k + i] = 0; + } + } + } + + /// The kernel's own arithmetic: the product and the sum in fp32, then the stream's bf16 rounding. + pub fn kernelOut(s: Steer, out: []f64) void { + const k = s.p.hidden; + for (0..s.p.rows) |r| { + for (0..k) |i| { + const x = c.fromBf16(s.x[r * k + i]); + const step: f32 = s.p.alpha * s.dir[i]; + const v: f32 = if (step == 0) x else x + step; + out[r * k + i] = bf16.round32(v); + } + } + } + + /// The allowance per output: the product's and the sum's fp32 roundings, then the output's own rounding. + pub fn bounds(s: Steer, want: []const f64, allow: []f64) void { + const u = 0x1p-24; + const k = s.p.hidden; + const scale = @abs(@as(f64, s.p.alpha)); + for (0..s.p.rows) |r| { + for (0..k) |i| { + const w = want[r * k + i]; + if (!std.math.isFinite(w)) { + allow[r * k + i] = 0; // the nonfinite gate compares classes, not distances + continue; + } + const prod = scale * @abs(@as(f64, s.dir[i])); + const work = u * (prod + @abs(w)); + allow[r * k + i] = work + 0x1p-8 * (@abs(w) + work) + 0x1p-133; + } + } + } +}; + +/// The kernel's sum as bf16 bits: the product rounded to fp32, then the sum, then the stream's rounding. +pub fn bits(x: f32, alpha: f32, d: f32) u16 { + const step: f32 = alpha * d; + return c.toBf16(if (step == 0) x else x + step); +} + +/// The same sum contracted into one fused multiply-add: the form the reference ordering must tell apart. +pub fn fused(x: f32, alpha: f32, d: f32) u16 { + return c.toBf16(@mulAdd(f32, alpha, d, x)); +} + +/// The kernel has no sums to round. +pub fn depthNone(_: c.Shape) usize { + return 0; +} + +/// The kernel's registration: the served shapes and the bound of its one product and one sum. +pub fn spec() c.Spec { + return .{ + .name = "qwen27 steer", + .accum = .none, + .depth = depthNone, + .ops = 2, + .out = .bf16, + .in_place = false, + .tiles = .{ + .{ .size = 8, .step = 8, .min = 8 }, + .{ .size = hidden, .step = hidden, .min = hidden }, + .{ .size = hidden, .step = hidden, .min = hidden }, + }, + .served = &.{ + .{ .rows = 1, .n = hidden, .k = hidden }, + .{ .rows = 8, .n = hidden, .k = hidden }, + .{ .rows = 64, .n = hidden, .k = hidden }, + }, + .sums = .{ + .why = "Each output is one product and one sum of two values, with no iterative accumulation.", + }, + }; +} + +test "the kernel's own arithmetic lands inside the bound the spec declares" { + const a = std.testing.allocator; + var s = try Steer.init(a, .{ .alpha = 0.75, .rows = 8 }); + defer s.deinit(); + s.fill(.random, 11); + const n = Steer.outputs(s.p); + const want = try a.alloc(f64, n); + defer a.free(want); + const mag = try a.alloc(f64, n); + defer a.free(mag); + const got = try a.alloc(f64, n); + defer a.free(got); + const allow = try a.alloc(f64, n); + defer a.free(allow); + try s.reference(want, mag); + s.kernelOut(got); + s.bounds(want, allow); + for (got, want, allow) |g, w, l| try std.testing.expect(@abs(g - w) <= l); +} + +test "the reference adds the strength times the direction, whatever the direction's length" { + const a = std.testing.allocator; + var s = try Steer.withDirection(a, .{ .alpha = 2, .rows = 1, .hidden = 2 }, &.{ 3, 4 }); + defer s.deinit(); + s.x[0] = c.toBf16(1); + s.x[1] = c.toBf16(0); + var want: [2]f64 = undefined; + var mag: [2]f64 = undefined; + try s.reference(&want, &mag); + try std.testing.expectEqual(@as(f64, 7), want[0]); // 1 + 2 * 3 + try std.testing.expectEqual(@as(f64, 8), want[1]); // 0 + 2 * 4 +} + +test "a NaN in a row stays in its own element, as float64 does" { + const a = std.testing.allocator; + var s = try Steer.init(a, .{ .alpha = 1, .rows = 5, .hidden = 64 }); + defer s.deinit(); + s.fill(.nonfinite, 3); + const n = Steer.outputs(s.p); + const want = try a.alloc(f64, n); + defer a.free(want); + const mag = try a.alloc(f64, n); + defer a.free(mag); + const got = try a.alloc(f64, n); + defer a.free(got); + try s.reference(want, mag); + s.kernelOut(got); + try std.testing.expect(std.math.isNan(want[21])); + try std.testing.expect(std.math.isFinite(want[0])); + for (got, want) |g, w| try std.testing.expectEqual(c.classOf(w), c.classOf(g)); +} + +test "a zero-length or mismatched direction is refused" { + const a = std.testing.allocator; + try std.testing.expectError(error.BadDirectionWidth, Steer.init(a, .{ .rows = 1, .hidden = 0 })); + var s = try Steer.withDirection(a, .{ .rows = 1, .hidden = 4 }, &.{ 1, 2, 3 }); + defer s.deinit(); + var want: [4]f64 = undefined; + var mag: [4]f64 = undefined; + try std.testing.expectError(error.BadDirectionWidth, s.reference(&want, &mag)); +} + +test "ordered rows tell the separately rounded add from a fused multiply-add in every element" { + const a = std.testing.allocator; + for ([_]f32{ 0.1, 0.3 }) |alpha| { + var s = try Steer.init(a, .{ .alpha = alpha, .rows = 3, .hidden = 512 }); + defer s.deinit(); + try s.fillOrdered(7); + const got = try a.alloc(f64, Steer.outputs(s.p)); + defer a.free(got); + s.kernelOut(got); + for (got, 0..) |v, j| { + const x = c.fromBf16(s.x[j]); + const d = s.dir[j % 512]; + try std.testing.expectEqual(bits(x, alpha, d), c.toBf16(@floatCast(v))); + try std.testing.expect(fused(x, alpha, d) != bits(x, alpha, d)); + } + } + // A power-of-two strength makes every product exact: no row can tell the two orders apart. + var s = try Steer.init(a, .{ .alpha = 1, .rows = 1, .hidden = 4 }); + defer s.deinit(); + try std.testing.expectError(error.OrderInvisible, s.fillOrdered(7)); +} + +test "zero scaled step preserves negative-zero residual" { + const neg_zero: u16 = 0x8000; + try std.testing.expectEqual(neg_zero, bits(c.fromBf16(neg_zero), 1.0, 0.0)); + try std.testing.expectEqual(neg_zero, bits(c.fromBf16(neg_zero), 1e-25, 1e-25)); +} diff --git a/zig/src/core/contract/steer_records.zig b/zig/src/core/contract/steer_records.zig new file mode 100644 index 00000000000..d954e51598c --- /dev/null +++ b/zig/src/core/contract/steer_records.zig @@ -0,0 +1,21 @@ +//! The steering launch's threads and threadgroup memory, for gate 5's limits. +const std = @import("std"); +const limits = @import("limits.zig"); +const steer = @import("steer.zig"); + +/// The launch as the engine makes it: a threadgroup a row, the fused norm's threads, its one set of partials. +pub const metal = [_]limits.MetalLaunch{ + .{ + .name = "qwen27 norm steer custom_kernel_q27_norm_steer_bfloat16_t_bfloat16_t_bfloat16_t_floatc_int32_t_bfloat16_t_bfloat16_t_float_float_float", + .threads = steer.threads, + .tg_memory = steer.group_memory, + .reserved = steer.threads, + }, +}; + +test "the steering launch fits every Apple family" { + const a = std.testing.allocator; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(a); + for (metal) |l| for (limits.apple) |f| try std.testing.expectEqual(@as(usize, 0), try limits.metal(l, f, &out, a)); +} diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index c2403172389..15b7eef03cc 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -5,6 +5,7 @@ const Allocator = std.mem.Allocator; pub const profile = @import("profile"); pub const tfvideo = @import("tfvideo.zig"); pub const DraftSources = @import("draft_sources.zig").Sources; +pub const glp = @import("glp.zig"); /// The server's name for one request, unique while the process lives. pub const Id = u64; /// One request's sampling (Python's exact_sampling.Sampling); a request without one decodes greedily. @@ -90,10 +91,7 @@ pub const Event = union(enum) { }; /// Where a request's events go. Called on the engine's thread: it must return at once and not re-enter the engine. -pub const Sink = struct { - ctx: *anyopaque, - event: *const fn (ctx: *anyopaque, id: Id, event: *const Event) void, -}; +pub const Sink = struct { ctx: *anyopaque, event: *const fn (ctx: *anyopaque, id: Id, event: *const Event) void }; pub const Benchmark = @import("benchmark_info.zig").Snapshot; /// A reranker's label tokens: a prompt's relevance score is sigmoid(yes - no) of their last-row logits. @@ -279,6 +277,8 @@ pub const Open = struct { rope_yarn: ?f64 = null, // --rope-yarn: YaRN over the checkpoint's trained window; families without it refuse /// --record: each stream's committed rows and tapped features written under this folder, for drafter training. record: ?[]const u8 = null, + /// --glp: the control vector the engine applies to the residual stream (null: none). + glp: ?glp.Glp = null, speed_up: ?[]const u8 = null, prompt_cache_gib: ?f64 = null, prompt_cache_over_cap: bool = false, diff --git a/zig/src/core/glp.zig b/zig/src/core/glp.zig new file mode 100644 index 00000000000..b1a88864e6f --- /dev/null +++ b/zig/src/core/glp.zig @@ -0,0 +1,485 @@ +//! A GLP control vector, read and written; implements the GLP format defined by the `weightless` project (@msuiche). + +const std = @import("std"); +const gguf = @import("glp_container.zig"); + +/// Why a file was refused, in one sentence the server prints. +pub const Why = struct { + buf: [320]u8 = undefined, + len: usize = 0, + + pub fn set(self: *Why, comptime fmt: []const u8, args: anytype) void { + var w: std.Io.Writer = .fixed(&self.buf); + w.print(fmt, args) catch {}; + self.len = w.end; + } + + pub fn text(self: *const Why) []const u8 { + return self.buf[0..self.len]; + } +}; + +pub const Error = error{BadGlpVector} || std.mem.Allocator.Error; + +/// The mode word a file may carry and this reader applies: h += alpha*d, llama.cpp's control vector, a bias. +const add_mode = "add"; + +/// One layer's direction: its zero-based layer id and the vector itself. +pub const Layer = struct { + id: u32, + dir: []const f32, +}; + +/// What the file says about itself: the keys a consumer reads before it reads the directions. +pub const Publication = struct { + /// What the file calls itself: general.name. + name: ?[]const u8 = null, + /// What the file says it is: general.description. + description: ?[]const u8 = null, + /// Who derived it: general.author. + author: ?[]const u8 = null, + /// The licence the file is under: general.license. + license: ?[]const u8 = null, + /// The model family a consumer matches against: controlvector.model_hint. + model_hint: ?[]const u8 = null, + /// What the strength does, as it was measured: glp.measured_effect. + measured_effect: ?[]const u8 = null, + /// The day the file was made: glp.created. + created: ?[]const u8 = null, +}; + +/// A vector read whole and accepted. +pub const Vector = struct { + alpha: f32, + hook_point: []const u8, + derived_at: []const u8, + base_model: []const u8, + base_revision: []const u8, + method: []const u8, + contrast: []const u8, + width: usize, + layers: []const Layer, + sha256: [32]u8, + /// Whether the file's own content digest key was parsed and checked against its tensors. + claims_digest: bool, + /// The SHA-256 of the file's exact bytes, as the reader was handed them. + file_sha256: [32]u8, + transferred: bool, + publication: Publication = .{}, +}; + +/// The control vector a serve applies to the residual stream (--glp). +pub const Glp = struct { + /// The file's vector: one direction per layer and the checkpoint it was derived from. + vector: Vector, + /// The strength in force: --glp-alpha, or the file's own alpha_default. + alpha: f32, +}; + +/// The residual site this reader applies at, the one llama.cpp's control vectors name. +pub const residual_site = "residual_stream_post_layer"; + +fn refuse(why: *Why, comptime fmt: []const u8, args: anytype) Error { + why.set(fmt, args); + return error.BadGlpVector; +} + +/// The direction's layer id, or null when the tensor is not one. +fn directionId(name: []const u8) ?u32 { + if (!std.mem.startsWith(u8, name, "direction.")) return null; + const tail = name["direction.".len..]; + if (tail.len == 0) return null; + for (tail) |ch| if (ch < '0' or ch > '9') return null; + return std.fmt.parseInt(u32, tail, 10) catch null; +} + +/// The digest over the tensor bytes; the file's own key names the vectors it covers. +fn digest(file: gguf.File, only_directions: bool) ?[32]u8 { + var h: std.crypto.hash.sha2.Sha256 = .init(.{}); + for (file.tensors) |t| { + if (only_directions and directionId(t.name) == null) continue; + const raw = file.bytesOf(t) orelse return null; + h.update(raw); + } + var out: [32]u8 = undefined; + h.final(&out); + return out; +} + +/// Read a vector whole and accept it, or refuse it with a reason; the strings and layers live in `a`. +pub fn read(a: std.mem.Allocator, bytes: []const u8, why: *Why) Error!Vector { + if (bytes.len < 8) return refuse(why, "the file is too short to be a control vector", .{}); + const file = try parseContainer(a, bytes, why); + + var glp_keys: usize = 0; + for (file.entries) |e| { + // The keys whose meaning the spec version decides; alpha and the digest mean the same in every version. + const interpretation = std.mem.eql(u8, e.key, "glp.mode") or std.mem.eql(u8, e.key, "glp.rank") or + std.mem.eql(u8, e.key, "glp.orthonormal") or std.mem.eql(u8, e.key, "glp.hook_point") or + std.mem.eql(u8, e.key, "glp.derived_at") or std.mem.eql(u8, e.key, "glp.dir_scales") or + std.mem.eql(u8, e.key, "glp.layer_scales"); + if (interpretation) glp_keys += 1; + } + + // Only an add vector is applied: a mode the file names, in either key, has to be the word add. + for ([_][]const u8{ "glp.mode", "dspark.mode" }) |key| { + if (file.find(key) == null) continue; + const mode = file.str(key) orelse return refuse(why, "the file's {s} is not text; this reader applies add vectors only", .{key}); + if (std.mem.eql(u8, mode, "project")) return refuse(why, "the file's mode is project; this reader applies add vectors only", .{}); + if (!std.mem.eql(u8, mode, add_mode)) return refuse(why, "the file's mode is not one this reader applies; it applies add vectors only", .{}); + } + + // Absent is the only pass to the unversioned path: a present value that is not an integer is refused below. + if (file.find("glp.spec_version") != null) { + const version = file.num("glp.spec_version") orelse return refuse(why, "glp.spec_version is not an unsigned integer", .{}); + if (version != 1) return refuse(why, "glp.spec_version {d}; this reader implements version 1", .{version}); + } else if (glp_keys > 0) { + return refuse(why, "the file carries glp keys but no glp.spec_version", .{}); + } + for ([_][]const u8{ "glp.dir_scales", "glp.layer_scales" }) |k| { + if (file.find(k) != null) return refuse(why, "the file carries {s}: per-direction and per-layer scales are not implemented", .{k}); + } + + if (glp_keys > 0) { + const rank = file.num("glp.rank") orelse value: { + if (file.find("glp.rank") != null) return refuse(why, "glp.rank is not an integer", .{}); + break :value 1; + }; + if (rank != 1) return refuse(why, "glp.rank {d}; this reader implements rank 1", .{rank}); + const site = try strictText(file, "glp.hook_point", why) orelse return refuse(why, "the file names no glp.hook_point", .{}); + if (!std.mem.eql(u8, site, residual_site)) return refuse(why, "the file's hook point is {s}; this reader applies at {s}", .{ site, residual_site }); + } + + var layers: std.ArrayList(Layer) = .empty; + var width: usize = 0; + for (file.tensors) |t| { + const id = directionId(t.name) orelse continue; + if (id == 0) return refuse(why, "the file holds direction.0; layer 0 is not steerable", .{}); + if (t.kind != gguf.f32_type) return refuse(why, "{s} is not fp32", .{t.name}); + if (t.dims.len != 1) return refuse(why, "{s} is not one dimensional", .{t.name}); + if (width == 0) width = @intCast(t.dims[0]) else if (width != t.dims[0]) return refuse(why, "{s} is {d} wide; the other directions are {d}", .{ t.name, t.dims[0], width }); + const raw = file.bytesOf(t) orelse return refuse(why, "{s} points past the file", .{t.name}); + const dir = try a.alloc(f32, t.dims[0]); + for (dir, 0..) |*v, i| v.* = @bitCast(std.mem.readInt(u32, raw[i * 4 ..][0..4], .little)); + try layers.append(a, .{ .id = id, .dir = dir }); + } + if (layers.items.len == 0) return refuse(why, "the file holds no direction tensors", .{}); + std.mem.sort(Layer, layers.items, {}, struct { + fn lessThan(_: void, x: Layer, y: Layer) bool { + return x.id < y.id; + } + }.lessThan); + // "direction.5" and "direction.05" both parse as layer 5; refuse a file that names one layer twice. + for (layers.items[1..], 1..) |l, i| { + if (l.id == layers.items[i - 1].id) return refuse(why, "the file holds two directions for layer {d}", .{l.id}); + } + + if (try strictText(file, "glp.layer_ids_zero_based", why)) |list| { + var it = std.mem.splitScalar(u8, list, ','); + var i: usize = 0; + while (it.next()) |part| { + if (i >= layers.items.len) return refuse(why, "the file names more layers than it holds", .{}); + const id = std.fmt.parseInt(u32, std.mem.trim(u8, part, " "), 10) catch return refuse(why, "the file's layer id list is not a number list", .{}); + if (id != layers.items[i].id) return refuse(why, "the file's layer id {d} does not match its tensor's {d}", .{ id, layers.items[i].id }); + i += 1; + } + if (i != layers.items.len) return refuse(why, "the file names {d} layers and holds {d}", .{ i, layers.items.len }); + } + + // A direction is applied as it stands, so a NaN or an infinity is refused. + for (layers.items) |l| { + for (l.dir) |v| if (!std.math.isFinite(v)) return refuse(why, "layer {d}'s direction holds a value that is not finite", .{l.id}); + } + + // The digest a file reports as verified is the one its parsed key holds, never a string that merely reads like it. + var sha: [32]u8 = undefined; + var claims_digest = false; + if (file.str("glp.content_sha256")) |claimed| { + const all = digest(file, false) orelse return refuse(why, "the file's tensors point past its end", .{}); + const dirs = digest(file, true) orelse return refuse(why, "the file's tensors point past its end", .{}); + // The file may claim the digest over every tensor or over the directions alone; the match decides. + const hex_all = std.fmt.bytesToHex(all, .lower); + const hex_dirs = std.fmt.bytesToHex(dirs, .lower); + if (std.mem.eql(u8, hex_all[0..], claimed)) { + sha = all; + } else if (std.mem.eql(u8, hex_dirs[0..], claimed)) { + sha = dirs; + } else { + return refuse(why, "the file's content digest does not match its vectors", .{}); + } + claims_digest = true; + } else { + if (file.find("glp.content_sha256") != null) return refuse(why, "glp.content_sha256 is not text", .{}); + sha = digest(file, true) orelse std.mem.zeroes([32]u8); + } + + const hook = try strictText(file, "glp.hook_point", why) orelse residual_site; + const derived = try strictText(file, "glp.derived_at", why) orelse hook; + const base_model_key = try strictText(file, "glp.base_model", why); + const base_repo_url = try strictText(file, "general.base_model.0.repo_url", why); + const base_revision = try strictText(file, "glp.base_revision", why); + + var file_sha256: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &file_sha256, .{}); + + return .{ + .file_sha256 = file_sha256, + .alpha = if (file.find("glp.alpha_default")) |v| switch (v) { + .f32v => |x| x, + .f64v => |x| @floatCast(x), + else => return refuse(why, "glp.alpha_default is not a floating-point strength", .{}), + } else 1.0, + .hook_point = hook, + .derived_at = derived, + .base_model = base_model_key orelse base_repo_url orelse "", + .base_revision = base_revision orelse "", + .method = file.str("glp.method") orelse "", + .contrast = file.str("glp.contrast") orelse "", + .width = width, + .layers = layers.items, + .sha256 = sha, + .claims_digest = claims_digest, + .transferred = !std.mem.eql(u8, derived, hook), + .publication = .{ + .name = file.str("general.name"), + .description = file.str("general.description"), + .author = file.str("general.author"), + .license = file.str("general.license"), + .model_hint = file.str("controlvector.model_hint"), + .measured_effect = file.str("glp.measured_effect"), + .created = file.str("glp.created"), + }, + }; +} + +/// Check the vector against the model it would steer: its width and the checkpoint it came from. +pub fn checkModel(v: Vector, hidden: usize, base_model: []const u8, why: *Why) Error!void { + if (v.width != hidden) return refuse(why, "the vector's directions are {d} wide; the model is {d}", .{ v.width, hidden }); + if (base_model.len > 0 and v.base_model.len > 0 and !sameModel(v.base_model, base_model)) { + return refuse(why, "the vector is for {s}; the model is {s}", .{ v.base_model, base_model }); + } +} + +/// The text a key holds, null when the key is absent; a present non-string value is refused, not skipped. +fn strictText(file: gguf.File, key: []const u8, why: *Why) Error!?[]const u8 { + const v = file.find(key) orelse return null; + return switch (v) { + .string => |s| s, + else => return refuse(why, "{s} is not text", .{key}), + }; +} + +/// The hub's URL prefix: a base model named by URL names the repo that follows it. +pub const hub_prefix = "https://huggingface.co/"; + +/// A repo id, whether the file names the model as an id or as the hub's URL for it. +pub fn repoId(name: []const u8) []const u8 { + return if (std.mem.startsWith(u8, name, hub_prefix)) name[hub_prefix.len..] else name; +} + +const short_commit = 7; + +fn revisionMatches(a: []const u8, b: []const u8) bool { + if (std.ascii.eqlIgnoreCase(a, b)) return true; + if (@min(a.len, b.len) < short_commit) return false; + return std.ascii.startsWithIgnoreCase(a, b) or std.ascii.startsWithIgnoreCase(b, a); +} + +/// Reject a snapshot revision mismatch when both vector and served model name the same cached repository. +pub fn checkRevision(v: Vector, base_model: []const u8, revision: []const u8, why: *Why) Error!void { + if (base_model.len == 0 or v.base_model.len == 0 or v.base_revision.len == 0 or revision.len == 0) return; + if (!std.ascii.eqlIgnoreCase(repoId(v.base_model), repoId(base_model))) return; + if (!revisionMatches(v.base_revision, revision)) { + return refuse(why, "the vector is for revision {f}; the model is revision {f}", .{ std.zig.fmtString(v.base_revision), std.zig.fmtString(revision) }); + } +} + +/// The served checkpoint is the vector's model when it is that model or a conversion of it. +fn sameModel(base: []const u8, served: []const u8) bool { + if (std.mem.eql(u8, base, served)) return true; + return std.mem.startsWith(u8, nameOf(served), nameOf(base)); +} + +/// A repo id's model name: what follows its owner. +fn nameOf(repo: []const u8) []const u8 { + if (std.mem.lastIndexOfScalar(u8, repo, '/')) |i| return repo[i + 1 ..]; + return repo; +} + +/// The container's metadata and tensor headers; the arena keeps every allocation. +fn parseContainer(a: std.mem.Allocator, bytes: []const u8, why: *Why) Error!gguf.File { + var problem: gguf.Problem = .{}; + const file = gguf.parse(a, bytes, &problem) catch |err| { + if (err == error.OutOfMemory) return error.OutOfMemory; + // A cursor that runs out of bytes names no rule: say so rather than print an empty reason. + if (problem.text().len == 0) problem.set("the file ends before its metadata is complete", .{}); + return refuse(why, "{s}", .{problem.text()}); + }; + return file; +} + +/// The checkpoint a vector names, escaped, with its revision when it names one; never raw log text. +pub fn baseLine(v: Vector, buf: []u8) []const u8 { + var w: std.Io.Writer = .fixed(buf); + if (v.base_model.len == 0) { + w.writeAll("an unnamed checkpoint") catch {}; + } else { + w.print("{f}", .{std.zig.fmtString(v.base_model)}) catch {}; + if (v.base_revision.len > 0) w.print(" @ {f}", .{std.zig.fmtString(v.base_revision)}) catch {}; + } + return buf[0..w.end]; +} + +/// What a producer writes: the vector's fields and one direction per layer. +pub const WriteSpec = struct { + alpha: f32 = 1.0, + hook_point: []const u8 = residual_site, + derived_at: ?[]const u8 = null, + base_model: []const u8 = "", + base_revision: []const u8 = "", + method: []const u8 = "", + contrast: []const u8 = "", + /// What the file says about itself; the keys a consumer reads before it reads the directions. + publication: Publication = .{}, + layers: []const Layer, +}; + +/// Write a vector file the way the spec names it; the returned bytes are owned by the caller. +pub fn write(a: std.mem.Allocator, spec: WriteSpec) Error![]u8 { + if (spec.layers.len == 0) return error.BadGlpVector; + if (!std.mem.eql(u8, spec.hook_point, residual_site)) return error.BadGlpVector; + + var arena = std.heap.ArenaAllocator.init(a); + defer arena.deinit(); + const tmp = arena.allocator(); + + // The file lists its layers in ascending order, whatever order the caller hands them over in. + const sorted = try tmp.alloc(Layer, spec.layers.len); + @memcpy(sorted, spec.layers); + std.mem.sort(Layer, sorted, {}, struct { + fn lessThan(_: void, x: Layer, y: Layer) bool { + return x.id < y.id; + } + }.lessThan); + + const width = sorted[0].dir.len; + for (sorted, 0..) |l, i| { + if (i > 0 and l.id == sorted[i - 1].id) return error.BadGlpVector; + if (l.id == 0 or l.dir.len == 0 or l.dir.len != width) return error.BadGlpVector; + for (l.dir) |v| if (!std.math.isFinite(v)) return error.BadGlpVector; + } + + var payload: std.ArrayList(u8) = .empty; + defer payload.deinit(tmp); + for (sorted) |l| { + for (l.dir) |v| { + var buf: [4]u8 = undefined; + std.mem.writeInt(u32, &buf, @bitCast(v), .little); + try payload.appendSlice(tmp, &buf); + } + } + + // The digest covers the concatenated tensor bytes, which is what the reader hashes to check the file. + var h: std.crypto.hash.sha2.Sha256 = .init(.{}); + h.update(payload.items); + var sha: [32]u8 = undefined; + h.final(&sha); + const hex = std.fmt.bytesToHex(sha, .lower); + + var ids: std.ArrayList(u8) = .empty; + defer ids.deinit(tmp); + for (sorted, 0..) |l, i| { + if (i > 0) try ids.append(tmp, ','); + try ids.print(tmp, "{d}", .{l.id}); + } + + const dims = try tmp.alloc(u64, 1); + dims[0] = width; + const names = try tmp.alloc([32]u8, sorted.len); + const tensors = try tmp.alloc(gguf.OutTensor, sorted.len); + var start: usize = 0; + for (sorted, tensors, 0..) |l, *t, i| { + const name = std.fmt.bufPrint(names[i][0..], "direction.{d}", .{l.id}) catch return error.BadGlpVector; + t.* = .{ .name = name, .dims = dims, .kind = gguf.f32_type, .data = payload.items[start..][0 .. l.dir.len * 4] }; + start += l.dir.len * 4; + } + + const entries = [_]gguf.Entry{ + .{ .key = "general.architecture", .value = .{ .string = "controlvector" } }, + .{ .key = "general.alignment", .value = .{ .u32v = 32 } }, + .{ .key = "controlvector.layer_count", .value = .{ .u32v = @intCast(sorted.len) } }, + .{ .key = "glp.spec_version", .value = .{ .u32v = 1 } }, + .{ .key = "glp.mode", .value = .{ .string = add_mode } }, + .{ .key = "glp.rank", .value = .{ .u32v = 1 } }, + .{ .key = "glp.alpha_default", .value = .{ .f32v = spec.alpha } }, + .{ .key = "glp.hook_point", .value = .{ .string = spec.hook_point } }, + .{ .key = "glp.derived_at", .value = .{ .string = spec.derived_at orelse spec.hook_point } }, + .{ .key = "glp.base_model", .value = .{ .string = spec.base_model } }, + .{ .key = "glp.base_revision", .value = .{ .string = spec.base_revision } }, + .{ .key = "glp.method", .value = .{ .string = spec.method } }, + .{ .key = "glp.contrast", .value = .{ .string = spec.contrast } }, + .{ .key = "glp.layer_ids_zero_based", .value = .{ .string = ids.items } }, + .{ .key = "glp.content_sha256", .value = .{ .string = hex[0..] } }, + }; + var written = std.ArrayList(gguf.Entry).empty; + defer written.deinit(tmp); + try written.appendSlice(tmp, &entries); + // The model the vector came from, in the shape a consumer reads: the repo it was derived from. + if (spec.base_model.len > 0) { + const is_url = std.mem.startsWith(u8, spec.base_model, "http"); + const owner = std.mem.lastIndexOfScalar(u8, spec.base_model, '/'); + const url = if (is_url) + spec.base_model + else + try std.fmt.allocPrint(tmp, "https://huggingface.co/{s}", .{spec.base_model}); + try written.append(tmp, .{ .key = "general.base_model.count", .value = .{ .u32v = 1 } }); + if (!is_url) { + const org = if (owner) |i| spec.base_model[0..i] else ""; + const repo_name = if (owner) |i| spec.base_model[i + 1 ..] else spec.base_model; + try written.append(tmp, .{ .key = "general.base_model.0.name", .value = .{ .string = repo_name } }); + try written.append(tmp, .{ .key = "general.base_model.0.organization", .value = .{ .string = org } }); + } + try written.append(tmp, .{ .key = "general.base_model.0.version", .value = .{ .string = spec.base_revision } }); + try written.append(tmp, .{ .key = "general.base_model.0.repo_url", .value = .{ .string = url } }); + } + // What the file says about itself, when the producer named it. + const about = spec.publication; + try appendText(&written, tmp, "general.name", about.name); + try appendText(&written, tmp, "general.description", about.description); + try appendText(&written, tmp, "general.author", about.author); + try appendText(&written, tmp, "general.license", about.license); + try appendText(&written, tmp, "controlvector.model_hint", about.model_hint); + try appendText(&written, tmp, "glp.measured_effect", about.measured_effect); + try appendText(&written, tmp, "glp.created", about.created); + return gguf.write(a, written.items, tensors) catch |err| switch (err) { + error.BadGguf => error.BadGlpVector, + error.OutOfMemory => error.OutOfMemory, + }; +} + +/// One more metadata key, when the producer named one. +fn appendText(written: *std.ArrayList(gguf.Entry), tmp: std.mem.Allocator, key: []const u8, text: ?[]const u8) !void { + const value = text orelse return; + try written.append(tmp, .{ .key = key, .value = .{ .string = value } }); +} + +/// Write a vector read earlier back out, so a file can be rewritten with the same fields. +pub fn writeVector(a: std.mem.Allocator, v: Vector) Error![]u8 { + return write(a, .{ + .alpha = v.alpha, + .hook_point = v.hook_point, + .derived_at = v.derived_at, + .base_model = v.base_model, + .base_revision = v.base_revision, + .method = v.method, + .contrast = v.contrast, + .publication = v.publication, + .layers = v.layers, + }); +} + +test { + _ = @import("glp_container_test.zig"); + _ = @import("glp_test.zig"); + _ = @import("glp_publication_test.zig"); +} diff --git a/zig/src/core/glp_container.zig b/zig/src/core/glp_container.zig new file mode 100644 index 00000000000..08a47ee0242 --- /dev/null +++ b/zig/src/core/glp_container.zig @@ -0,0 +1,409 @@ +//! The GGUF v3 subset a GLP file uses; implements the GLP format defined by the `weightless` project (@msuiche). + +const std = @import("std"); + +pub const Error = error{BadGguf} || std.mem.Allocator.Error; + +/// The alignment a container pads its tensor data to when its metadata names none. +pub const default_alignment = 32; + +/// The deepest an array inside an array may nest; a real file names none. +const max_array_depth = 4; + +/// The ggml type a tensor of floats carries. +pub const f32_type = 0; + +/// The gguf value types the container may hold. +pub const Type = enum(u32) { + u8v = 0, + i8v = 1, + u16v = 2, + i16v = 3, + u32v = 4, + i32v = 5, + f32v = 6, + boolv = 7, + string = 8, + array = 9, + u64v = 10, + i64v = 11, + f64v = 12, +}; + +/// An array's element type and its items, so an empty array still names the type it holds. +pub const Array = struct { + elem: Type, + items: []const Value, +}; + +/// A metadata value; strings and arrays borrow from the file's bytes or the arena. +pub const Value = union(Type) { + u8v: u8, + i8v: i8, + u16v: u16, + i16v: i16, + u32v: u32, + i32v: i32, + f32v: f32, + boolv: bool, + string: []const u8, + array: Array, + u64v: u64, + i64v: i64, + f64v: f64, +}; + +/// One metadata key and the value it holds. +pub const Entry = struct { key: []const u8, value: Value }; + +/// One tensor's header: its name, its shape, its ggml type and its offset in the data section. +pub const Tensor = struct { + name: []const u8, + dims: []const u64, + kind: u32, + offset: u64, +}; + +/// A tensor the writer emits: its name, its shape, its ggml type and its raw bytes. +pub const OutTensor = struct { + name: []const u8, + dims: []const u64, + kind: u32, + data: []const u8, +}; + +/// Why a container was refused, in one sentence. +pub const Problem = struct { + buf: [200]u8 = undefined, + len: usize = 0, + + pub fn set(self: *Problem, comptime fmt: []const u8, args: anytype) void { + var w: std.Io.Writer = .fixed(&self.buf); + w.print(fmt, args) catch {}; + self.len = w.end; + } + + pub fn text(self: *const Problem) []const u8 { + return self.buf[0..self.len]; + } +}; + +/// A parsed container: its metadata, its tensor headers and the file's bytes. +pub const File = struct { + entries: []Entry, + tensors: []Tensor, + data_start: usize, + alignment: usize, + bytes: []const u8, + + /// The value a key holds, or null when the key is absent or holds another type. + pub fn find(self: File, key: []const u8) ?Value { + for (self.entries) |e| if (std.mem.eql(u8, e.key, key)) return e.value; + return null; + } + + /// The string a key holds, or null when the key is absent or holds another type. + pub fn str(self: File, key: []const u8) ?[]const u8 { + const v = self.find(key) orelse return null; + return switch (v) { + .string => |s| s, + else => null, + }; + } + + /// The integer a key holds, or null; a negative value reads as nothing rather than as its wrap. + pub fn num(self: File, key: []const u8) ?u64 { + const v = self.find(key) orelse return null; + return switch (v) { + .u8v => |x| x, + .u16v => |x| x, + .u32v => |x| x, + .u64v => |x| x, + .i8v => |x| if (x < 0) null else @intCast(x), + .i16v => |x| if (x < 0) null else @intCast(x), + .i32v => |x| if (x < 0) null else @intCast(x), + .i64v => |x| if (x < 0) null else @intCast(x), + else => null, + }; + } + + /// The tensor header a name names, or null. + pub fn tensor(self: File, name: []const u8) ?Tensor { + for (self.tensors) |t| if (std.mem.eql(u8, t.name, name)) return t; + return null; + } + + /// The tensor's bytes, by its offset in the data section; null when its type's size or its place is unknown. + pub fn bytesOf(self: File, t: Tensor) ?[]const u8 { + const count = elemCount(t.dims) orelse return null; + const width = elemSize(t.kind) orelse return null; + const size = std.math.mul(usize, count, width) catch return null; + const offset = std.math.cast(usize, t.offset) orelse return null; + const start = std.math.add(usize, self.data_start, offset) catch return null; + // Subtract rather than add: a start past the end must be refused, not wrap into the file. + if (start < self.data_start or start > self.bytes.len or size > self.bytes.len - start) return null; + return self.bytes[start..][0..size]; + } +}; + +/// The bytes one element of a ggml type takes; the quantized types are not sized here. +fn elemSize(kind: u32) ?usize { + return switch (kind) { + 0 => 4, // F32 + 1 => 2, // F16 + 24 => 1, // I8 + 25 => 2, // I16 + 26 => 4, // I32 + 27 => 8, // I64 + 28 => 8, // F64 + 30 => 2, // BF16 + else => null, + }; +} + +/// The elements a shape holds, or null when the shape overflows. +fn elemCount(dims: []const u64) ?usize { + var n: u64 = 1; + for (dims) |d| { + if (d == 0 or n > (1 << 40) / d) return null; + n *= d; + } + return std.math.cast(usize, n); +} + +/// A cursor over the container's bytes that refuses to read past its end. +const Cursor = struct { + b: []const u8, + o: usize = 0, + + fn need(self: *Cursor, n: usize) Error!void { + if (n > self.b.len or self.o + n > self.b.len) return error.BadGguf; + } + + fn u8v(self: *Cursor) Error!u8 { + try self.need(1); + defer self.o += 1; + return self.b[self.o]; + } + + fn u16v(self: *Cursor) Error!u16 { + try self.need(2); + defer self.o += 2; + return std.mem.readInt(u16, self.b[self.o..][0..2], .little); + } + + fn u32v(self: *Cursor) Error!u32 { + try self.need(4); + defer self.o += 4; + return std.mem.readInt(u32, self.b[self.o..][0..4], .little); + } + + fn u64v(self: *Cursor) Error!u64 { + try self.need(8); + defer self.o += 8; + return std.mem.readInt(u64, self.b[self.o..][0..8], .little); + } + + fn f32v(self: *Cursor) Error!f32 { + try self.need(4); + defer self.o += 4; + return @bitCast(std.mem.readInt(u32, self.b[self.o..][0..4], .little)); + } + + fn string(self: *Cursor) Error![]const u8 { + const n = try self.u64v(); + if (n > self.b.len) return error.BadGguf; + try self.need(@intCast(n)); + defer self.o += @intCast(n); + return self.b[self.o..][0..@intCast(n)]; + } +}; + +fn refuse(problem: *Problem, comptime fmt: []const u8, args: anytype) Error { + problem.set(fmt, args); + return error.BadGguf; +} + +/// Parse the header, the metadata and the tensor headers; the arena keeps every allocation. +pub fn parse(a: std.mem.Allocator, bytes: []const u8, problem: *Problem) Error!File { + if (bytes.len < 8) return refuse(problem, "the file is too short to be a container", .{}); + var c: Cursor = .{ .b = bytes }; + if (!std.mem.eql(u8, c.b[0..4], "GGUF")) return refuse(problem, "not a GGUF container", .{}); + c.o = 4; + const version = try c.u32v(); + if (version != 3) return refuse(problem, "GGUF version {d}; this container reader implements version 3", .{version}); + const tensor_count = try c.u64v(); + const kv_count = try c.u64v(); + if (tensor_count > 1 << 20 or kv_count > 1 << 16) return refuse(problem, "the container's counts are out of range", .{}); + + var entries: std.ArrayList(Entry) = .empty; + for (0..kv_count) |_| { + const key = try c.string(); + const kind = std.enums.fromInt(Type, try c.u32v()) orelse + return refuse(problem, "the container holds an unknown metadata type", .{}); + const value = try readValue(a, &c, kind, 0, problem); + try entries.append(a, .{ .key = key, .value = value }); + } + + var tensors: std.ArrayList(Tensor) = .empty; + for (0..tensor_count) |_| { + const name = try c.string(); + const n_dims = try c.u32v(); + if (n_dims > 8) return refuse(problem, "a tensor has {d} dimensions", .{n_dims}); + const dims = try a.alloc(u64, n_dims); + for (dims) |*d| d.* = try c.u64v(); + const kind = try c.u32v(); + const offset = try c.u64v(); + try tensors.append(a, .{ .name = name, .dims = dims, .kind = kind, .offset = offset }); + } + + const alignment = alignmentOf(entries.items) orelse default_alignment; + if (alignment == 0 or !std.math.isPowerOfTwo(alignment)) return refuse(problem, "the container's alignment is {d}", .{alignment}); + const data_start = alignUp(c.o, alignment) orelse return refuse(problem, "the container's alignment is {d}", .{alignment}); + + return .{ + .entries = entries.items, + .tensors = tensors.items, + .data_start = data_start, + .alignment = alignment, + .bytes = bytes, + }; +} + +fn readValue(a: std.mem.Allocator, c: *Cursor, kind: Type, depth: u8, problem: *Problem) Error!Value { + return switch (kind) { + .u8v => .{ .u8v = try c.u8v() }, + .i8v => .{ .i8v = @bitCast(try c.u8v()) }, + .u16v => .{ .u16v = try c.u16v() }, + .i16v => .{ .i16v = @bitCast(try c.u16v()) }, + .u32v => .{ .u32v = try c.u32v() }, + .i32v => .{ .i32v = @bitCast(try c.u32v()) }, + .f32v => .{ .f32v = try c.f32v() }, + .boolv => .{ .boolv = (try c.u8v()) != 0 }, + .string => .{ .string = try c.string() }, + .u64v => .{ .u64v = try c.u64v() }, + .i64v => .{ .i64v = @bitCast(try c.u64v()) }, + .f64v => .{ .f64v = @bitCast(try c.u64v()) }, + .array => blk: { + if (depth >= max_array_depth) return refuse(problem, "the container's metadata nests arrays deeper than {d}", .{max_array_depth}); + const elem = std.enums.fromInt(Type, try c.u32v()) orelse + return refuse(problem, "an array holds an unknown metadata type", .{}); + const n = try c.u64v(); + if (n > 1 << 20) return refuse(problem, "an array holds {d} items", .{n}); + const items = try a.alloc(Value, @intCast(n)); + for (items) |*it| it.* = try readValue(a, c, elem, depth + 1, problem); + break :blk .{ .array = .{ .elem = elem, .items = items } }; + }, + }; +} + +/// Write a container the way llama.cpp's convention lays it out; the returned bytes are owned by the caller. +pub fn write(a: std.mem.Allocator, entries: []const Entry, tensors: []const OutTensor) Error![]u8 { + const alignment = alignmentOf(entries) orelse default_alignment; + if (alignment == 0 or !std.math.isPowerOfTwo(alignment)) return error.BadGguf; + + // The tensor offsets are relative to the data section, so their place follows from the bytes alone. + const offsets = try a.alloc(u64, tensors.len); + defer a.free(offsets); + var data_len: usize = 0; + for (tensors, offsets) |t, *off| { + data_len = alignUp(data_len, alignment) orelse return error.BadGguf; + off.* = data_len; + data_len = std.math.add(usize, data_len, t.data.len) catch return error.BadGguf; + } + + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(a); + try out.appendSlice(a, "GGUF"); + try putU32(a, &out, 3); + try putU64(a, &out, tensors.len); + try putU64(a, &out, entries.len); + for (entries) |e| try writeEntry(a, &out, e); + for (tensors, offsets) |t, off| { + try putString(a, &out, t.name); + try putU32(a, &out, @intCast(t.dims.len)); + for (t.dims) |d| try putU64(a, &out, d); + try putU32(a, &out, t.kind); + try putU64(a, &out, off); + } + while (out.items.len % alignment != 0) try out.append(a, 0); + for (tensors) |t| { + while (out.items.len % alignment != 0) try out.append(a, 0); + try out.appendSlice(a, t.data); + } + return out.toOwnedSlice(a); +} + +/// The alignment a container's metadata names, or null when it names none this module understands. +fn alignmentOf(entries: []const Entry) ?usize { + for (entries) |e| { + if (!std.mem.eql(u8, e.key, "general.alignment")) continue; + return switch (e.value) { + .u32v => |x| x, + .u64v => |x| std.math.cast(usize, x), + else => default_alignment, + }; + } + return null; +} + +fn writeEntry(a: std.mem.Allocator, out: *std.ArrayList(u8), e: Entry) Error!void { + try putString(a, out, e.key); + try putU32(a, out, @backingInt(std.meta.activeTag(e.value))); + try writeValue(a, out, e.value); +} + +/// Write a value without its type tag; an array's items carry the array's element type instead. +fn writeValue(a: std.mem.Allocator, out: *std.ArrayList(u8), v: Value) Error!void { + switch (v) { + .u8v => |x| try out.append(a, x), + .i8v => |x| try out.append(a, @bitCast(x)), + .u16v => |x| try putU16(a, out, x), + .i16v => |x| try putU16(a, out, @bitCast(x)), + .u32v => |x| try putU32(a, out, x), + .i32v => |x| try putU32(a, out, @bitCast(x)), + .f32v => |x| try putU32(a, out, @bitCast(x)), + .boolv => |x| try out.append(a, if (x) 1 else 0), + .string => |s| try putString(a, out, s), + .array => |arr| { + for (arr.items) |it| { + if (std.meta.activeTag(it) != arr.elem) return error.BadGguf; + } + try putU32(a, out, @backingInt(arr.elem)); + try putU64(a, out, arr.items.len); + for (arr.items) |it| try writeValue(a, out, it); + }, + .u64v => |x| try putU64(a, out, x), + .i64v => |x| try putU64(a, out, @bitCast(x)), + .f64v => |x| try putU64(a, out, @bitCast(x)), + } +} + +/// The first place at or after x that a divides; null when that place does not fit. +fn alignUp(x: usize, a: usize) ?usize { + const last = std.math.add(usize, x, a - 1) catch return null; + return last / a * a; +} + +fn putU16(a: std.mem.Allocator, out: *std.ArrayList(u8), x: u16) Error!void { + var buf: [2]u8 = undefined; + std.mem.writeInt(u16, &buf, x, .little); + try out.appendSlice(a, &buf); +} + +fn putU32(a: std.mem.Allocator, out: *std.ArrayList(u8), x: u32) Error!void { + var buf: [4]u8 = undefined; + std.mem.writeInt(u32, &buf, x, .little); + try out.appendSlice(a, &buf); +} + +fn putU64(a: std.mem.Allocator, out: *std.ArrayList(u8), x: u64) Error!void { + var buf: [8]u8 = undefined; + std.mem.writeInt(u64, &buf, x, .little); + try out.appendSlice(a, &buf); +} + +fn putString(a: std.mem.Allocator, out: *std.ArrayList(u8), s: []const u8) Error!void { + try putU64(a, out, s.len); + try out.appendSlice(a, s); +} diff --git a/zig/src/core/glp_container_test.zig b/zig/src/core/glp_container_test.zig new file mode 100644 index 00000000000..5e653c746ec --- /dev/null +++ b/zig/src/core/glp_container_test.zig @@ -0,0 +1,50 @@ +//! The GGUF subset's own bounds: tensor offsets and metadata arrays, refused rather than wrapping or recursing. + +const std = @import("std"); +const gguf = @import("glp_container.zig"); + +test "a tensor offset that would wind past the address space is refused, not wrapped" { + const bytes = try std.testing.allocator.alloc(u8, 64); + defer std.testing.allocator.free(bytes); + const dims = [_]u64{8}; + const file: gguf.File = .{ .entries = &.{}, .tensors = &.{}, .data_start = 8, .alignment = 32, .bytes = bytes }; + const t: gguf.Tensor = .{ .name = "direction.10", .dims = &dims, .kind = gguf.f32_type, .offset = std.math.maxInt(u64) - 15 }; + // data_start + offset is eight bytes short of the end, where a start + size check would wrap into the file. + try std.testing.expect(file.bytesOf(t) == null); + const inside: gguf.Tensor = .{ .name = "direction.10", .dims = &dims, .kind = gguf.f32_type, .offset = 0 }; + try std.testing.expectEqual(@as(usize, 32), file.bytesOf(inside).?.len); +} + +test "metadata arrays nested past the limit are refused" { + // Four arrays inside one another parse; eight do not recurse. + for ([_]u8{ 4, 8 }) |depth| { + const bytes = try nested(depth); + defer std.testing.allocator.free(bytes); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + var problem: gguf.Problem = .{}; + if (depth == 4) { + _ = try gguf.parse(arena.allocator(), bytes, &problem); + continue; + } + try std.testing.expectError(error.BadGguf, gguf.parse(arena.allocator(), bytes, &problem)); + try std.testing.expect(std.mem.indexOf(u8, problem.text(), "nests arrays deeper than") != null); + } +} + +/// A container whose only metadata value is `depth` arrays inside one another. +fn nested(depth: u8) ![]u8 { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const tmp = arena.allocator(); + var value: gguf.Value = .{ .u32v = 1 }; + for (0..depth) |_| { + const items = try tmp.alloc(gguf.Value, 1); + items[0] = value; + // The tag is read before the assignment: result-location semantics make `value` the new union already. + const elem = std.meta.activeTag(value); + value = .{ .array = .{ .elem = elem, .items = items } }; + } + const entries = [_]gguf.Entry{.{ .key = "general.notes", .value = value }}; + return gguf.write(std.testing.allocator, &entries, &.{}); +} diff --git a/zig/src/core/glp_publication_test.zig b/zig/src/core/glp_publication_test.zig new file mode 100644 index 00000000000..f21211965cb --- /dev/null +++ b/zig/src/core/glp_publication_test.zig @@ -0,0 +1,182 @@ +//! What the GLP container says about itself: the keys a consumer reads before it reads the directions. + +const std = @import("std"); +const gguf = @import("glp_container.zig"); +const glp = @import("glp.zig"); +const t = @import("glp_test.zig"); + +test "a file that names itself carries what it said, and the model it came from" { + const a = std.testing.allocator; + const dir = try t.unitDir(a, 8, 0); + defer a.free(dir); + const layers = [_]glp.Layer{.{ .id = 10, .dir = dir }}; + const bytes = try glp.write(a, .{ + .base_model = "TensorFold/Qwen3.8-27B-MLX-4bit", + .base_revision = "22d8d538154e0e5b6f8dcb1fcc74a60a0798104c", + .publication = .{ + .name = "Qwen3.8-27B-sample-cvec-per_layer-L10-58-a1", + .description = "A sample control vector.", + .author = "TensorFold", + .license = "MIT", + .model_hint = "qwen3_5", + .measured_effect = "a sample note on the strength", + .created = "2026-10-27", + }, + .layers = &layers, + }); + defer a.free(bytes); + var read = try t.readOk(bytes); + defer read.deinit(); + const p = read.vector.publication; + try std.testing.expectEqualStrings("Qwen3.8-27B-sample-cvec-per_layer-L10-58-a1", p.name.?); + try std.testing.expectEqualStrings("A sample control vector.", p.description.?); + try std.testing.expectEqualStrings("TensorFold", p.author.?); + try std.testing.expectEqualStrings("MIT", p.license.?); + try std.testing.expectEqualStrings("qwen3_5", p.model_hint.?); + try std.testing.expectEqualStrings("a sample note on the strength", p.measured_effect.?); + try std.testing.expectEqualStrings("2026-10-27", p.created.?); + + // The container itself carries the keys a consumer reads, not only the reader. + var parsed = try t.parseFile(a, bytes); + defer parsed.deinit(); + try std.testing.expectEqualStrings("Qwen3.8-27B-sample-cvec-per_layer-L10-58-a1", parsed.file.str("general.name").?); + try std.testing.expectEqualStrings("TensorFold", parsed.file.str("general.author").?); + try std.testing.expectEqualStrings("qwen3_5", parsed.file.str("controlvector.model_hint").?); + try std.testing.expectEqual(@as(u64, 1), parsed.file.num("controlvector.layer_count").?); + try std.testing.expectEqual(@as(u64, 1), parsed.file.num("general.base_model.count").?); + try std.testing.expectEqualStrings("Qwen3.8-27B-MLX-4bit", parsed.file.str("general.base_model.0.name").?); + try std.testing.expectEqualStrings("TensorFold", parsed.file.str("general.base_model.0.organization").?); + try std.testing.expectEqualStrings("22d8d538154e0e5b6f8dcb1fcc74a60a0798104c", parsed.file.str("general.base_model.0.version").?); + try std.testing.expectEqualStrings("https://huggingface.co/TensorFold/Qwen3.8-27B-MLX-4bit", parsed.file.str("general.base_model.0.repo_url").?); +} + +test "a vector written again keeps what the file said about itself" { + const a = std.testing.allocator; + const dir = try t.unitDir(a, 8, 0); + defer a.free(dir); + const layers = [_]glp.Layer{.{ .id = 10, .dir = dir }}; + const bytes = try glp.write(a, .{ + .base_model = "Qwen/Qwen3.8-27B", + .publication = .{ .name = "a name", .author = "an author" }, + .layers = &layers, + }); + defer a.free(bytes); + var read = try t.readOk(bytes); + defer read.deinit(); + const again = try glp.writeVector(a, read.vector); + defer a.free(again); + var reread = try t.readOk(again); + defer reread.deinit(); + try std.testing.expectEqualStrings("a name", reread.vector.publication.name.?); + try std.testing.expectEqualStrings("an author", reread.vector.publication.author.?); +} + +test "a file that names no model of its own keeps the base model out of the header" { + const a = std.testing.allocator; + const dir = try t.unitDir(a, 8, 0); + defer a.free(dir); + const layers = [_]glp.Layer{.{ .id = 10, .dir = dir }}; + const bytes = try glp.write(a, .{ .layers = &layers }); + defer a.free(bytes); + var parsed = try t.parseFile(a, bytes); + defer parsed.deinit(); + try std.testing.expect(parsed.file.str("general.base_model.0.repo_url") == null); + try std.testing.expectEqual(@as(u64, 1), parsed.file.num("controlvector.layer_count").?); +} + +test "a file that names no other site names the site it is applied at" { + const a = std.testing.allocator; + const dir = try t.unitDir(a, 8, 0); + defer a.free(dir); + const layers = [_]glp.Layer{.{ .id = 10, .dir = dir }}; + const bytes = try glp.write(a, .{ .hook_point = glp.residual_site, .layers = &layers }); + defer a.free(bytes); + var parsed = try t.parseFile(a, bytes); + defer parsed.deinit(); + // glp.derived_at is the site the direction was captured at, not a time. + try std.testing.expectEqualStrings("residual_stream_post_layer", parsed.file.str("glp.derived_at").?); + var read = try t.readOk(bytes); + defer read.deinit(); + try std.testing.expect(!read.vector.transferred); +} + +fn readReasonWithBadKey(a: std.mem.Allocator, base_model: []const u8, bad_key: []const u8) ![]const u8 { + const dir = try t.unitDir(a, 8, 0); + defer a.free(dir); + const layers = [_]glp.Layer{.{ .id = 10, .dir = dir }}; + const base_bytes = try glp.write(a, .{ + .base_model = base_model, + .base_revision = "1111111111111111111111111111111111111111", + .layers = &layers, + }); + defer a.free(base_bytes); + var parsed = try t.parseFile(a, base_bytes); + defer parsed.deinit(); + var entries: std.ArrayList(gguf.Entry) = .empty; + defer entries.deinit(a); + var replaced = false; + for (parsed.file.entries) |e| { + if (std.mem.eql(u8, e.key, bad_key)) { + try entries.append(a, .{ .key = bad_key, .value = .{ .u32v = 7 } }); + replaced = true; + } else { + try entries.append(a, e); + } + } + if (!replaced) try entries.append(a, .{ .key = bad_key, .value = .{ .u32v = 7 } }); + var tensors: std.ArrayList(gguf.OutTensor) = .empty; + defer tensors.deinit(a); + for (parsed.file.tensors) |ten| { + try tensors.append(a, .{ .name = ten.name, .dims = ten.dims, .kind = ten.kind, .data = parsed.file.bytesOf(ten).? }); + } + const forged = try gguf.write(a, entries.items, tensors.items); + defer a.free(forged); + var arena: std.heap.ArenaAllocator = .init(a); + defer arena.deinit(); + var why: glp.Why = .{}; + if (glp.read(arena.allocator(), forged, &why)) |_| { + return error.NotRefused; + } else |err| { + if (err != error.BadGlpVector) return err; + return a.dupe(u8, why.text()); + } +} + +test "non-string executable metadata keys are refused instead of skipped" { + const a = std.testing.allocator; + const keys = [_][]const u8{ + "glp.base_model", + "general.base_model.0.repo_url", + "glp.base_revision", + "glp.hook_point", + "glp.derived_at", + "glp.layer_ids_zero_based", + }; + for (keys) |bad_key| { + for ([_][]const u8{ "Qwen/Qwen3.8-27B", "" }) |model| { + const why = try readReasonWithBadKey(a, model, bad_key); + defer a.free(why); + try std.testing.expect(std.mem.indexOf(u8, why, bad_key) != null); + try std.testing.expect(std.mem.indexOf(u8, why, "is not text") != null); + } + } +} + +test "valid string revision still rejects a mismatched snapshot revision" { + const a = std.testing.allocator; + const dir = try t.unitDir(a, 8, 0); + defer a.free(dir); + const layers = [_]glp.Layer{.{ .id = 10, .dir = dir }}; + const bytes = try glp.write(a, .{ + .base_model = "Qwen/Qwen3.8-27B", + .base_revision = "22d8d538154e0e5b6f8dcb1fcc74a60a0798104c", + .layers = &layers, + }); + defer a.free(bytes); + var read = try t.readOk(bytes); + defer read.deinit(); + var why: glp.Why = .{}; + try glp.checkRevision(read.vector, "Qwen/Qwen3.8-27B", "22d8d538154e", &why); + try std.testing.expectError(error.BadGlpVector, glp.checkRevision(read.vector, "Qwen/Qwen3.8-27B", "0000000000000000000000000000000000000000", &why)); + try std.testing.expect(std.mem.indexOf(u8, why.text(), "revision") != null); +} diff --git a/zig/src/core/glp_test.zig b/zig/src/core/glp_test.zig new file mode 100644 index 00000000000..63f1410e0a7 --- /dev/null +++ b/zig/src/core/glp_test.zig @@ -0,0 +1,594 @@ +//! The GLP container's acceptance rules, over synthetic containers written the way a producer writes them. + +const std = @import("std"); +const glp = @import("glp.zig"); +const gguf = @import("glp_container.zig"); + +/// What a container holds, so a test can bend one rule at a time. +const Shape = struct { + mode: ?[]const u8 = "add", + spec_version: ?u32 = 1, + rank: ?u32 = 1, + hook_point: ?[]const u8 = "residual_stream_post_layer", + derived_at: ?[]const u8 = null, + alpha: f32 = 1.0, + numeric_text: ?enum { alpha, rank, version } = null, + layers: []const u32 = &.{ 10, 11 }, + width: usize = 8, + unit: bool = true, + /// Every component's value, when a test needs one that is not finite. + value: ?f32 = null, + digest: enum { correct, wrong, absent } = .correct, + /// A digest key holding a number, which no file reports as verified. + digest_not_text: bool = false, + base_model: ?[]const u8 = "Qwen/Qwen3.8-27B", + layer_ids_key: bool = true, + layer_ids: ?[]const u8 = null, + /// Tensor names to write instead of "direction.", so a test can name one layer twice. + tensor_names: ?[]const []const u8 = null, + /// A general.description value, so its text can read like a metadata key. + description: ?[]const u8 = null, + extra_key: ?[]const u8 = null, +}; + +/// The metadata a fixture writes: the key's bytes and how many keys there are. +const Kv = struct { + bytes: std.ArrayList(u8) = .empty, + count: u64 = 0, + a: std.mem.Allocator, + + fn init(a: std.mem.Allocator) Kv { + return .{ .a = a }; + } + + fn deinit(self: *Kv) void { + self.bytes.deinit(self.a); + } + + fn key(self: *Kv, name: []const u8) !void { + try self.bytes.appendSlice(self.a, &std.mem.toBytes(@as(u64, name.len))); + try self.bytes.appendSlice(self.a, name); + self.count += 1; + } + + fn text(self: *Kv, name: []const u8, value: []const u8) !void { + try self.key(name); + try self.bytes.appendSlice(self.a, &std.mem.toBytes(@as(u32, 8))); + try self.bytes.appendSlice(self.a, &std.mem.toBytes(@as(u64, value.len))); + try self.bytes.appendSlice(self.a, value); + } + + fn number(self: *Kv, name: []const u8, value: u32) !void { + try self.key(name); + try self.bytes.appendSlice(self.a, &std.mem.toBytes(@as(u32, 4))); + try self.bytes.appendSlice(self.a, &std.mem.toBytes(value)); + } + + fn real(self: *Kv, name: []const u8, value: f32) !void { + try self.key(name); + try self.bytes.appendSlice(self.a, &std.mem.toBytes(@as(u32, 6))); + try self.bytes.appendSlice(self.a, &std.mem.toBytes(@as(u32, @bitCast(value)))); + } +}; + +/// Write a container holding one direction per listed layer. +fn writeFixture(shape: Shape) ![]u8 { + const a = std.testing.allocator; + var payload: std.ArrayList(u8) = .empty; + defer payload.deinit(a); + var offsets: std.ArrayList(u64) = .empty; + defer offsets.deinit(a); + for (shape.layers) |_| { + try offsets.append(a, payload.items.len); + for (0..shape.width) |_| { + const v: f32 = shape.value orelse if (shape.unit) 1.0 / @sqrt(@as(f32, @floatFromInt(shape.width))) else 0.25; + try payload.appendSlice(a, &std.mem.toBytes(@as(u32, @bitCast(v)))); + } + } + + var h: std.crypto.hash.sha2.Sha256 = .init(.{}); + h.update(payload.items); + var sha: [32]u8 = undefined; + h.final(&sha); + const hex = std.fmt.bytesToHex(sha, .lower); + + var kv: Kv = Kv.init(a); + defer kv.deinit(); + try kv.text("general.architecture", "controlvector"); + try kv.text("general.alignment", "32"); + if (shape.mode) |m| try kv.text("glp.mode", m); + if (shape.numeric_text == .version) try kv.text("glp.spec_version", "1") else if (shape.spec_version) |v| try kv.number("glp.spec_version", v); + if (shape.numeric_text == .rank) try kv.text("glp.rank", "1") else if (shape.rank) |v| try kv.number("glp.rank", v); + if (shape.numeric_text == .alpha) try kv.text("glp.alpha_default", "1") else try kv.real("glp.alpha_default", shape.alpha); + if (shape.hook_point) |h2| try kv.text("glp.hook_point", h2); + if (shape.derived_at) |d| try kv.text("glp.derived_at", d); + if (shape.base_model) |b| try kv.text("glp.base_model", b); + if (shape.layer_ids_key) { + if (shape.layer_ids) |ids| { + try kv.text("glp.layer_ids_zero_based", ids); + } else { + var list: std.ArrayList(u8) = .empty; + defer list.deinit(a); + for (shape.layers, 0..) |id, i| { + if (i > 0) try list.appendSlice(a, ","); + try list.print(a, "{d}", .{id}); + } + try kv.text("glp.layer_ids_zero_based", list.items); + } + } + if (shape.digest_not_text) { + try kv.number("glp.content_sha256", 0); + } else switch (shape.digest) { + .correct => try kv.text("glp.content_sha256", &hex), + .wrong => try kv.text("glp.content_sha256", "0000000000000000000000000000000000000000000000000000000000000000"), + .absent => {}, + } + if (shape.description) |d| try kv.text("general.description", d); + if (shape.extra_key) |k| try kv.text(k, "0.5"); + + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(a); + try out.appendSlice(a, "GGUF"); + try out.appendSlice(a, &std.mem.toBytes(@as(u32, 3))); + try out.appendSlice(a, &std.mem.toBytes(@as(u64, shape.layers.len))); + try out.appendSlice(a, &std.mem.toBytes(kv.count)); + try out.appendSlice(a, kv.bytes.items); + for (shape.layers, offsets.items, 0..) |id, off, i| { + var name_buf: [32]u8 = undefined; + const name = if (shape.tensor_names) |names| names[i] else try std.fmt.bufPrint(&name_buf, "direction.{d}", .{id}); + try out.appendSlice(a, &std.mem.toBytes(@as(u64, name.len))); + try out.appendSlice(a, name); + try out.appendSlice(a, &std.mem.toBytes(@as(u32, 1))); + try out.appendSlice(a, &std.mem.toBytes(@as(u64, shape.width))); + try out.appendSlice(a, &std.mem.toBytes(@as(u32, 0))); + try out.appendSlice(a, &std.mem.toBytes(off)); + } + while (out.items.len % 32 != 0) try out.append(a, 0); + try out.appendSlice(a, payload.items); + return out.toOwnedSlice(a); +} + +/// A vector and the arena that holds its strings and layers. +pub const Read = struct { + arena: std.heap.ArenaAllocator, + vector: glp.Vector, + + pub fn deinit(self: *Read) void { + self.arena.deinit(); + } +}; + +pub fn readOk(bytes: []const u8) !Read { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + errdefer arena.deinit(); + var why: glp.Why = .{}; + const v = try glp.read(arena.allocator(), bytes, &why); + return .{ .arena = arena, .vector = v }; +} + +/// Fail unless the file was refused. +fn refused(bytes: []const u8) !void { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: glp.Why = .{}; + if (glp.read(arena.allocator(), bytes, &why)) |_| { + return error.NotRefused; + } else |err| { + if (err != error.BadGlpVector) return err; + } +} + +/// The reason a file was refused, copied out so it outlives the arena. +fn reason(bytes: []const u8) ![]const u8 { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + var why: glp.Why = .{}; + if (glp.read(arena.allocator(), bytes, &why)) |_| { + return error.NotRefused; + } else |err| { + if (err != error.BadGlpVector) return err; + return std.testing.allocator.dupe(u8, why.text()); + } +} + +/// A unit vector of a given width, pointing along one axis. +pub fn unitDir(a: std.mem.Allocator, width: usize, axis: usize) ![]f32 { + const dir = try a.alloc(f32, width); + for (dir) |*v| v.* = 0.0; + dir[axis] = 1.0; + return dir; +} + +/// A container and the arena that holds its metadata. +pub const Parsed = struct { + arena: std.heap.ArenaAllocator, + file: gguf.File, + + pub fn deinit(self: *Parsed) void { + self.arena.deinit(); + } +}; + +/// The container a file holds, read with the generic reader. +pub fn parseFile(a: std.mem.Allocator, bytes: []const u8) !Parsed { + var arena = std.heap.ArenaAllocator.init(a); + errdefer arena.deinit(); + var problem: gguf.Problem = .{}; + const file = try gguf.parse(arena.allocator(), bytes, &problem); + return .{ .arena = arena, .file = file }; +} + +/// The vector a producer writes for two layers, handed over in the order a caller would hold them. +fn writeSample(a: std.mem.Allocator) ![]u8 { + const dir10 = try unitDir(a, 8, 0); + defer a.free(dir10); + const dir11 = try unitDir(a, 8, 1); + defer a.free(dir11); + const layers = [_]glp.Layer{ .{ .id = 11, .dir = dir11 }, .{ .id = 10, .dir = dir10 } }; + return glp.write(a, .{ + .alpha = 0.75, + .hook_point = glp.residual_site, + .derived_at = null, + .base_model = "Qwen/Qwen3.8-27B", + .base_revision = "1d4bf0f2ff6012fd82039f2fa52739d0dd7c60c0", + .method = "difference_of_means_per_layer", + .contrast = "matched_prompts_unpaired", + .layers = &layers, + }); +} + +test "a vector with the metadata a producer writes is accepted" { + const bytes = try writeFixture(.{}); + defer std.testing.allocator.free(bytes); + var read = try readOk(bytes); + defer read.deinit(); + const v = read.vector; + var want: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &want, .{}); + try std.testing.expectEqualSlices(u8, &want, &v.file_sha256); + try std.testing.expectEqual(@as(f32, 1.0), v.alpha); + try std.testing.expectEqual(@as(usize, 8), v.width); + try std.testing.expectEqual(@as(usize, 2), v.layers.len); + try std.testing.expectEqual(@as(u32, 10), v.layers[0].id); + try std.testing.expectEqual(@as(u32, 11), v.layers[1].id); + try std.testing.expectEqualStrings("residual_stream_post_layer", v.hook_point); + try std.testing.expectEqualStrings("Qwen/Qwen3.8-27B", v.base_model); + try std.testing.expect(!v.transferred); +} + +test "a file with no glp keys is llama.cpp's additive control vector" { + const bytes = try writeFixture(.{ .mode = null, .spec_version = null, .rank = null, .hook_point = null, .layer_ids_key = false, .digest = .absent }); + defer std.testing.allocator.free(bytes); + var read = try readOk(bytes); + defer read.deinit(); + const v = read.vector; + try std.testing.expectEqual(@as(usize, 2), v.layers.len); +} + +test "a mode other than add is refused, project by name" { + for ([_][]const u8{ "scale", "project" }) |mode| { + const bytes = try writeFixture(.{ .mode = mode }); + defer std.testing.allocator.free(bytes); + const why = try reason(bytes); + defer std.testing.allocator.free(why); + try std.testing.expect(std.mem.indexOf(u8, why, "add vectors only") != null); + } +} + +test "a spec version this reader does not implement is refused" { + const bytes = try writeFixture(.{ .spec_version = 2 }); + defer std.testing.allocator.free(bytes); + try refused(bytes); +} + +test "a text spec_version with no other counted glp key is refused, not read as unversioned" { + const bytes = try writeFixture(.{ .mode = null, .rank = null, .hook_point = null, .numeric_text = .version, .layer_ids_key = false, .digest = .absent }); + defer std.testing.allocator.free(bytes); + try refused(bytes); +} + +test "a rank above one is refused" { + const bytes = try writeFixture(.{ .rank = 2 }); + defer std.testing.allocator.free(bytes); + try refused(bytes); +} + +test "numeric GLP metadata cannot be text" { + for ([_]Shape{ .{ .numeric_text = .alpha }, .{ .numeric_text = .rank }, .{ .numeric_text = .version } }) |shape| { + const bytes = try writeFixture(shape); + defer std.testing.allocator.free(bytes); + const why = try reason(bytes); + defer std.testing.allocator.free(why); + const key = switch (shape.numeric_text.?) { + .alpha => "glp.alpha_default", + .rank => "glp.rank", + .version => "glp.spec_version", + }; + try std.testing.expect(std.mem.indexOf(u8, why, key) != null); + } +} + +test "a hook point this reader does not apply at is refused" { + const bytes = try writeFixture(.{ .hook_point = "ffn_out_pre_residual" }); + defer std.testing.allocator.free(bytes); + try refused(bytes); +} + +test "layer zero is not steerable" { + const bytes = try writeFixture(.{ .layers = &.{ 0, 11 } }); + defer std.testing.allocator.free(bytes); + try refused(bytes); +} + +test "an additive direction needs no unit length" { + const bytes = try writeFixture(.{ .unit = false }); + defer std.testing.allocator.free(bytes); + var read = try readOk(bytes); + defer read.deinit(); + try std.testing.expectEqual(@as(usize, 2), read.vector.layers.len); +} + +test "a direction that is not finite is refused" { + for ([_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }) |value| { + const bytes = try writeFixture(.{ .value = value }); + defer std.testing.allocator.free(bytes); + const why = try reason(bytes); + defer std.testing.allocator.free(why); + try std.testing.expect(std.mem.indexOf(u8, why, "not finite") != null); + } +} + +test "a content digest that does not cover the vectors is refused" { + const bytes = try writeFixture(.{ .digest = .wrong }); + defer std.testing.allocator.free(bytes); + try refused(bytes); +} + +test "a layer id list that disagrees with the tensors is refused" { + const bytes = try writeFixture(.{ .layers = &.{ 10, 11 }, .layer_ids = "9,10" }); + defer std.testing.allocator.free(bytes); + const why = try reason(bytes); + defer std.testing.allocator.free(why); + try std.testing.expect(std.mem.indexOf(u8, why, "layer id") != null); +} + +test "a vector derived at another site is a warning, not a refusal" { + const bytes = try writeFixture(.{ .derived_at = "ffn_out_pre_residual" }); + defer std.testing.allocator.free(bytes); + var read = try readOk(bytes); + defer read.deinit(); + const v = read.vector; + try std.testing.expect(v.transferred); +} + +test "a vector whose width is not the model's is refused" { + const bytes = try writeFixture(.{}); + defer std.testing.allocator.free(bytes); + var read = try readOk(bytes); + defer read.deinit(); + const v = read.vector; + var why: glp.Why = .{}; + try std.testing.expectError(error.BadGlpVector, glp.checkModel(v, 4096, "Qwen/Qwen3.8-27B", &why)); + try std.testing.expect(std.mem.indexOf(u8, why.text(), "wide") != null); +} + +test "a vector for another checkpoint is refused" { + const bytes = try writeFixture(.{}); + defer std.testing.allocator.free(bytes); + var read = try readOk(bytes); + defer read.deinit(); + const v = read.vector; + var why: glp.Why = .{}; + try std.testing.expectError(error.BadGlpVector, glp.checkModel(v, 8, "Qwen/Qwen3.5-2B", &why)); + try std.testing.expect(std.mem.indexOf(u8, why.text(), "the model is") != null); +} + +test "a truncated file is refused, not read past" { + const bytes = try writeFixture(.{}); + defer std.testing.allocator.free(bytes); + const cut = try std.testing.allocator.dupe(u8, bytes[0 .. bytes.len - 64]); + defer std.testing.allocator.free(cut); + try refused(cut); +} + +test "a file that ends inside its metadata is refused with a reason" { + const a = std.testing.allocator; + var b: std.ArrayList(u8) = .empty; + defer b.deinit(a); + // A GGUF header whose one metadata key is longer than the bytes that follow it. + try b.appendSlice(a, "GGUF"); + try b.appendSlice(a, &std.mem.toBytes(@as(u32, 3))); + try b.appendSlice(a, &std.mem.toBytes(@as(u64, 0))); + try b.appendSlice(a, &std.mem.toBytes(@as(u64, 1))); + try b.appendSlice(a, &std.mem.toBytes(@as(u64, 100))); + const why = try reason(b.items); + defer a.free(why); + try std.testing.expect(why.len > 0); + try std.testing.expect(std.mem.indexOf(u8, why, "ends before its metadata") != null); +} + +test "a written vector's digest covers its tensor bytes" { + const a = std.testing.allocator; + const bytes = try writeSample(a); + defer a.free(bytes); + var parsed = try parseFile(a, bytes); + defer parsed.deinit(); + const claimed = parsed.file.str("glp.content_sha256").?; + var h: std.crypto.hash.sha2.Sha256 = .init(.{}); + for (parsed.file.tensors) |t| h.update(parsed.file.bytesOf(t).?); + var sha: [32]u8 = undefined; + h.final(&sha); + const hex = std.fmt.bytesToHex(sha, .lower); + try std.testing.expectEqualStrings(hex[0..], claimed); +} + +test "a written vector derived at another site is transferred" { + const a = std.testing.allocator; + const dir = try unitDir(a, 4, 0); + defer a.free(dir); + const layers = [_]glp.Layer{.{ .id = 10, .dir = dir }}; + const bytes = try glp.write(a, .{ .hook_point = glp.residual_site, .derived_at = "ffn_out_pre_residual", .layers = &layers }); + defer a.free(bytes); + var read = try readOk(bytes); + defer read.deinit(); + const v = read.vector; + try std.testing.expect(v.transferred); + try std.testing.expectEqualStrings("ffn_out_pre_residual", v.derived_at); + try std.testing.expectEqualStrings("residual_stream_post_layer", v.hook_point); +} + +test "a vector re-stamped for another checkpoint keeps its directions" { + const a = std.testing.allocator; + const bytes = try writeSample(a); + defer a.free(bytes); + var read = try readOk(bytes); + defer read.deinit(); + // The same weights under another name: the directions stay, the checkpoint they name changes. + const again = try glp.write(a, .{ + .alpha = read.vector.alpha, + .hook_point = read.vector.hook_point, + .derived_at = read.vector.derived_at, + .base_model = "mlx-community/Qwen3.8-27B-4bit", + .base_revision = "10c35caafbb80f7dc6a7a432cdd11af10a6d4818", + .method = read.vector.method, + .contrast = read.vector.contrast, + .publication = read.vector.publication, + .layers = read.vector.layers, + }); + defer a.free(again); + var reread = try readOk(again); + defer reread.deinit(); + try std.testing.expectEqualStrings("mlx-community/Qwen3.8-27B-4bit", reread.vector.base_model); + try std.testing.expectEqualStrings("10c35caafbb80f7dc6a7a432cdd11af10a6d4818", reread.vector.base_revision); + // The numbers and the digest over them are what they were: only the name moved. + try std.testing.expectEqualSlices(u8, &read.vector.sha256, &reread.vector.sha256); + try std.testing.expectEqual(read.vector.layers.len, reread.vector.layers.len); + for (read.vector.layers, reread.vector.layers) |before, after| { + try std.testing.expectEqual(before.id, after.id); + try std.testing.expectEqualSlices(f32, before.dir, after.dir); + } + // The binding moved with it: the new checkpoint takes the vector, the old one does not. + var why: glp.Why = .{}; + try glp.checkModel(reread.vector, 8, "mlx-community/Qwen3.8-27B-4bit", &why); + try std.testing.expectError(error.BadGlpVector, glp.checkModel(reread.vector, 8, "Qwen/Qwen3.8-27B", &why)); +} + +test "a producer refuses a direction that is not finite" { + const a = std.testing.allocator; + const dir = try a.alloc(f32, 4); + defer a.free(dir); + @memset(dir, std.math.nan(f32)); + const layers = [_]glp.Layer{.{ .id = 10, .dir = dir }}; + try std.testing.expectError(error.BadGlpVector, glp.write(a, .{ .layers = &layers })); +} + +test "a producer refuses a layer the reader cannot steer" { + const a = std.testing.allocator; + const dir = try unitDir(a, 4, 0); + defer a.free(dir); + const layers = [_]glp.Layer{.{ .id = 0, .dir = dir }}; + try std.testing.expectError(error.BadGlpVector, glp.write(a, .{ .layers = &layers })); +} + +test "the container keeps every value type it is given" { + const a = std.testing.allocator; + const entries = [_]gguf.Entry{ + .{ .key = "a.u8", .value = .{ .u8v = 7 } }, + .{ .key = "a.i8", .value = .{ .i8v = -7 } }, + .{ .key = "a.u16", .value = .{ .u16v = 1000 } }, + .{ .key = "a.i16", .value = .{ .i16v = -1000 } }, + .{ .key = "a.u32", .value = .{ .u32v = 100000 } }, + .{ .key = "a.i32", .value = .{ .i32v = -100000 } }, + .{ .key = "a.f32", .value = .{ .f32v = 0.5 } }, + .{ .key = "a.bool", .value = .{ .boolv = true } }, + .{ .key = "a.string", .value = .{ .string = "hello" } }, + .{ .key = "a.array", .value = .{ .array = .{ .elem = .u32v, .items = &.{ .{ .u32v = 1 }, .{ .u32v = 2 } } } } }, + .{ .key = "a.u64", .value = .{ .u64v = 1 << 40 } }, + .{ .key = "a.i64", .value = .{ .i64v = -(1 << 40) } }, + .{ .key = "a.f64", .value = .{ .f64v = 0.25 } }, + }; + const bytes = try gguf.write(a, &entries, &.{}); + defer a.free(bytes); + var parsed = try parseFile(a, bytes); + defer parsed.deinit(); + try std.testing.expectEqual(@as(usize, 13), parsed.file.entries.len); + try std.testing.expectEqual(@as(u8, 7), parsed.file.find("a.u8").?.u8v); + try std.testing.expectEqual(@as(i8, -7), parsed.file.find("a.i8").?.i8v); + try std.testing.expectEqual(@as(u16, 1000), parsed.file.find("a.u16").?.u16v); + try std.testing.expectEqual(@as(i16, -1000), parsed.file.find("a.i16").?.i16v); + try std.testing.expectEqual(@as(u32, 100000), parsed.file.find("a.u32").?.u32v); + try std.testing.expectEqual(@as(i32, -100000), parsed.file.find("a.i32").?.i32v); + try std.testing.expectEqual(@as(f32, 0.5), parsed.file.find("a.f32").?.f32v); + try std.testing.expectEqual(true, parsed.file.find("a.bool").?.boolv); + try std.testing.expectEqualStrings("hello", parsed.file.find("a.string").?.string); + try std.testing.expectEqual(@as(usize, 2), parsed.file.find("a.array").?.array.items.len); + try std.testing.expectEqual(@as(u32, 2), parsed.file.find("a.array").?.array.items[1].u32v); + try std.testing.expectEqual(@as(u64, 1 << 40), parsed.file.find("a.u64").?.u64v); + try std.testing.expectEqual(@as(i64, -(1 << 40)), parsed.file.find("a.i64").?.i64v); + try std.testing.expectEqual(@as(f64, 0.25), parsed.file.find("a.f64").?.f64v); +} + +test "a conversion of the vector's model takes the vector" { + const bytes = try writeFixture(.{}); + defer std.testing.allocator.free(bytes); + var read = try readOk(bytes); + defer read.deinit(); + const v = read.vector; + var why: glp.Why = .{}; + try glp.checkModel(v, 8, "TensorFold/Qwen3.8-27B-MLX-4bit", &why); + try glp.checkModel(v, 8, "Qwen/Qwen3.8-27B", &why); +} + +test "a different model of the same size is refused" { + const bytes = try writeFixture(.{}); + defer std.testing.allocator.free(bytes); + var read = try readOk(bytes); + defer read.deinit(); + const v = read.vector; + var why: glp.Why = .{}; + try std.testing.expectError(error.BadGlpVector, glp.checkModel(v, 8, "Qwen/Qwen3.5-2B", &why)); +} + +test "a file that names one layer twice is refused" { + const names = [_][]const u8{ "direction.5", "direction.05" }; + const bytes = try writeFixture(.{ .layers = &.{ 5, 5 }, .tensor_names = &names }); + defer std.testing.allocator.free(bytes); + try refused(bytes); + const why = try reason(bytes); + defer std.testing.allocator.free(why); + try std.testing.expect(std.mem.indexOf(u8, why, "two directions for layer 5") != null); +} + +test "a description that names the digest key is not a claimed digest" { + const absent = try writeFixture(.{ .digest = .absent, .description = "the file carries glp.content_sha256 in its description" }); + defer std.testing.allocator.free(absent); + var no_digest = try readOk(absent); + defer no_digest.deinit(); + try std.testing.expect(!no_digest.vector.claims_digest); + + const present = try writeFixture(.{ .description = "the file carries glp.content_sha256 in its description" }); + defer std.testing.allocator.free(present); + var digest = try readOk(present); + defer digest.deinit(); + try std.testing.expect(digest.vector.claims_digest); +} + +test "a digest key that is not text is refused" { + const bytes = try writeFixture(.{ .digest_not_text = true }); + defer std.testing.allocator.free(bytes); + try refused(bytes); + const why = try reason(bytes); + defer std.testing.allocator.free(why); + try std.testing.expect(std.mem.indexOf(u8, why, "glp.content_sha256 is not text") != null); +} + +test "version-1 vectors declaring dir_scales or layer_scales are refused" { + for ([_][]const u8{ "glp.dir_scales", "glp.layer_scales" }) |scale_key| { + const bytes = try writeFixture(.{ .extra_key = scale_key }); + defer std.testing.allocator.free(bytes); + try refused(bytes); + const why = try reason(bytes); + defer std.testing.allocator.free(why); + try std.testing.expect(std.mem.indexOf(u8, why, scale_key) != null); + } +} diff --git a/zig/src/families/qwen27/forward.zig b/zig/src/families/qwen27/forward.zig index aa8be799d05..a2cc42278a5 100644 --- a/zig/src/families/qwen27/forward.zig +++ b/zig/src/families/qwen27/forward.zig @@ -8,6 +8,7 @@ const Config = @import("config.zig").Config; pub const Ref = @import("projection.zig").Ref; const Frame = @import("gpu_frame.zig").Frame; const ane_mlp = @import("ane_mlp.zig"); +const norm_steer = @import("norm_steer_gpu.zig"); pub const Mixer = struct { ptr: *anyopaque, @@ -86,6 +87,8 @@ pub const Stages = struct { norm: ?wts.Tensor = null, /// Where the head writes its logits: the frame's, or the MTP head's own (the target's last row stays readable). logits: ?Ref = null, + /// Whether the target's control-vector plan applies at the block norms; the MTP head's own block sets this false. + steer: bool = true, /// The rows layer `index`'s post and the final norm run: the tail's on the last layer, else every row. fn rowsAt(s: *const Stages, index: usize) Span { const f = &s.model.frame; @@ -124,10 +127,17 @@ pub const Stages = struct { try @import("loop.zig").preMhc(&m.mhc.?, &m.kernels, m.config, index, layer, m.weights.mhc[m.config.exec_phys[index]], &s.hidden, &s.residual, &s.pending, f, s.rows, e, tap); return; } - try m.kernels.normShift(e, s.hidden, s.pending, wts.ref(layer.norm), f.get(.eps), f.get(.dims), s.residual, f.get(.input), f.get(.sums), h, s.rows, m.config.shift_norms); + // The direction for the block before this one rides along with the norm that adds that block's output. + const dir = if (s.pending != null) s.direction(index - 1) else null; + if (dir) |d| { + try norm_steer.encode(&m.kernels, d.plan, e, s.hidden, s.pending.?, wts.ref(layer.norm), f.get(.eps), f.get(.dims), s.residual, f.get(.input), f.get(.sums), d.buffer, h, s.rows); + } else { + try m.kernels.normShift(e, s.hidden, s.pending, wts.ref(layer.norm), f.get(.eps), f.get(.dims), s.residual, f.get(.input), f.get(.sums), h, s.rows, m.config.shift_norms); + } e.barrier(); if (s.pending != null) { std.mem.swap(Ref, &s.hidden, &s.residual); + // The residual now holds the output of the block before this one, which is layer `index - 1`. if (s.hooks.tap) |tap| try tap(s.hooks.ptr, e, index - 1, s.hidden, s.rows); if (stage_planes.on) try stage_planes.record(s.model.glue, e, .{ .block = index - 1 }, s.hidden, s.rows); } @@ -286,9 +296,16 @@ pub const Stages = struct { const h: u32 = @intCast(m.config.hidden); const t = s.rowsAt(m.config.layers - 1); const pending: ?Ref = if (s.pending) |p| t.at(p, h) else null; - try m.kernels.normShift(e, t.at(s.hidden, h), pending, wts.ref(s.norm orelse m.weights.norm), f.get(.eps), t.dims, t.at(s.residual, h), t.at(f.get(.input), h), t.sums(f.get(.sums)), h, t.n, m.config.shift_norms); + // The last block's output is layer `layers - 1`, and the direction for it rides along with the norm. + const dir = if (pending != null) s.direction(m.config.layers - 1) else null; + if (dir) |d| { + try norm_steer.encode(&m.kernels, d.plan, e, t.at(s.hidden, h), pending.?, wts.ref(s.norm orelse m.weights.norm), f.get(.eps), t.dims, t.at(s.residual, h), t.at(f.get(.input), h), t.sums(f.get(.sums)), d.buffer, h, t.n); + } else { + try m.kernels.normShift(e, t.at(s.hidden, h), pending, wts.ref(s.norm orelse m.weights.norm), f.get(.eps), t.dims, t.at(s.residual, h), t.at(f.get(.input), h), t.sums(f.get(.sums)), h, t.n, m.config.shift_norms); + } e.barrier(); std.mem.swap(Ref, &s.hidden, &s.residual); + // The residual now holds the output of the last block, which is layer `layers - 1`. if (s.hooks.tap) |tap| try tap(s.hooks.ptr, e, m.config.layers - 1, s.hidden, s.rows); if (stage_planes.on) { // the last block is the residual stream; final is the normed rows the head reads (f.input) @@ -323,6 +340,20 @@ pub const Stages = struct { } if (s.tail) |tail| try tail.encode(tail.ptr, e); } + + /// The direction that steers the layer whose residual just landed; none in force (or off) means nothing done. + pub fn direction(s: *const Stages, layer: usize) ?Direction { + if (!s.steer) return null; + const plan = s.model.steer orelse return null; + const buffer = plan.dir(@intCast(layer)) orelse return null; + return .{ .plan = plan, .buffer = buffer }; + } + + /// A direction on the device and the plan it belongs to, whose alpha it is added at. + pub const Direction = struct { + plan: *@import("steer.zig").Plan, + buffer: mtl.Buffer, + }; }; /// `e` is the caller's encoder, but seams reopen it: the final one is written back through the pointer, so commit it. diff --git a/zig/src/families/qwen27/model.zig b/zig/src/families/qwen27/model.zig index c8abf41b163..a9e97e01be3 100644 --- a/zig/src/families/qwen27/model.zig +++ b/zig/src/families/qwen27/model.zig @@ -9,6 +9,7 @@ const wts = @import("gpu_weights.zig"); const quant = @import("quant_gpu.zig"); const glue = @import("glue_gpu.zig"); const moe_gpu = @import("moe_gpu.zig"); +const steer = @import("steer.zig"); const Frame = @import("gpu_frame.zig").Frame; const ane_mlp = @import("ane_mlp.zig"); const idle_release = @import("idle_release.zig"); @@ -39,6 +40,8 @@ pub const Model = struct { ane: ?*ane_mlp.Share = null, /// A deferred share still needs the checkpoint mappings, until loadShare decides and closes them. share_pending: bool = false, + /// The control vector in force, when one was loaded at open; null: the model runs unsteered. + steer: ?*steer.Plan = null, /// widths.Widths.tag: 0 for a uniform 4-bit g64 checkpoint. widths_tag: u64 = 0, /// Opt-in prepared extents; checkpoint aliases and task/KV/MTP/ANE storage are intentionally excluded. @@ -194,6 +197,7 @@ pub const Model = struct { errdefer m.frame.deinit(); allocation.end(); m.ane = null; + m.steer = null; m.share_pending = true; if (!later) try m.finishShare(null, share_fits); return m; @@ -257,6 +261,7 @@ pub const Model = struct { } pub fn deinit(m: *Model) void { + if (m.steer) |plan| plan.deinit(); if (m.metal4) |q| q.deinit(); if (m.ane) |share| share.deinit(); m.frame.deinit(); diff --git a/zig/src/families/qwen27/mtp.zig b/zig/src/families/qwen27/mtp.zig index d8b7125dc51..3d82d591ad0 100644 --- a/zig/src/families/qwen27/mtp.zig +++ b/zig/src/families/qwen27/mtp.zig @@ -46,6 +46,20 @@ pub fn pick(values: []const u16) !Pick { return .{ .token = token, .chance = @floatCast(1 / sum) }; } +/// The head's stages: its own final norm and logits rows over `config.layers`, and no target steering plan. +pub fn headStages( + m: *Model, + rows: u32, + hooks: forward.Mixer, + head: forward.Head, + norm: ?wts.Tensor, + logits: Ref, + hidden: Ref, + residual: Ref, +) forward.Stages { + return .{ .model = m, .rows = rows, .hooks = hooks, .head = head, .norm = norm, .logits = logits, .hidden = hidden, .residual = residual, .steer = false }; +} + /// One head pass over `rows` frame rows (ids and positions set): `hidden` row i beside token i; returns normed rows. pub fn encode(m: *Model, sc: *const Scratch, e: *mtl.ComputeEncoder, hooks: forward.Mixer, hidden: Ref, rows: u32, head: forward.Head) !Ref { const w = m.weights.mtp orelse return error.NoMtpHead; @@ -64,7 +78,7 @@ pub fn encode(m: *Model, sc: *const Scratch, e: *mtl.ComputeEncoder, hooks: forw e.barrier(); var lane = @import("core").segments.Lane{ .k = 0, .cb = undefined, .enc = e.*, .fence = undefined }; defer e.* = lane.enc; - var s = forward.Stages{ .model = m, .rows = rows, .hooks = hooks, .head = head, .norm = w.norm, .logits = .{ .buffer = sc.logits }, .hidden = f.get(.hidden), .residual = f.get(.residual) }; + var s = headStages(m, rows, hooks, head, w.norm, .{ .buffer = sc.logits }, f.get(.hidden), f.get(.residual)); const block = m.config.layers; try s.pre(&lane, block); try s.mixer(&lane, block); diff --git a/zig/src/families/qwen27/norm_steer_gpu.zig b/zig/src/families/qwen27/norm_steer_gpu.zig new file mode 100644 index 00000000000..f968fe90159 --- /dev/null +++ b/zig/src/families/qwen27/norm_steer_gpu.zig @@ -0,0 +1,46 @@ +//! The steered norm on the GPU: the residual norm with a control vector's direction added inside it. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("qwen_runtime_sources"); +const profile = @import("core").gpu_profile; +const quant = @import("quant_gpu.zig"); +const steer = @import("steer.zig"); +const Ref = quant.Ref; + +pub const symbol = "custom_kernel_q27_norm_steer_bfloat16_t_bfloat16_t_bfloat16_t_floatc_int32_t_bfloat16_t_bfloat16_t_float_float_float"; + +/// The steered norm's source for a `width`-wide row, specialised as the plain norms are. +pub fn source(a: std.mem.Allocator, width: u32) ![]u8 { + const template = sources.norm_steer; + const mark = std.mem.indexOf(u8, template, "Q27_SPECIALIZE") orelse return error.BadKernelSource; + const definitions = try std.fmt.allocPrint(a, "constexpr int K={d};", .{width}); + defer a.free(definitions); + return std.mem.concat(a, u8, &.{ "#define Q27_XS 64\n", template[0..mark], definitions, template[mark + "Q27_SPECIALIZE".len ..] }); +} + +/// The plan's pipeline, compiled at its first dispatch: the plan's rows are all `width` wide. +fn pipeline(k: *quant.Kernels, plan: *steer.Plan, width: u32) !mtl.Pipeline { + if (plan.pipeline) |p| return p; + const text = try source(k.allocator, width); + defer k.allocator.free(text); + const library = try mtl.Library.fromSource(k.device, text, mtl.CompileOptions.mlx()); + defer library.deinit(); + plan.pipeline = try mtl.Pipeline.init(k.device, library, symbol, false); + return plan.pipeline.?; +} + +/// The norm with a direction inside it: alpha times the direction is added before the normalisation reads the row. +pub fn encode(k: *quant.Kernels, plan: *steer.Plan, input_encoder: mtl.ComputeEncoder, h: Ref, residual: Ref, weight: Ref, eps: Ref, dims: Ref, combined: Ref, out: Ref, xs: Ref, dir: mtl.Buffer, width: u32, rows: u32) !void { + var span = profile.begin(k.profiler, input_encoder, .norm); + errdefer span.cancel(); + const e = span.encoder; + + e.setPipeline(try pipeline(k, plan, width)); + inline for (.{ h, residual, weight, eps, dims, combined, out, xs }, 0..) |r, i| e.setBuffer(r.buffer, r.offset, i); + e.setBuffer(dir, 0, 8); + e.setValue(plan.alpha, 9); + e.dispatchGroups(mtl.Size.of(1, quant.padded(rows), 1), mtl.Size.of(width / 16, 1, 1)); + // The steered output has no tf_sq_fits words: the last plain norm's must not outlive it. + k.fits = null; + try span.end(); +} diff --git a/zig/src/families/qwen27/qwen27.zig b/zig/src/families/qwen27/qwen27.zig index 3630f5033c7..85f19790acb 100644 --- a/zig/src/families/qwen27/qwen27.zig +++ b/zig/src/families/qwen27/qwen27.zig @@ -47,6 +47,8 @@ pub const ane_mlp = @import("ane_mlp.zig"); pub const round_plan = @import("round_plan.zig"); pub const state = @import("state.zig"); pub const session = @import("session.zig"); +pub const steer = @import("steer.zig"); +pub const norm_steer_gpu = @import("norm_steer_gpu.zig"); pub const snapshot = @import("snapshot.zig"); pub const disk = @import("disk.zig"); pub const taps = @import("taps.zig"); @@ -67,6 +69,7 @@ test { _ = @import("core").qwen35_stages; _ = stage_planes; _ = session; + _ = steer; _ = @import("gdn_test.zig"); _ = @import("simd_attention.zig"); _ = glue; diff --git a/zig/src/families/qwen27/steer.zig b/zig/src/families/qwen27/steer.zig new file mode 100644 index 00000000000..7ddb1c6939a --- /dev/null +++ b/zig/src/families/qwen27/steer.zig @@ -0,0 +1,77 @@ +//! A control vector's directions on the device: the layer each one steers and the strength it takes. +const std = @import("std"); +const mtl = @import("metal"); + +/// One layer's direction: its layer id and the vector to add. +pub const Layer = struct { id: u32, dir: []const f32 }; + +/// What the plan is built from: the vector's directions and the model they steer. +pub const Source = struct { + alpha: f32, + hidden: u32, + layers_total: u32, + layers: []const Layer, +}; + +/// The vector in force: one direction a device buffer, and the lookup that finds a layer's. +pub const Plan = struct { + allocator: std.mem.Allocator, + alpha: f32, + hidden: u32, + ids: []u32, + dirs: []mtl.Buffer, + cover: []?usize, + /// The steered norm's pipeline, compiled at its first dispatch. + pipeline: ?mtl.Pipeline = null, + + /// The direction that steers `layer`; null when the vector does not cover it. + pub fn dir(p: *const Plan, layer: u32) ?mtl.Buffer { + if (layer >= p.cover.len) return null; + const index = p.cover[layer] orelse return null; + return p.dirs[index]; + } + + /// The layers the vector covers, ascending. + pub fn covered(p: *const Plan) []const u32 { + return p.ids; + } + + pub fn deinit(p: *Plan) void { + if (p.pipeline) |q| q.deinit(); + for (p.dirs) |d| d.deinit(); + p.allocator.free(p.dirs); + p.allocator.free(p.ids); + p.allocator.free(p.cover); + p.allocator.destroy(p); + } +}; + +/// The plan for a vector: every direction on the device and the lookup that maps a layer to it. +pub fn init(allocator: std.mem.Allocator, device: mtl.Device, src: Source) !*Plan { + if (src.hidden == 0 or src.layers_total == 0 or src.layers.len == 0) return error.BadSteerShape; + for (src.layers) |l| { + // The blocks are zero to `layers_total - 1`, and the format carries no direction for layer 0. + if (l.id == 0 or l.id >= src.layers_total) return error.BadSteerLayer; + if (l.dir.len != src.hidden) return error.BadSteerWidth; + } + const plan = try allocator.create(Plan); + errdefer allocator.destroy(plan); + const ids = try allocator.alloc(u32, src.layers.len); + errdefer allocator.free(ids); + const dirs = try allocator.alloc(mtl.Buffer, src.layers.len); + errdefer allocator.free(dirs); + var live: usize = 0; + errdefer for (dirs[0..live]) |d| d.deinit(); + const cover = try allocator.alloc(?usize, src.layers_total); + errdefer allocator.free(cover); + @memset(cover, null); + for (src.layers, 0..) |l, i| { + dirs[i] = try device.buffer(@as(usize, src.hidden) * 4, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + live += 1; + @memcpy(dirs[i].slice(f32, src.hidden), l.dir); + ids[i] = l.id; + cover[l.id] = i; + } + plan.* = .{ .allocator = allocator, .alpha = src.alpha, .hidden = src.hidden, .ids = ids, .dirs = dirs, .cover = cover }; + return plan; +} diff --git a/zig/src/families/qwen27/steer_test.zig b/zig/src/families/qwen27/steer_test.zig new file mode 100644 index 00000000000..cf5adac2748 --- /dev/null +++ b/zig/src/families/qwen27/steer_test.zig @@ -0,0 +1,73 @@ +//! The control vector's plan on the host: the layer lookup and the directions a device holds. +const std = @import("std"); +const mtl = @import("metal"); +const steer = @import("steer.zig"); + +/// The recording device the host tests use: the buffers live in host memory, no GPU runs. +fn device(allocations: *mtl.Allocations) mtl.Device { + return .{ .allocations = allocations }; +} + +test "the plan holds a direction for every layer the vector names and none for the rest" { + var allocations: mtl.Allocations = .{}; + const dir = [_]f32{ 1, 0, 0, 0 }; + const plan = try steer.init(std.testing.allocator, device(&allocations), .{ + .alpha = 0.5, + .hidden = 4, + .layers_total = 8, + .layers = &.{ .{ .id = 3, .dir = &dir }, .{ .id = 5, .dir = &dir } }, + }); + defer plan.deinit(); + try std.testing.expect(plan.dir(3) != null); + try std.testing.expect(plan.dir(5) != null); + try std.testing.expect(plan.dir(4) == null); + try std.testing.expect(plan.dir(0) == null); + try std.testing.expect(plan.dir(8) == null); + try std.testing.expectEqualSlices(u32, &.{ 3, 5 }, plan.covered()); + try std.testing.expectEqualSlices(f32, &dir, plan.dir(3).?.slice(f32, 4)); + try std.testing.expectEqual(@as(f32, 0.5), plan.alpha); +} + +test "a vector that names a layer the model does not have is refused before any buffer is made" { + var allocations: mtl.Allocations = .{}; + const dir = [_]f32{ 1, 0, 0, 0 }; + // The blocks are zero to `layers_total - 1`, so the last one is the model's last layer. + try std.testing.expectError(error.BadSteerLayer, steer.init(std.testing.allocator, device(&allocations), .{ + .alpha = 1, + .hidden = 4, + .layers_total = 4, + .layers = &.{.{ .id = 4, .dir = &dir }}, + })); + try std.testing.expectError(error.BadSteerLayer, steer.init(std.testing.allocator, device(&allocations), .{ + .alpha = 1, + .hidden = 4, + .layers_total = 4, + .layers = &.{.{ .id = 0, .dir = &dir }}, + })); + try std.testing.expectEqual(@as(usize, 0), allocations.calls); +} + +test "a vector that names the model's last layer is taken" { + var allocations: mtl.Allocations = .{}; + const dir = [_]f32{ 1, 0, 0, 0 }; + const plan = try steer.init(std.testing.allocator, device(&allocations), .{ + .alpha = 1, + .hidden = 4, + .layers_total = 4, + .layers = &.{.{ .id = 3, .dir = &dir }}, + }); + defer plan.deinit(); + try std.testing.expect(plan.dir(3) != null); +} + +test "a direction that is not as wide as the model is refused" { + var allocations: mtl.Allocations = .{}; + const dir = [_]f32{ 1, 0 }; + try std.testing.expectError(error.BadSteerWidth, steer.init(std.testing.allocator, device(&allocations), .{ + .alpha = 1, + .hidden = 4, + .layers_total = 4, + .layers = &.{.{ .id = 1, .dir = &dir }}, + })); + try std.testing.expectEqual(@as(usize, 0), allocations.calls); +} diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index 204089bdd17..d2912021d95 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -353,7 +353,7 @@ fn openQwen27(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[ const learn: ?@import("qwen27_disk.zig").Learn = if (o.learn_conversations) if (o.learn) |root| .{ .root = root, .dir = o.dir, .drafter = drafter, .cap = gibBytes(o.learn_gib), .floor = gibBytes(o.learn_min_free_gib), .daily = gibBytes(o.learn_daily_gib), .spill = o.spill, .slots = spill.slots(o) } else null else null; const witness = try q27_witness.begin(gpa, io, o); // before the load: stamps, and the libraries it builds defer q27_witness.release(witness); - const h = qwen27.open(gpa, io, o.dir, .{ .context = @intCast(context), .streams = o.lanes, .streams_fixed = o.lanes_fixed, .drafts = if (sn) o.drafts else true, .drafter = drafter, .drafter_name = o.drafter_name, .drafter_bits = o.drafter_bits, .mtp_drafts = if (o.drafts) o.mtp_drafts else null, .mtp_confidence = o.mtp_confidence, .cache_gib = o.prompt_cache_gib, .cache_over_cap = o.prompt_cache_over_cap, .decode_share = o.decode_share, .learn = learn, .vision = o.vision, .rope_yarn = if (sn) o.rope_yarn else null, .slide = o.slide }, a, &why) catch |err| { + const h = qwen27.open(gpa, io, o.dir, .{ .context = @intCast(context), .streams = o.lanes, .streams_fixed = o.lanes_fixed, .drafts = if (sn) o.drafts else true, .drafter = drafter, .drafter_name = o.drafter_name, .drafter_bits = o.drafter_bits, .mtp_drafts = if (o.drafts) o.mtp_drafts else null, .mtp_confidence = o.mtp_confidence, .cache_gib = o.prompt_cache_gib, .cache_over_cap = o.prompt_cache_over_cap, .decode_share = o.decode_share, .glp = o.glp, .learn = learn, .vision = o.vision, .rope_yarn = if (sn) o.rope_yarn else null, .slide = o.slide }, a, &why) catch |err| { problem.* = if (why.len > 0) why else try std.fmt.allocPrint(a, "the native {s} engine cannot load {s} ({s})", .{ if (sn) "SenseNova" else "Qwen (27B class)", o.dir, @errorName(err) }); return null; }; diff --git a/zig/src/native/qwen27_disk.zig b/zig/src/native/qwen27_disk.zig index fa1d6fd6c04..e271697ba45 100644 --- a/zig/src/native/qwen27_disk.zig +++ b/zig/src/native/qwen27_disk.zig @@ -78,8 +78,8 @@ fn scatter(_: *anyopaque, saved: api.prompt_cache.Saved, ranges: []const rows.im } } -/// What disk states are read under, and the probe's prompt rate: the checkpoint, the drafter, sources, modes, bits. -pub fn identity(h: *Host, io: std.Io, a: Allocator, dir: []const u8, drafter: ?[]const u8) !struct { id: u64, rate: f64 } { +/// The checkpoint, drafter, code, policies and loaded control vector that computed a disk state, plus the probe rate. +pub fn identity(h: *Host, io: std.Io, a: Allocator, dir: []const u8, drafter: ?[]const u8, steering: ?*const api.glp.Glp) !struct { id: u64, rate: f64 } { var w = std.hash.Wyhash.init(0x7132); try @import("sys").file_identity.current(&w, a, io); try disk_identity.checkpoint(&w, a, io, dir); @@ -90,7 +90,8 @@ pub fn identity(h: *Host, io: std.Io, a: Allocator, dir: []const u8, drafter: ?[ @import("qwen27_mtp_flags.zig").identityWords(&w, &words, h.mtp != null); disk_identity.machine(&w, std.mem.span(h.model.device.name())); disk_identity.profile(&w, .{ .family = if (h.model.config.looped) "sensenova_loop" else if (h.model.config.moe()) "qwen3_5_moe" else "qwen3_5", .backend = "metal" }); - return .{ .id = withPolicy(w.final(), h), .rate = p.rate }; + const base = withPolicy(w.final(), h); + return .{ .id = if (steering) |g| withSteering(base, &g.vector.file_sha256, g.alpha) else base, .rate = p.rate }; } /// A fixed prompt's state through slot 0 (whole 128-row chunks, a decoded span, a short tail), hashed, and its rate. @@ -132,9 +133,9 @@ fn probe(h: *Host, io: std.Io) !struct { hash: u64, rate: f64 } { } /// The store for --learn-conversations under `root`, attached to the cache; the probe seeds its prompt rate. -pub fn attach(h: *Host, io: std.Io, a: Allocator, o: Learn) !void { +pub fn attach(h: *Host, io: std.Io, a: Allocator, o: Learn, steering: ?*const api.glp.Glp) !void { const store = &(h.cache orelse return std.log.warn("Qwen3.8-27B: --learn-conversations needs the prompt cache, which --prompt-cache-gib 0 turned off", .{})); - const id = try identity(h, io, a, o.dir, o.drafter); + const id = try identity(h, io, a, o.dir, o.drafter, steering); const r = try rows.attach(h.gpa, store, .{ .root = o.root, .identity = id.id, .cap = o.cap, .floor = o.floor, .daily = o.daily, .lookahead = store.rules.lookahead, .planned = store.rules.planned, .spill = o.spill, .slots = o.slots, .longest = h.host.info_.context_window }); r.prefill_rate = id.rate; std.log.info("Qwen3.8-27B: conversation states on disk in {s} ({d} states, {d} MiB of {d} MiB)", .{ r.dir, r.states.items.len, r.held() >> 20, o.cap >> 20 }); @@ -150,3 +151,12 @@ pub fn withPolicy(legacy: u64, h: anytype) u64 { h.back.chunk, // not frame.capacity: it only sizes buffers and bounds a pass's rows }); } + +/// A changed vector file or applied strength cannot reuse conversation states, even if the probe rounds alike. +pub fn withSteering(base: u64, file_sha256: *const [32]u8, alpha: f32) u64 { + var hash = std.hash.Wyhash.init(base); + hash.update("qwen-metal-glp-add-v1"); + hash.update(file_sha256); + hash.update(std.mem.asBytes(&alpha)); + return hash.final(); +} diff --git a/zig/src/native/qwen27_mtp.zig b/zig/src/native/qwen27_mtp.zig index 1426def0000..86281600a41 100644 --- a/zig/src/native/qwen27_mtp.zig +++ b/zig/src/native/qwen27_mtp.zig @@ -419,3 +419,21 @@ pub const Mtp = struct { return .{ .buffer = x.stage }; } }; + +test "qwen27 MTP: its own block does not reapply the target's last-layer direction" { + // A control vector that covers the target's last block (63 of 64), as the format allows. + var dirs = [_]mtl.Buffer{.{ .id = @ptrFromInt(0x5150) }}; + var ids = [_]u32{63}; + var cover: [64]?usize = @splat(null); + cover[63] = 0; + var plan = q.steer.Plan{ .allocator = std.testing.allocator, .alpha = 0.5, .hidden = 1, .ids = &ids, .dirs = &dirs, .cover = &cover }; + var m: q.model.Model = undefined; + m.steer = &plan; + const fake = Ref{ .buffer = .{ .id = @ptrFromInt(0x5160) } }; + const s = q.mtp.headStages(&m, 1, undefined, .all, null, fake, fake, fake); + // The target's own stages read the direction; the head's must not, or layer 63 is added twice. + var target = s; + target.steer = true; + try std.testing.expect(target.direction(63) != null); + try std.testing.expect(s.direction(63) == null); +} diff --git a/zig/src/native/qwen27_mtp_flags.zig b/zig/src/native/qwen27_mtp_flags.zig index 353e2cb0d91..e996bb9d7d3 100644 --- a/zig/src/native/qwen27_mtp_flags.zig +++ b/zig/src/native/qwen27_mtp_flags.zig @@ -24,6 +24,12 @@ pub fn deviceRefusal(drafts: ?u32, tensor_units: bool, pages: bool) ?Refused { } pub const Refused = struct { err: anyerror, why: []const u8 }; +/// Why --drafter is refused before the target or the drafter loads. +pub fn drafterRefusal(a: std.mem.Allocator, dir: []const u8, drafter: []const u8, err: anyerror) ![]const u8 { + if (err == error.DraftForAnotherTarget) return std.fmt.allocPrint(a, "--drafter {s} drafts for another target: its width, vocabulary or tapped layers do not fit {s} (DraftForAnotherTarget)", .{ drafter, dir }); + return std.fmt.allocPrint(a, "--drafter {s} is not a drafter the native Qwen engine serves for {s} ({s}): it takes z-lab/Qwen3.8-27B-DFlash2 as released, for Qwen3.8-27B", .{ drafter, dir, @errorName(err) }); +} + /// Hashes the disk identity's mode words; the head's word joins only when it is on, as main keys the rest. pub fn identityWords(w: *std.hash.Wyhash, words: []const u64, head: bool) void { w.update(std.mem.sliceAsBytes(words)); diff --git a/zig/src/native/qwen27_served.zig b/zig/src/native/qwen27_served.zig index 6b1b7ea0704..f6ba932911a 100644 --- a/zig/src/native/qwen27_served.zig +++ b/zig/src/native/qwen27_served.zig @@ -19,6 +19,7 @@ const reserve = @import("qwen27_reserve.zig"); const StartupLine = startup.StartupLine; const disk = @import("qwen27_disk.zig"); const images = @import("qwen27_images.zig"); +const steer_served = @import("qwen27_steer_served.zig"); const Mtp = @import("qwen27_mtp.zig").Mtp; const Allocator = std.mem.Allocator; const helpers = @import("qwen27_served_helpers.zig"); @@ -47,6 +48,7 @@ pub const Options = struct { vision: ?api.VisionOpen = null, // --vision: open loads the image tower, and requests may hold images images: ?*images.Vision = null, // the loaded tower attach serves (and the host then owns) rope_yarn: ?f64 = null, + glp: ?api.glp.Glp = null, // the control vector the model steers with (null: none) slide: bool = false, // --slide: Folded Memory Weights v3 live learning dir: []const u8 = "", // checkpoint directory for living-weights.safetensors }; @@ -248,7 +250,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, o: Options, a: Allocato const pool = mtl.objc.Pool.push(); defer pool.pop(); if (o.drafter) |d| _ = q.dflash.config.admit(gpa, io, dir, d) catch |err| { - why.* = try drafterRefusal(a, dir, d, err); + why.* = try @import("qwen27_mtp_flags.zig").drafterRefusal(a, dir, d, err); return err; }; const model = q.model.Model.loadDeferredOpts(gpa, io, dir, reserve.loaded_rows, .{ .rope_yarn = o.rope_yarn }) catch |err| { @@ -258,6 +260,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, o: Options, a: Allocato return err; }; errdefer model.deinit(); + if (o.glp) |g| try steer_served.apply(gpa, model, dir, g, a, why); if (@import("qwen27_mtp_flags.zig").deviceRefusal(o.mtp_drafts, model.device.tensorUnits(), try q.decode_round.pagesOn())) |r| { why.* = r.why; return r.err; @@ -433,7 +436,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q if (slot_state.rewindInit(h.back, rewind_room, if (o.cache_gib) |g| gibBytes(g) else cache_fit.defaultBudget(rewind_room))) |buf| if (h.resident) |*r| r.addNow(&.{buf}); try enableCache(h, o.cache_gib, o.cache_over_cap, a, why); errdefer if (h.cache) |*store| store.deinit(); - if (o.learn) |l| try disk.attach(h, io, a, l); + if (o.learn) |l| try disk.attach(h, io, a, l, if (o.glp) |*g| g else null); errdefer if (h.cache) |*store| if (store.disk) |r| r.deinit(); // a wide prompt pass commits its buffers at once: the probe keeps the sets in use while it runs h.host.keepalive_target = .{ .ctx = &h.warm, .tick = mtl.keepalive.Target.tick, .probe = mtl.keepalive.Target.busy }; @@ -452,6 +455,7 @@ pub fn attach(parent: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q try h.host.start(); tf.startup_receipt.span(.model_ready).end(); std.log.info("{f}", .{StartupLine{ .streams = slots, .context = capacity, .draft_slots = if (h.draft != null) h.back.draft_slots else if (h.sn_mtp != null) slots else 0, .drafter = if (h.draft) |d| d.model.graph.config.kind() else "DFlash2", .images = o.images != null }}); + if (o.glp) |g| if (model.steer != null) steer_served.report(g); return h; } @@ -528,6 +532,7 @@ test { if (builtin.os.tag == .macos) { _ = @import("qwen27_served_startup_test.zig"); _ = @import("qwen27_draft_block.zig"); + _ = @import("qwen27_mtp.zig"); _ = @import("qwen27_share_fit.zig"); _ = @import("qwen27_served_test.zig"); _ = @import("qwen27_startup_test.zig"); diff --git a/zig/src/native/qwen27_steer_served.zig b/zig/src/native/qwen27_steer_served.zig new file mode 100644 index 00000000000..cea511c8462 --- /dev/null +++ b/zig/src/native/qwen27_steer_served.zig @@ -0,0 +1,112 @@ +//! The control vector a served Qwen3.8-27B takes: its fit, its plan on the device and the line that reports it. +const std = @import("std"); +const api = @import("engine_api"); +const q = @import("tensorfold").qwen27; +const Allocator = std.mem.Allocator; + +/// Check whether a control vector matches the Qwen3.8-27B model's geometry, repo, and snapshot revision. +pub fn checkFit(vector: api.glp.Vector, hidden: usize, dir: []const u8, a: Allocator, reason: *api.glp.Why) !void { + const src = cachedSource(a, dir); + try api.glp.checkModel(vector, hidden, src.repo, reason); + try api.glp.checkRevision(vector, src.repo, src.revision, reason); +} + +/// Check the vector against the model that loaded, then put its directions on the device. +pub fn apply(gpa: Allocator, model: *q.model.Model, dir: []const u8, g: api.glp.Glp, a: Allocator, why: *[]const u8) !void { + // The steered norm has neither the looped model's mHC blocks nor its shifted gains. + if (model.config.looped or model.config.shift_norms) { + why.* = try std.fmt.allocPrint(a, "the control vector cannot steer {s}: SenseNova models take no control vector", .{dir}); + return error.SteeringUnsupported; + } + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + var reason: api.glp.Why = .{}; + checkFit(g.vector, model.config.hidden, dir, arena.allocator(), &reason) catch |err| { + why.* = try std.fmt.allocPrint(a, "the control vector does not fit {s}: {s}", .{ dir, reason.text() }); + return err; + }; + const layers = try gpa.alloc(q.steer.Layer, g.vector.layers.len); + defer gpa.free(layers); + for (g.vector.layers, 0..) |l, i| layers[i] = .{ .id = l.id, .dir = l.dir }; + model.steer = q.steer.init(gpa, model.device, .{ + .alpha = g.alpha, + .hidden = @intCast(model.config.hidden), + .layers_total = @intCast(model.config.layers), + .layers = layers, + }) catch |err| { + why.* = try std.fmt.allocPrint(a, "the control vector does not fit {s}: {s}", .{ dir, steerProblem(err) }); + return err; + }; +} + +/// The line that reports the control vector this model steers with. +pub fn report(g: api.glp.Glp) void { + const v = g.vector; + const file_sha = std.fmt.bytesToHex(v.file_sha256, .lower); + var first: u32 = 0; + var last: u32 = 0; + for (v.layers, 0..) |l, i| { + if (i == 0) first = l.id; + last = l.id; + } + var base: [320]u8 = undefined; + std.log.info("Qwen3.8-27B: control vector in force, replies are steered: alpha {d:.3}, {d} layers ({d}-{d}), base {s}, file sha256 {s}", .{ + g.alpha, + v.layers.len, + first, + last, + api.glp.baseLine(v, base[0..]), + file_sha[0..], + }); + if (v.transferred) std.log.warn("Qwen3.8-27B: the control vector was derived at {f}, not at {f}: it is applied at the residual stream", .{ std.zig.fmtString(v.derived_at), std.zig.fmtString(v.hook_point) }); +} + +/// The repo id and revision a cached checkpoint came from; empty strings when not a cache snapshot. +fn cachedSource(a: Allocator, dir: []const u8) struct { repo: []const u8, revision: []const u8 } { + const at = std.mem.lastIndexOf(u8, dir, "models--") orelse return .{ .repo = "", .revision = "" }; + const rest = dir[at + "models--".len ..]; + const sep = std.mem.indexOf(u8, rest, "/snapshots/") orelse return .{ .repo = "", .revision = "" }; + const owner = rest[0..sep]; + const dash = std.mem.indexOf(u8, owner, "--") orelse return .{ .repo = "", .revision = "" }; + const tail = rest[sep + "/snapshots/".len ..]; + const rev = tail[0 .. std.mem.indexOfScalar(u8, tail, '/') orelse tail.len]; + const repo = std.fmt.allocPrint(a, "{s}/{s}", .{ owner[0..dash], owner[dash + 2 ..] }) catch ""; + return .{ .repo = repo, .revision = if (repo.len > 0) rev else "" }; +} + +/// Why a vector's directions cannot be prepared, as the operator reads it. +fn steerProblem(err: anyerror) []const u8 { + return switch (err) { + error.BadSteerLayer => "it names a layer this model does not have", + error.BadSteerWidth => "its directions are not as wide as this model", + error.BadSteerShape => "it holds no direction", + else => "its directions cannot be prepared", + }; +} + +test "checkFit rejects a mismatched snapshot revision on the same Qwen repo while keeping conversions" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const dir = [_]f32{ 1, 0, 0, 0, 0, 0, 0, 0 }; + const vector: api.glp.Vector = .{ + .alpha = 1, + .hook_point = api.glp.residual_site, + .derived_at = api.glp.residual_site, + .base_model = "Qwen/Qwen3.8-27B", + .base_revision = "aaaa1111bbbb", + .method = "", + .contrast = "", + .width = 8, + .layers = &.{.{ .id = 1, .dir = &dir }}, + .sha256 = @splat(0), + .claims_digest = false, + .file_sha256 = @splat(0), + .transferred = false, + }; + var why: api.glp.Why = .{}; + try checkFit(vector, 8, "/cache/models--Qwen--Qwen3.8-27B/snapshots/aaaa1111bbbb", a, &why); + try checkFit(vector, 8, "/cache/models--mlx-community--Qwen3.8-27B-4bit/snapshots/cccc2222dddd", a, &why); + try std.testing.expectError(error.BadGlpVector, checkFit(vector, 8, "/cache/models--Qwen--Qwen3.8-27B/snapshots/cccc2222dddd", a, &why)); + try std.testing.expect(std.mem.indexOf(u8, why.text(), "revision") != null); +} diff --git a/zig/src/server/cli.zig b/zig/src/server/cli.zig index a4089b6fddb..2efc28bad63 100644 --- a/zig/src/server/cli.zig +++ b/zig/src/server/cli.zig @@ -2,22 +2,12 @@ const std = @import("std"); const builtin = @import("builtin"); const api = @import("engine_api"); +const glp_startup = @import("glp_startup.zig"); const Allocator = std.mem.Allocator; -pub const Kind = enum { - value, // --flag VALUE or --flag=VALUE - store_true, // --flag - append, // repeatable --flag VALUE -}; -pub const Flag = struct { - name: []const u8, - kind: Kind = .value, - choices: []const []const u8 = &.{}, // argparse's choices; empty: any value of the flag's type. - /// This binary honours the flag (and lists it in ``capabilities``); the rest are refused as unsupported. - native: bool = false, - native_values: ?[]const []const u8 = null, // The values it honours when only some of the choices. - /// The value names a file or folder: a config file's relative one is read from that file's folder (cli_config.zig). - path: bool = false, -}; +/// The serve flag table and its sub-tables (glp_startup.zig) concatenate, so there is one shape only. +const cli_flag = @import("cli_flag.zig"); +pub const Kind = cli_flag.Kind; +pub const Flag = cli_flag.Flag; const backend_values: []const []const u8 = if (builtin.os.tag == .macos) &.{ "auto", "mlx" } else if (served("--backend=vulkan")) &.{ "auto", "vulkan" } else if (served("--backend=rocm")) &.{ "auto", "rocm" } else &.{ "auto", "cuda" }; /// The flags past the common ones the binary's backend serves, from its root's `serves` (test roots: none). const native_serves: []const []const u8 = if (@hasDecl(@import("root"), "serves")) @import("root").serves else &.{}; @@ -49,7 +39,7 @@ pub const flags = [_]Flag{ .{ .name = "--chat-template", .path = true, .native = true }, .{ .name = "--voices", .path = true, .native = true }, .{ .name = "--default-voice", .native = true }, -} ++ @import("drama_cfg.zig").flags ++ @import("admission_cli.zig").flags ++ @import("connection_cli.zig").flags ++ @import("voice_cli.zig").flags ++ @import("speech_cli.zig").flags ++ [_]Flag{ +} ++ @import("drama_cfg.zig").flags ++ @import("admission_cli.zig").flags ++ @import("connection_cli.zig").flags ++ @import("voice_cli.zig").flags ++ @import("speech_cli.zig").flags ++ glp_startup.flags ++ [_]Flag{ .{ .name = "--alias", .kind = .append, .native = true }, .{ .name = "--name-priority", .kind = .append, .native = true }, .{ .name = "--api-key", .kind = .append, .native = true }, @@ -254,6 +244,7 @@ pub fn parse(a: Allocator, argv: []const []const u8, u: *Usage) error{ Usage, Ou var env_buf: [192]u8 = undefined; if (!out.confidential) if (api.prefill_env.problem(&env_buf)) |why| return fail(u, a, "{s}", .{why}); try spillWith(u, a, out); + if (try glp_startup.read(a, &out.glp)) |why| return fail(u, a, "{s}", .{why}); return out; } @@ -419,7 +410,7 @@ fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usa out.redraw.budget_s = try float(u, a, name, v); } else if (is(name, "--short-reply-ratio")) out.redraw.short_ratio = try float(u, a, name, v) else if (is(name, "--short-reply-chars-per-s")) out.redraw.short_chars_per_s = try float(u, a, name, v) else if (is(name, "--silence-redraw-controls")) { out.redraw.controls = @import("drama_allow.zig").parse(v) catch return fail(u, a, "argument --silence-redraw-controls: expected comma-separated UTF-8 names without square brackets, or an empty list: '{s}'", .{v}); - } else if (is(name, "--register-redraw-st")) out.redraw.register.st = try float(u, a, name, v) else if (is(name, "--register-redraw-high")) out.redraw.register.high = try float(u, a, name, v) else if (is(name, "--register-high-hz")) out.redraw.register.high_hz = try float(u, a, name, v); + } else if (is(name, "--register-redraw-st")) out.redraw.register.st = try float(u, a, name, v) else if (is(name, "--register-redraw-high")) out.redraw.register.high = try float(u, a, name, v) else if (is(name, "--register-high-hz")) out.redraw.register.high_hz = try float(u, a, name, v) else if (is(name, "--glp")) out.glp = glp_startup.withPath(out.glp, v) else if (is(name, "--glp-alpha")) out.glp = glp_startup.withAlpha(out.glp, glp_startup.strength(v) orelse return fail(u, a, "argument --glp-alpha: expected a finite strength above 0: '{s}'", .{v})); } pub const parallel = @import("cli_parallel.zig").parallel; @@ -438,6 +429,7 @@ pub fn request(a: Allocator, dir: []const u8, model_type: []const u8, args: Args .drafter = args.drafter, .drafter_name = args.drafter_name orelse args.drafter, .drafter_bits = args.drafter_bits, + .glp = try glp_startup.engine(a, dir, model_type, args.backend, args.glp), .rope_yarn = args.rope_yarn, .record = args.record, .kv8 = std.mem.eql(u8, args.kv_cache, "fp8"), diff --git a/zig/src/server/cli_args.zig b/zig/src/server/cli_args.zig index dacc228e969..f31fb952df8 100644 --- a/zig/src/server/cli_args.zig +++ b/zig/src/server/cli_args.zig @@ -117,4 +117,5 @@ pub const Args = struct { vision_image_tokens_set: bool = false, // --vision-image-tokens given: a family's own default no longer applies vision_image_share: api.ImageShare = .request, // --vision-image-share: the request's own count, or the fixed share vision_video_tokens: u32 = 16384, // the visual tokens a request's videos share (the processor's max_image_tokens) + glp: ?@import("glp_startup.zig").Vec = null, // --glp: the control vector file and the strength in force }; diff --git a/zig/src/server/cli_capabilities.zig b/zig/src/server/cli_capabilities.zig index 83c1c3bd870..de9fcfddd65 100644 --- a/zig/src/server/cli_capabilities.zig +++ b/zig/src/server/cli_capabilities.zig @@ -19,6 +19,11 @@ pub const Engines = struct { /// Native flags and selected supported variables; env is non-exhaustive, profiles lists registered switches. pub fn capabilities(w: *std.Io.Writer, e: Engines) !void { + return capabilitiesFor(w, e, @import("glp_startup.zig").steers); +} + +/// As `capabilities`, with `steers` naming whether this build serves the flags only a steering build accepts. +pub fn capabilitiesFor(w: *std.Io.Writer, e: Engines, steers: bool) !void { try w.print("{{\"schema\": 1, \"engine\": \"zig\", \"version\": \"{s}\", \"chip\": ", .{e.version}); if (e.chip) |c| try w.print("\"{s}\"", .{c}) else try w.writeAll("null"); try w.writeAll(", \"backends\": ["); @@ -40,7 +45,7 @@ pub fn capabilities(w: *std.Io.Writer, e: Engines) !void { try w.writeAll("}, \"serve\": {\"flags\": {"); var first = true; for (cli.flags) |f| { - if (!f.native) continue; + if (!f.native or (!f.advertised and !steers)) continue; try w.print("{s}\"{s}\": {{", .{ if (first) "" else ", ", f.name }); first = false; const values = f.native_values orelse f.choices; @@ -157,3 +162,21 @@ test "capability audit: environment table omits dead readers and slide metadata } try std.testing.expectEqual(@as(usize, 1), groups); } + +test "capability audit: a flag a build only refuses is not advertised" { + // --glp is parsed on every platform so its refusal names the engine; only a steering build lists it. + const steers = @import("glp_startup.zig").steers; + var without: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer without.deinit(); + try capabilitiesFor(&without.writer, .{ .version = "test" }, false); + // A build that refuses the flags lists none, but a steering host's own advertised bit still wins. + try std.testing.expectEqual(steers, std.mem.indexOf(u8, without.written(), "\"--glp\":") != null); + var serving: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer serving.deinit(); + try capabilitiesFor(&serving.writer, .{ .version = "test" }, true); + try std.testing.expect(std.mem.indexOf(u8, serving.written(), "\"--glp\":") != null); + var real: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer real.deinit(); + try capabilities(&real.writer, .{ .version = "test" }); + try std.testing.expectEqual(steers, std.mem.indexOf(u8, real.written(), "\"--glp\":") != null); +} diff --git a/zig/src/server/cli_config_test.zig b/zig/src/server/cli_config_test.zig index 59d73541717..6213dc1afdc 100644 --- a/zig/src/server/cli_config_test.zig +++ b/zig/src/server/cli_config_test.zig @@ -151,11 +151,13 @@ test "serve --config: a relative path in the file starts at the file's folder" { \\drafter = "./drafter" \\name = "plain/name" \\kv-cache = "bf16" + \\glp = "vec.gguf" + \\glp-alpha = 0.5 ; const sep = std.fs.path.sep_str; const argv: []const []const u8 = &.{ "--config", "conf" ++ sep ++ "f.toml" }; const out = try config.merge(a, argv, (try config.locate(a, argv, &f.u)).?, text, &f.u); - const want = [_][]const u8{ "conf" ++ sep ++ "weights/m", "--chat-template=conf" ++ sep ++ "t.jinja", "--api-key-file=conf" ++ sep ++ "../keys", "--learn-dir=/abs/learn", "--drafter=conf" ++ sep ++ "drafter", "--name=plain/name", "--kv-cache=bf16" }; + const want = [_][]const u8{ "conf" ++ sep ++ "weights/m", "--chat-template=conf" ++ sep ++ "t.jinja", "--api-key-file=conf" ++ sep ++ "../keys", "--learn-dir=/abs/learn", "--drafter=conf" ++ sep ++ "drafter", "--name=plain/name", "--kv-cache=bf16", "--glp=conf" ++ sep ++ "vec.gguf", "--glp-alpha=0.5" }; try t.expectEqual(want.len, out.argv.len); for (want, out.argv) |w, g| try t.expectEqualStrings(w, g); // a repo id, or a folder named without ./, is left as written: the hub resolves it as it does a typed model diff --git a/zig/src/server/cli_flag.zig b/zig/src/server/cli_flag.zig new file mode 100644 index 00000000000..c4d5b887777 --- /dev/null +++ b/zig/src/server/cli_flag.zig @@ -0,0 +1,22 @@ +//! The shape of one serve flag: its name, how it takes its value and what this binary honours. + +pub const Kind = enum { + value, // --flag VALUE or --flag=VALUE + store_true, // --flag + append, // repeatable --flag VALUE +}; + +pub const Flag = struct { + name: []const u8, + kind: Kind = .value, + /// argparse's choices; empty: any value of the flag's type. + choices: []const []const u8 = &.{}, + /// This binary honours the flag (and lists it in ``capabilities``); the rest are refused as unsupported. + native: bool = false, + /// Listed in ``capabilities``: a flag a build parses only to refuse it by name sets false. + advertised: bool = true, + /// The values it honours when only some of the choices. + native_values: ?[]const []const u8 = null, + /// The value names a file or folder: a config file's relative one is read from that file's folder (cli_config.zig). + path: bool = false, +}; diff --git a/zig/src/server/glp_startup.zig b/zig/src/server/glp_startup.zig new file mode 100644 index 00000000000..4c2c6ea3cb1 --- /dev/null +++ b/zig/src/server/glp_startup.zig @@ -0,0 +1,254 @@ +//! The control vector a serve starts with: the file it reads, the checks that refuse one, and the line that reports it. + +const std = @import("std"); +const builtin = @import("builtin"); +const api = @import("engine_api"); +const glp = api.glp; +const log = @import("log.zig"); +const cfg = @import("checkpoint_config"); +const cli_flag = @import("cli_flag.zig"); + +/// Whether this platform's engine steers: only the Metal engine is built with steering. +pub const steers = builtin.os.tag == .macos; + +/// The flags the control vector adds to the server's own; a platform without steering refuses them by name. +pub const flags = [_]cli_flag.Flag{ + .{ .name = "--glp", .path = true, .native = true, .advertised = steers }, + .{ .name = "--glp-alpha", .native = true, .advertised = steers }, +}; + +/// The model type of the family that takes a control vector: Qwen3.8-27B. +const steer_type = "qwen3_5"; + +/// The hidden size of that family: Qwen3.8-27B is 5120 wide. +const steer_hidden: usize = 5120; + +/// The bytes a control vector file may hold; a 64-layer 5120-wide vector is about 1.3 MiB. +const file_limit: usize = 64 << 20; + +/// What the --glp flags hold: the file the operator named, the strength and the vector the file carries. +pub const Vec = struct { + /// The file's path, as the operator wrote it (null: no file named). + path: ?[]const u8 = null, + /// The strength the operator gave (null: the file's own alpha_default is in force). + alpha: ?f64 = null, + /// The vector the file carries, read once at startup (null: the file was not read). + vector: ?glp.Vector = null, +}; + +/// The --glp file with the path the operator gave; null when the operator named none. +pub fn withPath(g: ?Vec, path: []const u8) Vec { + return .{ .path = path, .alpha = if (g) |v| v.alpha else null }; +} + +/// The --glp file with the strength the operator gave; null when the operator named none. +pub fn withAlpha(g: ?Vec, alpha: f64) Vec { + return .{ .path = if (g) |v| v.path else null, .alpha = alpha }; +} + +/// A finite strength above 0, as --glp-alpha gives it; null for anything else. +pub fn strength(v: []const u8) ?f64 { + const x = @import("fields.zig").pyFloat(v) orelse return null; + const applied: f32 = @floatCast(x); + if (!std.math.isFinite(applied) or applied <= 0) return null; + return x; +} + +/// Read the file the operator named and accept it; the message says why not, or null when it is read. +pub fn read(a: std.mem.Allocator, g: *?Vec) error{OutOfMemory}!?[]const u8 { + const v = g.* orelse return null; + const path = v.path orelse return "argument --glp-alpha: needs --glp"; + var why: glp.Why = .{}; + const loaded = load(a, path, v.alpha, &why) catch |e| { + if (e == error.OutOfMemory) return error.OutOfMemory; + return try std.fmt.allocPrint(a, "argument --glp: {s}", .{why.text()}); + }; + g.* = .{ .path = path, .alpha = v.alpha, .vector = loaded }; + return null; +} + +fn load(a: std.mem.Allocator, path: []const u8, alpha: ?f64, why: *glp.Why) error{ BadGlpFile, OutOfMemory }!glp.Vector { + // The strings the reader hands back borrow the file's bytes, so those bytes stay as long as the vector. + const bytes = std.Io.Dir.cwd().readFileAlloc(startupIo(), path, a, .limited(file_limit)) catch |e| { + if (e == error.OutOfMemory) return error.OutOfMemory; + why.set("cannot read '{s}': {s}", .{ path, reason(e) }); + return error.BadGlpFile; + }; + const vector = glp.read(a, bytes, why) catch |e| { + if (e == error.OutOfMemory) return error.OutOfMemory; + return error.BadGlpFile; + }; + if (alpha == null and (!std.math.isFinite(vector.alpha) or vector.alpha <= 0)) { + why.set("the file's own alpha_default is {d}; the strength must be above 0: pass --glp-alpha", .{vector.alpha}); + return error.BadGlpFile; + } + return vector; +} + +/// Why a file could not be read, in words the operator reads. +fn reason(e: anyerror) []const u8 { + return switch (e) { + error.FileNotFound => "no such file", + error.AccessDenied => "permission denied", + error.IsDir => "the path is a directory", + error.BadPathName => "the path is not a file name", + error.NameTooLong => "the path is too long", + error.StreamTooLong => "the file is over the size limit", + else => "the file cannot be read", + }; +} + +/// The io a startup file read uses: the process's own, since the flags are read before the server takes one. +fn startupIo() std.Io { + return std.Io.Threaded.global_single_threaded.io(); +} + +/// The control vector the engine applies, after the checks that refuse one. +pub fn engine(a: std.mem.Allocator, dir: []const u8, model_type: []const u8, backend: []const u8, g: ?Vec) error{ OutOfMemory, GlpRefused }!?api.glp.Glp { + const v = g orelse return null; + const vector = v.vector orelse return null; + if (try refusal(a, dir, model_type, backend, v)) |why| { + std.debug.print("tensorfold: {s}\n", .{why}); + return error.GlpRefused; + } + report(a, v); + return api.glp.Glp{ .vector = vector, .alpha = alphaOf(v) }; +} + +/// Why this checkpoint cannot take the vector, as the operator reads it; null: it can. +pub fn refusal(a: std.mem.Allocator, dir: []const u8, model_type: []const u8, backend: []const u8, v: Vec) error{OutOfMemory}!?[]const u8 { + const vector = v.vector orelse return null; + // The family's own refusal comes first: a Gemma checkpoint is never steered, whatever the vector's shape. + if (isGemma(model_type)) return "--glp: Gemma checkpoints are never steered: serve it without --glp"; + const model = modelOf(a, dir); + var why: glp.Why = .{}; + if (model.hidden) |hidden| glp.checkModel(vector, hidden, model.repo, &why) catch { + return try std.fmt.allocPrint(a, "--glp: {s}", .{why.text()}); + }; + glp.checkRevision(vector, model.repo, model.revision, &why) catch { + return try std.fmt.allocPrint(a, "--glp: {s}", .{why.text()}); + }; + if (model.layers) |layers| { + for (vector.layers) |l| { + if (l.id >= layers) return try std.fmt.allocPrint(a, "--glp: the vector steers layer {d} of a model with {d} layers: its deepest layer is {d}", .{ l.id, layers, layers - 1 }); + } + } + if (!std.mem.eql(u8, model_type, steer_type)) return try std.fmt.allocPrint(a, "--glp: {s} checkpoints are not steered: only Qwen3.8-27B takes a control vector", .{model_type}); + if (model.hidden) |hidden| if (hidden != steer_hidden) return "--glp: this checkpoint is not Qwen3.8-27B: only the 5120-wide one takes a control vector"; + if (!metal(backend)) return try std.fmt.allocPrint(a, "--glp: only the Metal engine steers: this server runs the {s} engine", .{backendName(backend)}); + return null; +} + +/// The checkpoint's hidden size, depth and provenance it came from, as the vector's own check needs them. +const Model = struct { + /// The model's hidden size, when its config names one. + hidden: ?usize = null, + /// The model's number of blocks, when its config names one. + layers: ?usize = null, + /// The repo id the checkpoint came from ("Org/Name"), empty when it is not a cache snapshot. + repo: []const u8 = "", + /// The snapshot revision the checkpoint came from, empty when it is not a cache snapshot. + revision: []const u8 = "", +}; + +fn modelOf(a: std.mem.Allocator, dir: []const u8) Model { + const src = cachedSource(a, dir); + var m: Model = .{ .repo = src.repo, .revision = src.revision }; + var problem: []const u8 = ""; + const bytes = (cfg.read(a, startupIo(), dir, &problem) catch null) orelse return m; + const doc = std.json.parseFromSliceLeaky(std.json.Value, a, bytes, .{}) catch return m; + if (doc != .object) return m; + const text = if (doc.object.get("text_config")) |t| (if (t == .object) t else doc) else doc; + if (text.object.get("hidden_size")) |v| { + if (v == .integer and v.integer > 0) m.hidden = @intCast(v.integer); + } + if (text.object.get("num_hidden_layers") orelse doc.object.get("num_hidden_layers")) |v| { + if (v == .integer and v.integer > 0) m.layers = @intCast(v.integer); + } + return m; +} + +/// The repo id and revision a cached checkpoint came from; empty strings when not a cache snapshot. +fn cachedSource(a: std.mem.Allocator, dir: []const u8) struct { repo: []const u8, revision: []const u8 } { + const at = std.mem.lastIndexOf(u8, dir, "models--") orelse return .{ .repo = "", .revision = "" }; + const rest = dir[at + "models--".len ..]; + const sep = std.mem.indexOf(u8, rest, "/snapshots/") orelse return .{ .repo = "", .revision = "" }; + const owner = rest[0..sep]; + const dash = std.mem.indexOf(u8, owner, "--") orelse return .{ .repo = "", .revision = "" }; + const tail = rest[sep + "/snapshots/".len ..]; + const rev = tail[0 .. std.mem.indexOfScalar(u8, tail, '/') orelse tail.len]; + const repo = std.fmt.allocPrint(a, "{s}/{s}", .{ owner[0..dash], owner[dash + 2 ..] }) catch ""; + return .{ .repo = repo, .revision = if (repo.len > 0) rev else "" }; +} + +/// Gemma checkpoints are never steered. +fn isGemma(model_type: []const u8) bool { + return std.mem.startsWith(u8, model_type, "gemma"); +} + +/// The backend that steers: the Metal engine; the CUDA engines carry no control vector. +fn metal(backend: []const u8) bool { + if (!steers) return false; + return std.mem.eql(u8, backend, "auto") or std.mem.eql(u8, backend, "mlx"); +} + +/// The engine a backend names, as the operator reads it. +fn backendName(backend: []const u8) []const u8 { + if (std.mem.eql(u8, backend, "auto")) return if (builtin.os.tag == .macos) "Metal" else "CUDA"; + if (std.mem.eql(u8, backend, "mlx")) return "Metal"; + if (std.mem.eql(u8, backend, "cuda")) return "CUDA"; + if (std.mem.eql(u8, backend, "rocm")) return "ROCm"; + return backend; +} + +/// The strength in force: the operator's, or the file's own. +pub fn alphaOf(v: Vec) f32 { + if (v.alpha) |x| return @floatCast(x); + return v.vector.?.alpha; +} + +/// The line that reports what is in force: the file (escaped), its SHA-256, that replies are steered, and the rest. +pub fn report(a: std.mem.Allocator, v: Vec) void { + const vector = v.vector orelse return; + const sha = std.fmt.bytesToHex(vector.sha256, .lower); + const file_sha = std.fmt.bytesToHex(vector.file_sha256, .lower); + log.line("glp on: replies are steered by the control vector in \"{f}\" (file sha256: {s}; alpha: {d:.2}; layers: {d} ({s}); base: {s}; tensor digest: {s})", .{ + std.zig.fmtString(v.path orelse ""), + file_sha[0..], + alphaOf(v), + vector.layers.len, + layerIds(a, vector.layers), + base(a, vector), + fmt(a, "{s} ({s})", .{ sha[0..12], if (vector.claims_digest) "verified" else "the file claims none" }), + }); + if (vector.transferred) log.line("warning: this vector was derived at {f}, not at {f}: it is applied at the residual stream", .{ std.zig.fmtString(vector.derived_at), std.zig.fmtString(vector.hook_point) }); +} + +/// The checkpoint the vector was derived from, with its revision when it names one; the file's own words, escaped. +fn base(a: std.mem.Allocator, v: glp.Vector) []const u8 { + if (v.base_model.len == 0) return "an unnamed checkpoint"; + if (v.base_revision.len == 0) return fmt(a, "{f}", .{std.zig.fmtString(v.base_model)}); + return fmt(a, "{f} @ {f}", .{ std.zig.fmtString(v.base_model), std.zig.fmtString(v.base_revision) }); +} + +/// The layer ids a vector covers: "1-63" when they run and "1, 3, 5" when they do not. +fn layerIds(a: std.mem.Allocator, layers: []const glp.Layer) []const u8 { + if (layers.len == 0) return "none"; + var run = true; + for (layers, 0..) |l, i| if (i > 0 and l.id != layers[i - 1].id + 1) { + run = false; + break; + }; + if (run) return fmt(a, "{d}-{d}", .{ layers[0].id, layers[layers.len - 1].id }); + var w: std.Io.Writer.Allocating = .init(a); + for (layers, 0..) |l, i| { + if (i > 0) w.writer.print(", ", .{}) catch {}; + w.writer.print("{d}", .{l.id}) catch {}; + } + return w.toOwnedSlice() catch "?"; +} + +/// A formatted string, or a mark when the allocator says no. +fn fmt(a: std.mem.Allocator, comptime f: []const u8, args: anytype) []const u8 { + return std.fmt.allocPrint(a, f, args) catch "?"; +} diff --git a/zig/src/server/glp_startup_test.zig b/zig/src/server/glp_startup_test.zig new file mode 100644 index 00000000000..4df6a363544 --- /dev/null +++ b/zig/src/server/glp_startup_test.zig @@ -0,0 +1,382 @@ +//! The control vector's serve checks: the file, the reader, the family and the line that reports what is in force. + +const std = @import("std"); +const builtin = @import("builtin"); +const glp = @import("engine_api").glp; +const serve = @import("glp_startup.zig"); +const log = @import("log.zig"); + +const io = std.testing.io; + +/// The width Qwen3.8-27B has; a vector that steers it is this wide. +const width = 5120; + +/// The depth Qwen3.8-27B has; its last block is layer 63. +const depth = 64; + +/// Whether this platform's engine steers: only the Metal engine does, and only on a Mac. +const steers = builtin.os.tag == .macos; + +/// The lines the server printed, for the report the operator reads. +const Sink = struct { + list: std.ArrayList(u8) = .empty, + a: std.mem.Allocator, +}; + +fn capture(ctx: *anyopaque, text: []const u8) void { + const sink: *Sink = @ptrCast(@alignCast(ctx)); + sink.list.appendSlice(sink.a, text) catch {}; +} + +/// A checkpoint folder with a config.json, a vector file beside it and the vector read. +const Fixture = struct { + tmp: std.testing.TmpDir, + /// The model's folder, as the serve path names it. + model: []const u8, + /// The vector the file holds, read once. + g: ?serve.Vec, + + fn make(a: std.mem.Allocator, w: usize, hidden: usize, ids: []const u32, spec: glp.WriteSpec, alpha: ?f64) !Fixture { + return makeDepth(a, w, hidden, depth, ids, spec, alpha); + } + + fn makeDepth(a: std.mem.Allocator, w: usize, hidden: usize, layers: usize, ids: []const u32, spec: glp.WriteSpec, alpha: ?f64) !Fixture { + var tmp = std.testing.tmpDir(.{}); + errdefer tmp.cleanup(); + const model = try std.fs.path.join(a, &.{ ".zig-cache", "tmp", tmp.sub_path[0..] }); + const json = try std.fmt.allocPrint(a, "{{\"model_type\":\"qwen3_5\",\"hidden_size\":{d},\"num_hidden_layers\":{d},\"text_config\":{{\"hidden_size\":{d}}}}}", .{ hidden, layers, hidden }); + try tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = json }); + const bytes = try vectorBytes(a, w, ids, spec); + try tmp.dir.writeFile(io, .{ .sub_path = "vector.gguf", .data = bytes }); + const path = try std.fs.path.join(a, &.{ model, "vector.gguf" }); + var g: ?serve.Vec = serve.withPath(null, path); + if (alpha) |x| g = serve.withAlpha(g, x); + if (try serve.read(a, &g)) |why| { + std.debug.print("refused: {s}\n", .{why}); + return error.UnexpectedRefusal; + } + return .{ .tmp = tmp, .model = model, .g = g }; + } +}; + +/// The reason the file was refused, as the operator reads it. +fn refused(a: std.mem.Allocator, g: *?serve.Vec) ![]const u8 { + return (try serve.read(a, g)) orelse return error.UnexpectedlyAccepted; +} + +/// A vector file with one direction per layer, each a unit vector the reader accepts. +fn vectorBytes(a: std.mem.Allocator, w: usize, ids: []const u32, spec: glp.WriteSpec) ![]u8 { + const layers = try a.alloc(glp.Layer, ids.len); + for (ids, 0..) |id, i| { + const dir = try a.alloc(f32, w); + dir[0] = 1.0; + layers[i] = .{ .id = id, .dir = dir }; + } + var s = spec; + s.layers = layers; + return glp.write(a, s); +} + +test "a missing file is refused with the path and the reason" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var g: ?serve.Vec = serve.withPath(null, ".zig-cache/tmp/no-such-vector.gguf"); + const why = try refused(a, &g); + try std.testing.expect(std.mem.indexOf(u8, why, "argument --glp:") != null); + try std.testing.expect(std.mem.indexOf(u8, why, "cannot read") != null); + try std.testing.expect(std.mem.indexOf(u8, why, "no such file") != null); + try std.testing.expect(std.mem.indexOf(u8, why, "no-such-vector.gguf") != null); +} + +test "a file the reader refuses is refused with the reader's reason" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(io, .{ .sub_path = "vector.gguf", .data = "not a control vector" }); + const path = try std.fs.path.join(a, &.{ ".zig-cache", "tmp", tmp.sub_path[0..], "vector.gguf" }); + var g: ?serve.Vec = serve.withPath(null, path); + const why = try refused(a, &g); + try std.testing.expect(std.mem.indexOf(u8, why, "argument --glp:") != null); + try std.testing.expect(std.mem.indexOf(u8, why, "not a GGUF container") != null); +} + +test "--glp-alpha without --glp is refused" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var g: ?serve.Vec = serve.withAlpha(null, 0.5); + const why = try refused(a, &g); + try std.testing.expect(std.mem.indexOf(u8, why, "needs --glp") != null); +} + +test "the strength must be finite and above 0" { + try std.testing.expect(serve.strength("0.5") != null); + try std.testing.expect(serve.strength("0") == null); + try std.testing.expect(serve.strength("-1") == null); + try std.testing.expect(serve.strength("inf") == null); + try std.testing.expect(serve.strength("nan") == null); + try std.testing.expect(serve.strength("1e100") == null); + try std.testing.expect(serve.strength("1e-100") == null); + try std.testing.expect(serve.strength("abc") == null); +} + +test "the line shows the file name escaped, so a name cannot add a line of its own" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.make(a, width, width, &.{ 1, 2 }, .{ .layers = &.{} }, null); + defer f.tmp.cleanup(); + var named = f.g.?; + named.path = "dir/a\nglp off: \"x\".gguf"; + var sink: Sink = .{ .a = a }; + log.Test.sink = .{ .ctx = @ptrCast(&sink), .call = capture }; + defer log.Test.sink = null; + serve.report(a, named); + try std.testing.expect(std.mem.indexOf(u8, sink.list.items, "dir/a\\nglp off: \\\"x\\\".gguf") != null); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, sink.list.items, "\n")); +} + +test "a good vector is accepted where the engine steers" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.make(a, width, width, &.{ 1, 2 }, .{ .alpha = 0.5, .base_model = "TensorFold/Qwen3.8-27B-MLX-4bit", .base_revision = "8f2c1d4e", .layers = &.{} }, null); + defer f.tmp.cleanup(); + const why = try serve.refusal(a, f.model, "qwen3_5", "auto", f.g.?); + if (steers) { + try std.testing.expect(why == null); + return; + } + // Only the Metal engine steers, so on this platform the same file is refused by name. + try std.testing.expect(why != null); + try std.testing.expect(std.mem.indexOf(u8, why.?, "Metal") != null); +} + +test "the operator's strength is the one in force" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.make(a, width, width, &.{ 1, 2 }, .{ .alpha = 0.5, .layers = &.{} }, 0.25); + defer f.tmp.cleanup(); + if (!steers) { + try std.testing.expectError(error.GlpRefused, serve.engine(a, f.model, "qwen3_5", "auto", f.g)); + return; + } + const g = (try serve.engine(a, f.model, "qwen3_5", "auto", f.g)).?; + try std.testing.expectEqual(@as(f32, 0.25), g.alpha); + try std.testing.expectEqual(@as(usize, 2), g.vector.layers.len); +} + +test "a family that is not steered is refused by name" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.make(a, width, width, &.{ 1, 2 }, .{ .layers = &.{} }, null); + defer f.tmp.cleanup(); + const why = (try serve.refusal(a, f.model, "glm5_next", "auto", f.g.?)).?; + try std.testing.expect(std.mem.indexOf(u8, why, "glm5_next") != null); + try std.testing.expect(std.mem.indexOf(u8, why, "Qwen3.8-27B") != null); +} + +test "a Gemma family is refused outright" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.make(a, width, width, &.{ 1, 2 }, .{ .layers = &.{} }, null); + defer f.tmp.cleanup(); + const why = (try serve.refusal(a, f.model, "gemma4", "auto", f.g.?)).?; + try std.testing.expect(std.mem.indexOf(u8, why, "Gemma") != null); + // The family speaks before the vector's width does, even when the two disagree. + var other = try Fixture.make(a, 4096, width, &.{ 1, 2 }, .{ .layers = &.{} }, null); + defer other.tmp.cleanup(); + const family = (try serve.refusal(a, other.model, "gemma4", "auto", other.g.?)).?; + try std.testing.expect(std.mem.indexOf(u8, family, "Gemma") != null); + try std.testing.expect(std.mem.indexOf(u8, family, "4096") == null); +} + +test "a vector the model's width does not match is refused" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.make(a, 4096, width, &.{ 1, 2 }, .{ .layers = &.{} }, null); + defer f.tmp.cleanup(); + const why = (try serve.refusal(a, f.model, "qwen3_5", "auto", f.g.?)).?; + try std.testing.expect(std.mem.indexOf(u8, why, "4096") != null); + try std.testing.expect(std.mem.indexOf(u8, why, "5120") != null); +} + +test "a vector that names a layer past the model's depth is refused before the model loads" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.makeDepth(a, width, width, 4, &.{ 1, 4 }, .{ .layers = &.{} }, null); + defer f.tmp.cleanup(); + const why = (try serve.refusal(a, f.model, "qwen3_5", "auto", f.g.?)).?; + try std.testing.expect(std.mem.indexOf(u8, why, "layer 4") != null); + try std.testing.expect(std.mem.indexOf(u8, why, "4 layers") != null); + try std.testing.expect(std.mem.indexOf(u8, why, "deepest layer is 3") != null); +} + +test "a nested config's depth is read from text_config" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.makeDepth(a, width, width, 4, &.{ 1, 4 }, .{ .layers = &.{} }, null); + defer f.tmp.cleanup(); + // The depth lives in text_config only, as a nested config carries it. + const json = try std.fmt.allocPrint(a, "{{\"model_type\":\"qwen3_5\",\"text_config\":{{\"hidden_size\":{d},\"num_hidden_layers\":4}}}}", .{width}); + try f.tmp.dir.writeFile(io, .{ .sub_path = "config.json", .data = json }); + const why = (try serve.refusal(a, f.model, "qwen3_5", "auto", f.g.?)).?; + try std.testing.expect(std.mem.indexOf(u8, why, "layer 4") != null); + try std.testing.expect(std.mem.indexOf(u8, why, "4 layers") != null); +} + +test "a vector that stops at the model's deepest layer is accepted" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.makeDepth(a, width, width, 4, &.{ 1, 3 }, .{ .layers = &.{} }, null); + defer f.tmp.cleanup(); + const why = try serve.refusal(a, f.model, "qwen3_5", "auto", f.g.?); + if (steers) try std.testing.expect(why == null) else try std.testing.expect(why != null and std.mem.indexOf(u8, why.?, "Metal") != null); +} + +test "the CUDA engine does not steer" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.make(a, width, width, &.{ 1, 2 }, .{ .layers = &.{} }, null); + defer f.tmp.cleanup(); + const why = (try serve.refusal(a, f.model, "qwen3_5", "cuda", f.g.?)).?; + try std.testing.expect(std.mem.indexOf(u8, why, "Metal") != null); +} + +test "the ROCm engine does not steer" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.make(a, width, width, &.{ 1, 2 }, .{ .layers = &.{} }, null); + defer f.tmp.cleanup(); + const why = (try serve.refusal(a, f.model, "qwen3_5", "rocm", f.g.?)).?; + try std.testing.expect(std.mem.indexOf(u8, why, "ROCm") != null); +} + +test "a vector derived at another site is reported" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.make(a, width, width, &.{ 1, 2 }, .{ .derived_at = "ffn_out_pre_residual", .layers = &.{} }, null); + defer f.tmp.cleanup(); + var sink: Sink = .{ .a = a }; + log.Test.sink = .{ .ctx = @ptrCast(&sink), .call = capture }; + defer log.Test.sink = null; + serve.report(a, f.g.?); + try std.testing.expect(std.mem.indexOf(u8, sink.list.items, "warning:") != null); + try std.testing.expect(std.mem.indexOf(u8, sink.list.items, "ffn_out_pre_residual") != null); +} + +test "a vector derived at another site is not refused where the engine steers" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.make(a, width, width, &.{ 1, 2 }, .{ .derived_at = "ffn_out_pre_residual", .layers = &.{} }, null); + defer f.tmp.cleanup(); + const why = try serve.refusal(a, f.model, "qwen3_5", "auto", f.g.?); + if (steers) { + try std.testing.expect(why == null); + return; + } + // The site's warning is not the refusal here; the engine is. + try std.testing.expect(why != null); + try std.testing.expect(std.mem.indexOf(u8, why.?, "Metal") != null); +} + +test "the control vector's flags are the serve table's flag type" { + // cli.zig concatenates this table into its own, so both must name one type, not two equal shapes. + const cli = @import("cli.zig"); + try std.testing.expect(@TypeOf(serve.flags[0]) == cli.Flag); +} + +test "the report says verified only when the parsed digest was checked" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.make(a, width, width, &.{ 1, 2 }, .{ .layers = &.{} }, null); + defer f.tmp.cleanup(); + var sink: Sink = .{ .a = a }; + log.Test.sink = .{ .ctx = @ptrCast(&sink), .call = capture }; + defer log.Test.sink = null; + var unchecked = f.g.?; + unchecked.vector.?.claims_digest = false; + serve.report(a, unchecked); + try std.testing.expect(std.mem.indexOf(u8, sink.list.items, "the file claims none") != null); + try std.testing.expect(std.mem.indexOf(u8, sink.list.items, "(verified)") == null); + sink.list.clearRetainingCapacity(); + serve.report(a, f.g.?); + try std.testing.expect(std.mem.indexOf(u8, sink.list.items, "(verified)") != null); +} + +/// Remove the file's parsed digest key, leaving any text that merely reads like it. +fn dropDigestKey(bytes: []u8) void { + const at = std.mem.indexOf(u8, bytes, "glp.content_sha256").?; + bytes[at + "glp.content_sha256".len - 1] = '7'; +} + +test "a description that reads like a digest does not make the loaded file verified" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const bytes = try vectorBytes(a, width, &.{ 1, 2 }, .{ .layers = &.{}, .publication = .{ .description = "the file carries glp.content_sha256 in its description" } }); + dropDigestKey(bytes); + try tmp.dir.writeFile(io, .{ .sub_path = "vector.gguf", .data = bytes }); + const path = try std.fs.path.join(a, &.{ ".zig-cache", "tmp", tmp.sub_path[0..], "vector.gguf" }); + var g: ?serve.Vec = serve.withPath(null, path); + try std.testing.expectEqual(@as(?[]const u8, null), try serve.read(a, &g)); + try std.testing.expect(!g.?.vector.?.claims_digest); + var sink: Sink = .{ .a = a }; + log.Test.sink = .{ .ctx = @ptrCast(&sink), .call = capture }; + defer log.Test.sink = null; + serve.report(a, g.?); + try std.testing.expect(std.mem.indexOf(u8, sink.list.items, "the file claims none") != null); + try std.testing.expect(std.mem.indexOf(u8, sink.list.items, "(verified)") == null); +} + +test "the control-vector flags are the serve table's type and a file flag" { + for (serve.flags) |f| try std.testing.expectEqual(steers, f.advertised); + // A config file's relative --glp starts at the file's folder, as its other file flags do. + try std.testing.expect(serve.flags[0].path); +} + +test "Qwen3.8-27B rejects a different snapshot revision on the same cached repo while accepting conversions" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try Fixture.make(a, width, width, &.{ 1, 2 }, .{ .base_model = "Qwen/Qwen3.8-27B", .base_revision = "aaaa1111bbbb", .layers = &.{} }, 1.0); + defer f.tmp.cleanup(); + const cfg_bytes = "{\"model_type\":\"qwen3_5\",\"hidden_size\":5120,\"num_hidden_layers\":64,\"text_config\":{\"hidden_size\":5120}}"; + const sub_dirs = [_]struct { path: []const u8, expect_mismatch: bool }{ + .{ .path = "cache/models--Qwen--Qwen3.8-27B/snapshots/aaaa1111bbbb", .expect_mismatch = false }, + .{ .path = "cache/models--Qwen--Qwen3.8-27B/snapshots/cccc2222dddd", .expect_mismatch = true }, + .{ .path = "cache/models--mlx-community--Qwen3.8-27B-4bit/snapshots/cccc2222dddd", .expect_mismatch = false }, + }; + for (sub_dirs) |case| { + try f.tmp.dir.createDirPath(io, case.path); + var sub = try f.tmp.dir.openDir(io, case.path, .{}); + defer sub.close(io); + try sub.writeFile(io, .{ .sub_path = "config.json", .data = cfg_bytes }); + const full = try std.fs.path.join(a, &.{ ".zig-cache", "tmp", f.tmp.sub_path[0..], case.path }); + const why = try serve.refusal(a, full, "qwen3_5", "auto", f.g.?); + if (steers and case.expect_mismatch) { + try std.testing.expect(why != null and std.mem.indexOf(u8, why.?, "revision") != null); + } else if (steers) { + try std.testing.expect(why == null); + } else { + try std.testing.expect(why != null); + } + } +} diff --git a/zig/src/server/main.zig b/zig/src/server/main.zig index 1fbd1f0cdcc..85c66506736 100644 --- a/zig/src/server/main.zig +++ b/zig/src/server/main.zig @@ -37,6 +37,7 @@ const usage_line = "usage: tensorfold serve [-h] [--config FILE.toml] [--host HO " [--thinking | --no-thinking] [--reasoning-effort {low,medium,high,xhigh}]" ++ " [--thinking-budget THINKING_BUDGET] [--thinking-reserve THINKING_RESERVE] [--loop-guard] [--loop-guard-stop] [--tool-think-close] [--no-drafts]" ++ " [--drafter DRAFTER]" ++ + " [--glp FILE] [--glp-alpha ALPHA]" ++ " [--drafter-bits {0,4}] [--record RECORD] [--keep-warm SECONDS] [--idle-unload SECONDS]" ++ " [--silence-floor-dbfs DBFS] [--silence-seconds SECONDS]" ++ " [--silence-onset-s SECONDS] [--silence-onset-voiced-s SECONDS]" ++ diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 9b9736e206f..8731219a8fd 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -324,7 +324,7 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp text = if (has(d.name, "tf_delta_gdn_post_sums")) sources.core_deltanet else try tf.qwen27.simd_attention.library(a, true, true); } else if (std.mem.startsWith(u8, d.name, "qwen27 ")) { if (!assemble) return undefined; - text = if (has(d.name, " copy ")) tf.qwen27.runtime_sources.copy else if (has(d.name, " moe rows ")) tf.qwen27.moe_gpu.rows_source else if (has(d.name, " moe ")) tf.qwen27.runtime_sources.moe else tf.qwen27.runtime_sources.glue; + text = if (has(d.name, " copy ")) tf.qwen27.runtime_sources.copy else if (has(d.name, " norm steer ")) try @import("metal_q27_limits.zig").specialize(a, tf.qwen27.runtime_sources.norm_steer, "constexpr int K=5120;") else if (has(d.name, " moe rows ")) tf.qwen27.moe_gpu.rows_source else if (has(d.name, " moe ")) tf.qwen27.runtime_sources.moe else tf.qwen27.runtime_sources.glue; } else if (std.mem.startsWith(u8, d.name, "metal pair ")) { if (!assemble) return undefined; text = sources.core_pair_rows; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index 8b17aae2535..3c064cbb02a 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -491,20 +491,8 @@ pub fn main(init: std.process.Init) !u8 { var pointwise_cases: [pointwise.count]pointwise.Case = undefined; try pointwise.collect(a, device, queue, &pointwise_kernels, &pointwise_cases, &kernels, o.only); defer for (&pointwise_cases) |*case| case.deinit(); - const native_hc = try @import("metal_qwen4_hc.zig").Suite.create(a, device, queue, &kernels, o.only); - defer native_hc.destroy(); - const native_qsa_select = try @import("metal_qwen4_qsa_select.zig").Suite.create(a, device, queue, &kernels, o.only); - defer native_qsa_select.destroy(); - const native_qsa_scores = try @import("metal_qwen4_qsa_scores.zig").Suite.create(a, device, queue, &kernels, o.only); - defer native_qsa_scores.destroy(); - const native_qsa_attn = try @import("metal_qwen4_qsa_attn.zig").Suite.create(a, device, queue, &kernels, o.only); - defer native_qsa_attn.destroy(); - const native_qsa_norm = try @import("metal_qwen4_qsa_norm.zig").Suite.create(a, device, queue, &kernels, o.only); - defer native_qsa_norm.destroy(); - const native_ple = try @import("metal_qwen4_ple.zig").Suite.create(a, device, queue, &kernels, o.only); - defer native_ple.destroy(); - const native_gdn = try @import("metal_qwen4_gdn.zig").Suite.create(a, device, queue, &kernels, o.only); - defer native_gdn.destroy(); + var qwen4_suites = try @import("metal_qwen4_main.zig").Suites.create(a, device, queue, &kernels, o.only); + defer qwen4_suites.destroy(); const moss_image = try @import("metal_moss_image.zig").Suite.create(a, device, queue, &kernels, o.only); defer moss_image.destroy(); const moss_image_decoder = try @import("metal_moss_image_decoder.zig").Suite.create(a, device, queue, &kernels, o.only); @@ -513,6 +501,9 @@ pub fn main(init: std.process.Init) !u8 { defer h3_image_suites.destroy(); var dsv41_suites = try @import("metal_dsv41_main.zig").Suites.create(a, device, queue, &kernels, o.only); defer dsv41_suites.destroy(); + var steer: @import("metal_qwen27_steer.zig").Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; + defer steer.deinit(); + try steer.collect(o.only, o.gates, o.seed); const sn_mhc = try @import("metal_sensenova_mhc.zig").Suite.create(a, device, queue, &kernels, o.only); defer sn_mhc.destroy(); var sn_lin = @import("metal_sensenova_linear.zig").Suite{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; diff --git a/zig/tests/contract/metal_q27_limits.zig b/zig/tests/contract/metal_q27_limits.zig index 1bb47021652..9c7dd3b4e6a 100644 --- a/zig/tests/contract/metal_q27_limits.zig +++ b/zig/tests/contract/metal_q27_limits.zig @@ -29,3 +29,8 @@ pub fn source(a: std.mem.Allocator, name: []const u8) ![]u8 { defer a.free(body); return std.fmt.allocPrint(a, "#define Q27_XS {d}\n{s}", .{ @intFromBool(xs), body }); } +/// The family's kernels carry a marker where the specialization goes; the limits pass compiles the real one. +pub fn specialize(a: std.mem.Allocator, template: []const u8, definitions: []const u8) ![]u8 { + const mark = std.mem.indexOf(u8, template, "Q27_SPECIALIZE") orelse return error.UnknownLaunch; + return std.mem.concat(a, u8, &.{ template[0..mark], definitions, template[mark + "Q27_SPECIALIZE".len ..] }); +} diff --git a/zig/tests/contract/metal_qwen27_steer.zig b/zig/tests/contract/metal_qwen27_steer.zig new file mode 100644 index 00000000000..46f907d577e --- /dev/null +++ b/zig/tests/contract/metal_qwen27_steer.zig @@ -0,0 +1,425 @@ +//! The qwen27 steering kernel on the GPU: the fused norm's steered row against the float64 reference. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); + +const c = contract.spec; +const g = contract.gates; +const steer = contract.steer; + +/// The kernel the family compiles for the steering launch. +const symbol = "custom_kernel_q27_norm_steer_bfloat16_t_bfloat16_t_bfloat16_t_floatc_int32_t_bfloat16_t_bfloat16_t_float_float_float"; + +/// The family's own norm kernel: the fused kernel's normalisation must agree with it. +const norm_symbol = "custom_kernel_q27_norm_xs_bfloat16_t_bfloat16_t_bfloat16_t_floatc_int32_t_bfloat16_t_bfloat16_t_float"; + +/// The width the family compiles the kernel at. +const width = steer.hidden; + +/// The strength the launch carries. +const strength: f32 = 1.0; + +/// The eps the norm reads. +const eps: f32 = 1e-6; + +/// The rows the frame pads a call to, as the kernel's grid is sized. +fn padded(rows: usize) usize { + return 16 * ((rows + 15) / 16); +} + +/// The groups of a row that write their own partial, four threads to a group. +const xs_groups = steer.threads / 4; + +/// A control's planted fault: a NaN dropped, a wrong normalisation, a contracted add, or an unguarded zero step. +const Variant = enum { production, nan, norm, contracted, unguarded }; + +/// Strengths whose products round, so the add's order shows: a power of two leaves every product exact. +const ordered_strengths = [_]f32{ 0.1, 0.3 }; + +/// One kernel this suite registers: the source it is built from and the gate its control breaks. +pub const Entry = struct { + name: []const u8, + variant: Variant, + control: ?g.Gate, +}; + +/// Every kernel this suite registers: the launch the engine makes, and the control that breaks a gate. +pub const entries = [_]Entry{ + .{ .name = "qwen27 steer", .variant = .production, .control = null }, + .{ .name = "qwen27 steer nan control", .variant = .nan, .control = .nonfinite }, +}; + +/// One line of the source replaced. +fn edit(a: std.mem.Allocator, text: []const u8, from: []const u8, to: []const u8) ![]u8 { + const at = std.mem.indexOf(u8, text, from) orelse return error.UnknownSource; + return std.mem.concat(a, u8, &.{ text[0..at], to, text[at + from.len ..] }); +} + +/// The family's source as production compiles it, with the fault a control plants. +fn source(a: std.mem.Allocator, variant: Variant) ![]u8 { + const text = try tf.qwen27.norm_steer_gpu.source(a, width); + defer a.free(text); + return switch (variant) { + .production => a.dupe(u8, text), + .nan => edit(a, text, "const float v = step == 0.0f ? hv[i] : (hv[i] + step);", "const float v = isnan(hv[i]) ? 0.0f : (step == 0.0f ? hv[i] : (hv[i] + step));"), + // The norm's own division, wrong: the row the model reads changes and the steered row does not. + .norm => edit(a, text, "total / float(K)", "total"), + .contracted => edit(a, text, "const float v = step == 0.0f ? hv[i] : (hv[i] + step);", "const float v = step == 0.0f ? hv[i] : fma(ALPHA, d, hv[i]);"), + .unguarded => edit(a, text, "const float v = step == 0.0f ? hv[i] : (hv[i] + step);", "const float v = hv[i] + step;"), + }; +} + +/// The plain norm's source as production compiles it, padded rows included: the launch dispatches them. +fn normSource(a: std.mem.Allocator) ![]u8 { + return tf.qwen27.quant_gpu.specializedSource(a, .{ .kind = .norm, .k = width, .xs = true }); +} + +/// One kernel's device side: the rig's buffers, the reference beside them and the launch. +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + pipe: mtl.Pipeline, + spec: c.Spec = undefined, + s: ?steer.Steer = null, + rows: usize = 0, + groups: usize = 0, + alpha: f32 = strength, + h: rig_.Ref = undefined, + residual: rig_.Ref = undefined, + weight: rig_.Ref = undefined, + epsilon: rig_.Ref = undefined, + dims: rig_.Ref = undefined, + dir: rig_.Ref = undefined, + ho: rig_.Ref = undefined, + xo: rig_.Ref = undefined, + xs: rig_.Ref = undefined, + + const vt = g.hooks(Probe); + + pub fn deinit(p: *Probe) void { + if (p.s) |s| s.deinit(); + p.rig.deinit(); + p.pipe.deinit(); + } + + pub fn kernel(p: *Probe, e: Entry) g.Kernel { + var spec = steer.spec(); + spec.name = e.name; + p.spec = spec; + return .{ .spec = spec, .ctx = p, .vt = &vt, .control = e.control }; + } + + /// The buffers for a shape and a fill: the residual stream, the direction and the norm's own inputs. + pub fn prepare(p: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + return p.load(shape, strength, fill, seed); + } + + /// The buffers at `alpha`; a null fill is the rows where the add's order shows (Steer.fillOrdered). + fn load(p: *Probe, shape: c.Shape, alpha: f32, fill: ?g.Fill, seed: u64) !bool { + p.rig.reset(); + if (shape.n != width or shape.k != width or shape.rows == 0) return false; + if (p.s) |s| s.deinit(); + p.s = null; + var s = try steer.Steer.init(p.a, .{ .alpha = alpha, .rows = shape.rows, .hidden = width }); + errdefer s.deinit(); + if (fill) |f| s.fill(f, seed) else try s.fillOrdered(seed); + p.alpha = alpha; + p.rows = shape.rows; + p.groups = padded(shape.rows); + const zeros = try p.a.alloc(u16, shape.rows * width); + defer p.a.free(zeros); + @memset(zeros, 0); + p.h = try p.rig.input(std.mem.sliceAsBytes(s.x)); + // The kernel adds the block's output to the residual: the residual is zero, so the row stands alone. + p.residual = try p.rig.input(std.mem.sliceAsBytes(zeros)); + @memset(zeros, c.toBf16(1)); + p.weight = try p.rig.input(std.mem.sliceAsBytes(zeros)); + const eps_value: f32 = eps; + p.epsilon = try p.rig.input(std.mem.asBytes(&eps_value)); + const dims = [2]i32{ @intCast(shape.rows), @intCast(p.groups) }; + p.dims = try p.rig.input(std.mem.asBytes(&dims)); + p.dir = try p.rig.input(std.mem.sliceAsBytes(s.dir)); + p.ho = try p.rig.output(shape.rows * width * 2); + p.xo = try p.rig.scratch(shape.rows * width * 2); + p.xs = try p.rig.scratch(xs_groups * p.groups * 4); + p.s = s; + return true; + } + + /// The launch the engine makes: a threadgroup a row, the fused norm's threads. + pub fn run(p: *Probe) !void { + return p.runWith(p.pipe); + } + + /// The same launch with a kernel of its own: the control's fault rides in the source it was built from. + pub fn runWith(p: *Probe, pipe: mtl.Pipeline) !void { + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(pipe); + e.setBuffer(p.h.buf, p.h.off, 0); + e.setBuffer(p.residual.buf, p.residual.off, 1); + e.setBuffer(p.weight.buf, p.weight.off, 2); + e.setBuffer(p.epsilon.buf, p.epsilon.off, 3); + e.setBuffer(p.dims.buf, p.dims.off, 4); + e.setBuffer(p.ho.buf, p.ho.off, 5); + e.setBuffer(p.xo.buf, p.xo.off, 6); + e.setBuffer(p.xs.buf, p.xs.off, 7); + e.setBuffer(p.dir.buf, p.dir.off, 8); + e.setValue(p.alpha, 9); + e.dispatchGroups(mtl.Size.of(1, p.groups, 1), mtl.Size.of(steer.threads, 1, 1)); + try p.rig.finish(pass); + } + + pub fn count(p: *Probe) usize { + return p.rows * width; + } + + /// How many steered elements differ from the separately rounded add (the contract's kernelOut), bit for bit. + fn unordered(p: *Probe) !usize { + const want = try p.a.alloc(f64, p.rows * width); + defer p.a.free(want); + p.s.?.kernelOut(want); + const got = p.rig.bytes(p.ho, p.rows * width * 2); + var differ: usize = 0; + for (want, 0..) |w, i| { + if (std.mem.readInt(u16, got[i * 2 ..][0..2], .little) != c.toBf16(@floatCast(w))) differ += 1; + } + return differ; + } + + pub fn reference(p: *Probe, want: []f64, mag: []f64) !void { + try p.s.?.reference(want, mag); + } + + pub fn bounds(p: *Probe, want: []const f64, mag: []const f64, allow: []f64) !void { + _ = mag; + p.s.?.bounds(want, allow); + } + + /// The plain norm's normalised row: the row the fused kernel steered, normalised by the family's own kernel. + fn plainRow(p: *Probe, pipe: mtl.Pipeline) ![]u8 { + const plain_ho = try p.rig.scratch(p.rows * width * 2); + const plain_xo = try p.rig.scratch(p.rows * width * 2); + const plain_xs = try p.rig.scratch(xs_groups * p.groups * 4); + const pass = p.rig.begin(); + const e = pass.e; + e.setPipeline(pipe); + e.setBuffer(p.ho.buf, p.ho.off, 0); + e.setBuffer(p.residual.buf, p.residual.off, 1); + e.setBuffer(p.weight.buf, p.weight.off, 2); + e.setBuffer(p.epsilon.buf, p.epsilon.off, 3); + e.setBuffer(p.dims.buf, p.dims.off, 4); + e.setBuffer(plain_ho.buf, plain_ho.off, 5); + e.setBuffer(plain_xo.buf, plain_xo.off, 6); + e.setBuffer(plain_xs.buf, plain_xs.off, 7); + e.dispatchGroups(mtl.Size.of(1, p.groups, 1), mtl.Size.of(steer.threads, 1, 1)); + try p.rig.finish(pass); + return p.a.dupe(u8, p.rig.bytes(plain_xo, p.rows * width * 2)); + } + + /// The fused kernel's normalisation must be the plain norm kernel's normalisation of the row it steered. + pub fn normalisedRowInvariant(p: *Probe, pipe: mtl.Pipeline) !void { + if (p.rows == 0) return; + const plain = try p.plainRow(pipe); + defer p.a.free(plain); + // The normalised row, element for element: the two kernels sum the same squares in the same order. + const fused = p.rig.bytes(p.xo, p.rows * width * 2); + for (0..p.rows * width) |i| { + const a = c.fromBf16(std.mem.readInt(u16, fused[i * 2 ..][0..2], .little)); + const b = c.fromBf16(std.mem.readInt(u16, plain[i * 2 ..][0..2], .little)); + if (a == b) continue; + if (std.math.isNan(a) and std.math.isNan(b)) continue; + return error.FusedNormDiffersFromPlainNorm; + } + } + + /// The planted fault in the normalisation must show: the fused row must differ from the plain norm's row. + pub fn normalisationFaultCaught(p: *Probe, plain_pipe: mtl.Pipeline, fault_pipe: mtl.Pipeline) !void { + if (p.rows == 0) return; + // The faulty kernel first, so the plain norm reads the row it steered and only the normalisation differs. + try p.runWith(fault_pipe); + const plain = try p.plainRow(plain_pipe); + defer p.a.free(plain); + const fused = p.rig.bytes(p.xo, p.rows * width * 2); + for (0..p.rows * width) |i| { + const a = c.fromBf16(std.mem.readInt(u16, fused[i * 2 ..][0..2], .little)); + const b = c.fromBf16(std.mem.readInt(u16, plain[i * 2 ..][0..2], .little)); + if (a == b) continue; + if (std.math.isNan(a) and std.math.isNan(b)) continue; + return; + } + return error.NormalisationFaultNotCaught; + } +}; + +/// The suite's kernels: each variant's library, the probes and the kernels the gates run. +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + libs: [5]?mtl.Library = @splat(null), + norm_lib: ?mtl.Library = null, + norm_pipe: ?mtl.Pipeline = null, + fault_lib: ?mtl.Library = null, + fault_pipe: ?mtl.Pipeline = null, + contracted_pipe: ?mtl.Pipeline = null, + unguarded_pipe: ?mtl.Pipeline = null, + + /// The family's plain norm kernel, the one the fused kernel's normalisation must agree with. + fn normPipeline(s: *Suite) !mtl.Pipeline { + if (s.norm_pipe) |p| return p; + const text = try normSource(s.a); + defer s.a.free(text); + const lib = try mtl.Library.fromSource(s.device, text, mtl.CompileOptions.mlx()); + errdefer lib.deinit(); + const pipe = try mtl.Pipeline.init(s.device, lib, norm_symbol, false); + s.norm_lib = lib; + s.norm_pipe = pipe; + return pipe; + } + + /// The fused kernel with a fault in its normalisation: the check must catch it. + fn faultPipeline(s: *Suite) !mtl.Pipeline { + if (s.fault_pipe) |p| return p; + const text = try source(s.a, .norm); + defer s.a.free(text); + const lib = try mtl.Library.fromSource(s.device, text, mtl.CompileOptions.mlx()); + errdefer lib.deinit(); + const pipe = try mtl.Pipeline.init(s.device, lib, symbol, false); + s.fault_lib = lib; + s.fault_pipe = pipe; + return pipe; + } + + /// Each probe at each served shape: the fused row's normalisation is the plain norm's, and the planted fault shows. + fn normalisedRows(s: *Suite, seed: u64) !void { + const pipe = try s.normPipeline(); + const fault = try s.faultPipeline(); + for (s.probes.items) |p| { + // Its own launches: the gates free a kernel's buffers once they are done with it. + defer p.rig.reset(); + for (p.spec.served, 0..) |shape, i| { + if (!try p.prepare(shape, .random, seed +% i)) return error.RefusedServedShape; + try p.run(); + try p.normalisedRowInvariant(pipe); + try p.normalisationFaultCaught(pipe, fault); + } + } + std.debug.print("PASS normalised: the fused kernel's row is the plain norm's row, element for element, and the planted fault shows\n", .{}); + } + + /// Where products round, every element is the separately rounded add; the contracted add differs in each one. + fn orderedRows(s: *Suite, seed: u64) !void { + const contracted = try s.library(.contracted); + if (s.contracted_pipe == null) s.contracted_pipe = try mtl.Pipeline.init(s.device, contracted, symbol, false); + var checked: usize = 0; + for (s.probes.items) |p| { + defer p.rig.reset(); + for (ordered_strengths) |alpha| for (p.spec.served, 0..) |shape, i| { + if (!try p.load(shape, alpha, null, seed +% i)) return error.RefusedServedShape; + try p.run(); + if (try p.unordered() != 0) return error.SteeredAddNotSeparatelyRounded; + try p.runWith(s.contracted_pipe.?); + if (try p.unordered() != p.rows * width) return error.ContractedAddNotCaught; + checked += p.rows * width; + }; + } + std.debug.print("PASS ordered: {d} elements at alpha 0.1 and 0.3 are the separately rounded add, bit for bit;" ++ + " the contracted add differs in every one\n", .{checked}); + } + + /// Zero-direction and underflow zero-step rows keep `-0.0` bits; an unguarded add turns every element to `+0.0`. + fn zeroStepRows(s: *Suite, seed: u64) !void { + const unguarded = try s.library(.unguarded); + if (s.unguarded_pipe == null) s.unguarded_pipe = try mtl.Pipeline.init(s.device, unguarded, symbol, false); + const cases = [_]struct { alpha: f32, dir: f32 }{ + .{ .alpha = 1.0, .dir = 0.0 }, + .{ .alpha = 1e-25, .dir = 1e-25 }, + }; + var checked: usize = 0; + for (s.probes.items) |p| { + if (!std.mem.eql(u8, p.spec.name, "qwen27 steer")) continue; + defer p.rig.reset(); + for (cases) |zc| for (p.spec.served, 0..) |shape, i| { + if (!try p.load(shape, zc.alpha, .random, seed +% i)) return error.RefusedServedShape; + const n = p.rows * width; + const hb = p.rig.bytes(p.h, n * 2); + const rb = p.rig.bytes(p.residual, n * 2); + for (0..n) |j| { + std.mem.writeInt(u16, hb[j * 2 ..][0..2], 0x8000, .little); + std.mem.writeInt(u16, rb[j * 2 ..][0..2], 0x8000, .little); + } + const db = p.rig.bytes(p.dir, width * 4); + for (0..width) |j| std.mem.writeInt(u32, db[j * 4 ..][0..4], @bitCast(zc.dir), .little); + try p.run(); + const kept = p.rig.bytes(p.ho, n * 2); + for (0..n) |j| if (std.mem.readInt(u16, kept[j * 2 ..][0..2], .little) != 0x8000) { + return error.ZeroStepLostNegativeZero; + }; + try p.runWith(s.unguarded_pipe.?); + const dropped = p.rig.bytes(p.ho, n * 2); + for (0..n) |j| if (std.mem.readInt(u16, dropped[j * 2 ..][0..2], .little) != 0x0000) { + return error.UnguardedZeroStepNotCaught; + }; + checked += n; + }; + } + std.debug.print("PASS zero-step: {d} elements across zero-direction and underflow preserve -0.0 bit for bit;" ++ + " the unguarded add drops the sign bit in every one\n", .{checked}); + } + + fn library(s: *Suite, variant: Variant) !mtl.Library { + const at: usize = @backingInt(variant); + if (s.libs[at]) |l| return l; + const text = try source(s.a, variant); + defer s.a.free(text); + const lib = try mtl.Library.fromSource(s.device, text, mtl.CompileOptions.mlx()); + s.libs[at] = lib; + return lib; + } + + /// The entries `only` names, registered with the gates; with `gates`, the norm and add-order checks run here. + pub fn collect(s: *Suite, only: ?[]const u8, gates: bool, seed: u64) !void { + for (entries) |e| { + if (only) |o| if (std.mem.indexOf(u8, e.name, o) == null) continue; + try s.add(e); + } + if (gates and s.probes.items.len > 0) { + try s.normalisedRows(seed); + try s.orderedRows(seed); + try s.zeroStepRows(seed); + } + } + + fn add(s: *Suite, e: Entry) !void { + const lib = try s.library(e.variant); + const pipe = try mtl.Pipeline.init(s.device, lib, symbol, false); + errdefer pipe.deinit(); + try s.probes.ensureUnusedCapacity(s.a, 1); + try s.kernels.ensureUnusedCapacity(s.a, 1); + const p = try s.a.create(Probe); + errdefer s.a.destroy(p); + p.* = .{ .a = s.a, .rig = .{ .a = s.a, .device = s.device, .queue = s.queue }, .pipe = pipe }; + s.probes.appendAssumeCapacity(p); + s.kernels.appendAssumeCapacity(p.kernel(e)); + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |p| { + p.deinit(); + s.a.destroy(p); + } + s.probes.deinit(s.a); + for (s.libs) |l| if (l) |lib| lib.deinit(); + if (s.norm_lib) |lib| lib.deinit(); + if (s.norm_pipe) |pipe| pipe.deinit(); + if (s.fault_lib) |lib| lib.deinit(); + if (s.fault_pipe) |pipe| pipe.deinit(); + if (s.contracted_pipe) |pipe| pipe.deinit(); + if (s.unguarded_pipe) |pipe| pipe.deinit(); + } +}; diff --git a/zig/tests/contract/metal_qwen4_main.zig b/zig/tests/contract/metal_qwen4_main.zig new file mode 100644 index 00000000000..99ba50b85c0 --- /dev/null +++ b/zig/tests/contract/metal_qwen4_main.zig @@ -0,0 +1,51 @@ +//! Qwen4's Metal contract suites behind one hook: the QSA attention variants, the projections and GDN. +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const g = contract.gates; + +const qwen4_hc = @import("metal_qwen4_hc.zig"); +const qwen4_qsa_select = @import("metal_qwen4_qsa_select.zig"); +const qwen4_qsa_scores = @import("metal_qwen4_qsa_scores.zig"); +const qwen4_qsa_attn = @import("metal_qwen4_qsa_attn.zig"); +const qwen4_qsa_norm = @import("metal_qwen4_qsa_norm.zig"); +const qwen4_ple = @import("metal_qwen4_ple.zig"); +const qwen4_gdn = @import("metal_qwen4_gdn.zig"); + +pub const Suites = struct { + hc: *qwen4_hc.Suite, + qsa_select: *qwen4_qsa_select.Suite, + qsa_scores: *qwen4_qsa_scores.Suite, + qsa_attn: *qwen4_qsa_attn.Suite, + qsa_norm: *qwen4_qsa_norm.Suite, + ple: *qwen4_ple.Suite, + gdn: *qwen4_gdn.Suite, + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kernels: *std.ArrayList(g.Kernel), only: ?[]const u8) !Suites { + const hc = try qwen4_hc.Suite.create(a, device, queue, kernels, only); + errdefer hc.destroy(); + const qsa_select = try qwen4_qsa_select.Suite.create(a, device, queue, kernels, only); + errdefer qsa_select.destroy(); + const qsa_scores = try qwen4_qsa_scores.Suite.create(a, device, queue, kernels, only); + errdefer qsa_scores.destroy(); + const qsa_attn = try qwen4_qsa_attn.Suite.create(a, device, queue, kernels, only); + errdefer qsa_attn.destroy(); + const qsa_norm = try qwen4_qsa_norm.Suite.create(a, device, queue, kernels, only); + errdefer qsa_norm.destroy(); + const ple = try qwen4_ple.Suite.create(a, device, queue, kernels, only); + errdefer ple.destroy(); + const gdn = try qwen4_gdn.Suite.create(a, device, queue, kernels, only); + errdefer gdn.destroy(); + return .{ .hc = hc, .qsa_select = qsa_select, .qsa_scores = qsa_scores, .qsa_attn = qsa_attn, .qsa_norm = qsa_norm, .ple = ple, .gdn = gdn }; + } + + pub fn destroy(s: *Suites) void { + s.gdn.destroy(); + s.ple.destroy(); + s.qsa_norm.destroy(); + s.qsa_attn.destroy(); + s.qsa_scores.destroy(); + s.qsa_select.destroy(); + s.hc.destroy(); + } +}; diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index e08cc4eec0d..c196e8f4f2d 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -178,4 +178,4 @@ zig/src/native/qwen27_slots.zig 16aed3398b2857dac31f0166655bd4a084895bb65bd8d2d6 zig/src/core/lane_host.zig f613ab153238031b65bf59ec73902afa97b4d8d3e9ade49949b09707bb4df4a9 raw main #4937 scoring, learn and folded-memory behavior retained; #5040 idle weight release hooks ported; #5312: passes the prefill timestamp to the prompt-cache pressure report, decisions unchanged zig/src/core/lane_host_run.zig 72c287fd129c9154ddd647a9320363c0587cc0160fb009e62f7756fc317737c0 raw main #4937 scoring, learn and folded-memory behavior retained; #5040 idle weight release hooks ported zig/src/core/lane_rounds.zig aa2c7ed73eb271ca6630d2d860705c41889712883c24b515c5cca3828747fd94 raw main #4937 scoring, learn and folded-memory behavior retained; #5040 idle weight release hooks ported -zig/src/native/qwen27_served.zig 206b1b85adfb88a66cb282fd082ec5baaa2841dfb53acfc08b8069bac778ac99 raw main #4937 scoring, learn and folded-memory behavior retained; #5040 idle weight release hooks ported; #5188 (environment settings through the registry; accepted values and replies unchanged); #4158 startup margin and 128-row frame step +zig/src/native/qwen27_served.zig 8f8afa4aac99b70bdabe09ab3bd39fee9ec1085533defb589a51f61191051d1c raw main #4937 scoring, learn and folded-memory behavior retained; #5040 idle weight release hooks ported; #5188 (environment settings through the registry; accepted values and replies unchanged); #4158 startup margin and 128-row frame step; #1835 (glp) diff --git a/zig/tests/glp_check.zig b/zig/tests/glp_check.zig new file mode 100644 index 00000000000..80f16cd774b --- /dev/null +++ b/zig/tests/glp_check.zig @@ -0,0 +1,135 @@ +//! The GLP control vector container as the outside world sees it: the reader's view of a file, and a rewrite of it. +const std = @import("std"); +const glp = @import("glp"); + +const help = + \\tf-glp-check read FILE OUT.json OUT.bin the reader's view: the metadata, the layers and their numbers + \\tf-glp-check rewrite FILE OUT.gguf [--repo ID] [--revision REV] + \\ the file again through this writer + \\ + \\--repo and --revision re-stamp the checkpoint the file names, for weights published under another + \\name: the directions stay the same bytes, so only do it for a checkpoint with the same weights. + \\ + \\The binary sidecar holds the directions in ascending layer order, each one's fp32 payload as it + \\stands in the file, so another reader's numbers can be compared byte for byte. +; + +/// Why these arguments cannot run, in the words the tool prints; null when they can. +pub fn usageProblem(args: []const []const u8) ?[]const u8 { + if (args.len < 2) return "one of read or rewrite is required"; + const command = args[1]; + if (std.mem.eql(u8, command, "--help")) return null; + if (std.mem.eql(u8, command, "read")) { + return if (args.len == 5) null else "read takes FILE OUT.json OUT.bin"; + } + if (!std.mem.eql(u8, command, "rewrite")) return "the command is read or rewrite"; + if (args.len < 4) return "rewrite takes FILE OUT.gguf"; + var i: usize = 4; + while (i < args.len) : (i += 1) { + if (std.mem.eql(u8, args[i], "--repo") or std.mem.eql(u8, args[i], "--revision")) { + i += 1; + if (i >= args.len) return "the option needs a value"; + } else return "the option is --repo or --revision"; + } + return null; +} + +pub fn main(init: std.process.Init) !void { + const a = init.arena.allocator(); + const io = init.io; + const args = try init.minimal.args.toSlice(a); + if (args.len < 2 or std.mem.eql(u8, args[1], "--help")) { + try std.Io.File.stdout().writeStreamingAll(io, help ++ "\n"); + return; + } + if (usageProblem(args)) |problem| { + const line = try std.fmt.allocPrint(a, "tf-glp-check: {s}\n{s}\n", .{ problem, help }); + try std.Io.File.stdout().writeStreamingAll(io, line); + std.process.exit(2); + } + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, args[2], a, .limited(64 << 20)); + var why: glp.Why = .{}; + const vector = glp.read(a, bytes, &why) catch |err| { + if (err == error.OutOfMemory) return err; + const line = try std.fmt.allocPrint(a, "refused: {s}\n", .{why.text()}); + try std.Io.File.stdout().writeStreamingAll(io, line); + return error.BadVector; + }; + if (std.mem.eql(u8, args[1], "rewrite")) { + // The checkpoint the file names may be re-stamped: the same weights under another name. + var base_model = vector.base_model; + var base_revision = vector.base_revision; + var i: usize = 4; + while (i < args.len) : (i += 1) { + if (std.mem.eql(u8, args[i], "--repo")) { + i += 1; + if (i >= args.len) return error.MissingValue; + base_model = args[i]; + } else if (std.mem.eql(u8, args[i], "--revision")) { + i += 1; + if (i >= args.len) return error.MissingValue; + base_revision = args[i]; + } else return error.UnknownOption; + } + const out = try glp.write(a, .{ + .alpha = vector.alpha, + .hook_point = vector.hook_point, + .derived_at = vector.derived_at, + .base_model = base_model, + .base_revision = base_revision, + .method = vector.method, + .contrast = vector.contrast, + .publication = vector.publication, + .layers = vector.layers, + }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = args[3], .data = out }); + return; + } + if (!std.mem.eql(u8, args[1], "read")) return error.UnknownCommand; + + // The directions as bytes, in the order the file holds them. + var blob: std.ArrayList(u8) = .empty; + for (vector.layers) |l| { + for (l.dir) |v| try blob.appendSlice(a, &std.mem.toBytes(@as(u32, @bitCast(v)))); + } + var ids: std.ArrayList(u32) = .empty; + for (vector.layers) |l| try ids.append(a, l.id); + const receipt = try std.json.Stringify.valueAlloc(a, .{ + .alpha = vector.alpha, + .hook_point = vector.hook_point, + .derived_at = vector.derived_at, + .base_model = vector.base_model, + .base_revision = vector.base_revision, + .method = vector.method, + .contrast = vector.contrast, + .width = vector.width, + .sha256 = std.fmt.bytesToHex(vector.sha256, .lower), + .file_sha256 = std.fmt.bytesToHex(vector.file_sha256, .lower), + .transferred = vector.transferred, + .name = vector.publication.name, + .description = vector.publication.description, + .author = vector.publication.author, + .license = vector.publication.license, + .model_hint = vector.publication.model_hint, + .measured_effect = vector.publication.measured_effect, + .created = vector.publication.created, + .layers = ids.items, + .bytes = blob.items.len, + }, .{}); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = args[3], .data = receipt }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = args[4], .data = blob.items }); +} + +test "the checker refuses missing output arguments before reading a file" { + try std.testing.expect(usageProblem(&.{"tf-glp-check"}) != null); + try std.testing.expect(usageProblem(&.{ "tf-glp-check", "read" }) != null); + try std.testing.expect(usageProblem(&.{ "tf-glp-check", "read", "f" }) != null); + try std.testing.expect(usageProblem(&.{ "tf-glp-check", "rewrite", "f" }) != null); + try std.testing.expect(usageProblem(&.{ "tf-glp-check", "bogus", "f", "o" }) != null); + try std.testing.expect(usageProblem(&.{ "tf-glp-check", "read", "f", "o.json", "o.bin" }) == null); + try std.testing.expect(usageProblem(&.{ "tf-glp-check", "rewrite", "f", "o.gguf" }) == null); + try std.testing.expect(usageProblem(&.{ "tf-glp-check", "rewrite", "f", "o.gguf", "--repo", "id", "--revision", "rev" }) == null); + try std.testing.expect(usageProblem(&.{ "tf-glp-check", "rewrite", "f", "o.gguf", "--repo" }) != null); + try std.testing.expect(usageProblem(&.{ "tf-glp-check", "rewrite", "f", "o.gguf", "--bogus" }) != null); + try std.testing.expect(usageProblem(&.{ "tf-glp-check", "--help" }) == null); +} diff --git a/zig/tests/qwen27/run.zig b/zig/tests/qwen27/run.zig index 9537e173757..04a8f7cb210 100644 --- a/zig/tests/qwen27/run.zig +++ b/zig/tests/qwen27/run.zig @@ -48,6 +48,7 @@ fn emit(a: std.mem.Allocator, io: std.Io, dir: []const u8) !void { const filename = try std.fmt.allocPrint(a, "{s}{s}.metal", .{ name, if (xs) "" else "-no-xs" }); try write(a, io, dir, filename, text); }; + try write(a, io, dir, "norm_steer.metal", try q.norm_steer_gpu.source(a, 5120)); const shapes = [_][3]usize{ .{ 10240, 5120, 4 }, .{ 6240, 5120, 8 }, .{ 5120, 6144, 8 }, .{ 12288, 5120, 4 }, .{ 2048, 5120, 8 }, .{ 34816, 5120, 2 }, .{ 5120, 17408, 8 }, .{ 248320, 5120, 1 } }; for (shapes, 0..) |shape, i| { const text = try core_lane.source(a, .{ .n = shape[0], .k = shape[1], .sk = shape[2], .format = .{ .bits = 4, .group = 64 }, .precompute_sums = true, .cooperative = true });